다음 예제에서 람다 식을 사용하여 참조 또는 값으로 변수를 캡처 할 때의 의미를 이해하려고합니다.람다 캡쳐 표현식에서 '&'또는 '='?
/** Encapsulates the private implementation details of Thread. */
struct Thread::Impl
{
public:
Impl() : m_queue(), m_thread()
{
}
private:
Impl(const Impl&);
const Impl& operator=(const Impl&);
void run()
{
// do some work
}
std::unique_ptr<std::thread> m_thread;
friend class Thread;
};
Thread::Thread() : m_impl(new Impl())
{
// start the thread
// ************************************
// '=' or '&' in the the capture block?
// ************************************
m_impl->m_thread = std::unique_ptr<std::thread>(new std::thread([&]{ m_impl->run(); }));
}
는 상관없이 내가 캡처 블록에 &
또는 =
사용 여부 위의 코드는 확인을 작동합니다. 그래서 내가 사용해야합니까?
[&]
을 사용하는 경우 m_impl
이 참조로 캡처됩니다. 맞습니까?
[=]
m_impl
값으로 캡처 한 경우 맞습니까? 그러나 나는 그것이 왜 컴파일되는지 이해하지 못한다. 그것의 사본을 만드는 것은 무엇입니까? Impl에 대한 복사 매개 변수가 비활성화되었습니다.
왜'unique_ptr'에'std :: thread'를 저장하고 있습니까? 이미 움직일 수 있습니다.'std :: thread'를 직접 사용하고 힙 할당을 피할 수 있습니다. –
나는 Herb Sutter의이 예제를 보았고 그는 나보다 잘 알고 있었기 때문에 - http://www.drdobbs.com/article/print?articleId=225700095&siteSectionName=parallel – ksl
허브가 생각하고있는 것이 무엇인지 모르겠지만 'thd = unique_ptr ( 새 스레드 (bind (& Active :: Run, this)));는 완전히 난센스입니다. 'unique_ptr'이나'bind'를 사용하지 않고 단순히'thd = std :: thread (& Active :: Run, this)'이어야합니다. –