libs/local_function/test/return_assign.cpp uses a dangling reference:
#include<boost/local_function.hpp>
#include<boost/function.hpp>
#include<boost/detail/lightweight_test.hpp>
#include<iostream>//[return_assignvoidcall1(boost::function<int (int) > f) { BOOST_TEST(f(1) == 5); }
voidcall0(boost::function<int (void)> f) { BOOST_TEST(f() == 5); }
boost::function<int (int, int)> linear(constint& slope) {
intBOOST_LOCAL_FUNCTION(const bind& slope,
int x, default1, int y, default2) {
return x + slope * y;
} BOOST_LOCAL_FUNCTION_NAME(lin)
boost::function<int (int, int)> f = lin; // Assign to local variable.BOOST_TEST(f(1, 2) == 5);
call1(lin); // Pass to other functions.call0(lin);
return lin; // Return.
}
voidcall(void) {
boost::function<int (int, int)> f = linear(2); // create temporary, bind reference to temporaryBOOST_TEST(f(1, 2) == 5); // !!!!!!!!!!!!!!!!!!!!!!!! use the reference
}
//]intmain(void) {
call();
returnboost::report_errors();
}changing the target from temporary to local variable can let the test fail:
#include<boost/local_function.hpp>
#include<boost/function.hpp>
#include<boost/detail/lightweight_test.hpp>
#include<iostream>//[return_assignvoidcall1(boost::function<int(int) > f) { BOOST_TEST(f(1) == 5); }
voidcall0(boost::function<int(void)> f) { BOOST_TEST(f() == 5); }
boost::function<int(int, int)> linear(constint& slope) {
intBOOST_LOCAL_FUNCTION(const bind & slope,
int x, default1, int y, default2) {
return x + slope * y;
} BOOST_LOCAL_FUNCTION_NAME(lin)
boost::function<int(int, int)> f = lin; // Assign to local variable.BOOST_TEST(f(1, 2) == 5);
call1(lin); // Pass to other functions.call0(lin);
return lin; // Return.
}
voidcall1(void) {
boost::function<int(int, int)> f = linear(2);
BOOST_TEST(f(1, 2) == 5); // !!!!!!!!!!!!!!!!!!!!!!!! test passed, although dangling reference
}
voidcall2(void) {
int a = 2;
boost::function<int(int, int)> f = linear(a);
a = 3;
BOOST_TEST(f(1, 2) == 5); // !!!!!!!!!!!!!!!!!!!!!!!! test failed
}
//]intmain(void) {
call1();
call2();
returnboost::report_errors();
}
libs/local_function/test/return_assign.cpp uses a dangling reference:
changing the target from temporary to local variable can let the test fail: