Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello, I have an issue with returning a reference of captured object.
To capture shared pointer I use capturing by value.
All works fine if I return a pointer.
Once function must return a reference, it does not work.
In following example first lambda works, second does not.

Is it a bug?
Am I doing wrong something in second case?

C++
#include <functional>
#include <memory>

int _tmain(int argc, _TCHAR* argv[])
{	
	// Compiles without warnings and works
	std::function<std::string*(void)> fnc1;
	{
		std::shared_ptr<std::string> str(new std::string("abcd"));
		fnc1 = [str]()
		{
			return str.get();
		};
	}

	std::string & str1 = *(fnc1()); // OK



	// Compiles with warning C4172: 
	//     returning address of local variable or temporary
	// Does NOT work
	std::function<std::string&(void)> fnc2;
	{
		std::shared_ptr<std::string> str(new std::string("abcd"));
		fnc2 = [str]()
		{
			return *str;
		};
	}

	std::string & str2 = fnc2(); // Wrong result

	return 0;
}
Posted

1 solution

in the second function use return the reference to the object and the destructor kills the object, while you only create a reference AND NOT A COPY of the returned object.

In the first function you return the object and a ref gets counted.

You need to better understand object life cycle managment.

Learn it! ;-)
 
Share this answer
 
v2
Comments
Dusan Paulovic 18-Jul-14 15:36pm    
Where in first case do you see a place where reference count is increased?
Reference count is increased only during capturing.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900