c++ - lambda: should capturing const reference by reference yield undefined behaviour? -
i found nasty bug in code because captured const reference string reference. time lambda run original string object long gone , referenced value empty whereas purpose contains value of original string, hence bug.
what baffles me did not invoke crash @ runtime: after all, shouldn't undefined behaviour since afaik there dangling reference? when looking @ id under debugger, doesn't garbage constructed empty string.
here's test case; prints empty line:
typedef std::vector< std::function< void() > > functions; void addfunction( const std::string& id, functions& funs ) { funs.push_back( [&id] () { //the type of id const std::string&, there //is no object reference. ub? std::cout << id << std::endl; } ); } int main() { functions funs; addfunction( "id", funs ); funs[ 0 ](); }
undefined behavior means there no requirement should happen. there no requirement should crash. whatever memory dangling reference points at, there's no reason shouldn't contain looks empty string, , it's plausible destructor of string
leaves memory in state.
Comments
Post a Comment