Is the following code really dangerous? doSmth returns object of vector, which should be copied from cont(doSmth) and then stored in a stack in the scope of function test. Thus, I believe that it will be desctructed only after returning from test.
struct MyData
{
double m_i;
};
std::vector<MyData> doSmth()
{
std::vector<MyData> cont(10);
return cont;
}
void test()
{
MyData& oneElement = doSmth()[0];
std::cout << oneElement.m_i << std::endl;
}
Yet valgrind thinks differently:
Invalid read of size 8
<line 1 in test function oneElement>
Address 0x101281db8 is 8 bytes inside a block of size 72 free'd
std::vector<BlockInfo, std::allocator<BlockInfo> >::~vector() (stl_vector.h:314)
<line 2 in test function>
Is it a problem in my logic or valgrind lies?
The return value is destroyed at the end of the full expression, i.e. at the first semicolon in the function
test. At that point,oneElementbecomes a dangling reference.You can prolong the lifetime of the return value by binding it to a const reference:
In the above case, the return value is destroyed at the end of the function.