C ++ lambda捕获问题(VS 2013) [英] C++ lambda capturing issue (VS 2013)

查看:128
本文介绍了C ++ lambda捕获问题(VS 2013)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在返回捕获对象的引用时遇到问题。

要捕获共享指针,我使用按值捕获。

如果我返回一个,则一切正常指针。

一旦函数必须返回一个引用,它就不起作用。

在下面的示例中,第一个lambda工作,第二个不工作。



这是一个错误吗?

我在第二种情况下做错了吗?



  #include   <   functional  >  
#include < memory >

int _tmain( int argc,_TCHAR * argv [])
{
// 编译时没有警告和工作
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()); // 确定



// 编译警告C4172:
// 返回本地变量或临时的地址
// 不起作用
std :: function< std :: string&( void )> FNC2;
{
std :: shared_ptr< std :: string> str( new std :: string( abcd< /跨度>));
fnc2 = [str]()
{
return * str;
};
}

std :: string& str2 = fnc2(); // 结果错误

返回 0 ;
}

解决方案

在第二个函数中使用返回对象的引用而析构函数杀死对象,而你只创建一个引用而不是返回对象的副本。



在第一个函数中,你返回对象并计算引用。



您需要更好地了解对象生命周期管理



学习它! ; - )

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?

#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;
}

解决方案

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! ;-)


这篇关于C ++ lambda捕获问题(VS 2013)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆