[C++] lambda, capture by value 주의사항

capture by value 가 lambda 식에 언급된 외부 변수의 값을 무조건 복사한다고 생각하면, 잘못된 코드를 만들 수 있다. 아래 코드와 같이 m_value 에 대해 capture by value 를 했다고 생각하지만

class BadClosureMaker
{
public:
	BadClosureMaker() : m_value(2012) {}

	std::function<int (void)> CreateClosure()
	{
		auto f = [=](void)
		{
			return m_value;
		};
		return f;
	}

private:
	int m_value;
};

실제로는 m_value를 capture 한 것이 아니라 BadClosureMaker 의 this 를 capture 한다. 만약 CreateClosure 에 의해 생성된 closure가 사용되기 전에 BadClosureMaker 가 delete 된다면, 잘못된 값에 접근한다.

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다