[英]extend scope of pass by ref object for std::thread
To demonstrate the problem, let me present a short code - 为了演示这个问题,让我给出一个简短的代码-
void someMethod() {
// CustomType obj;
const auto obj = getCustomTypeObj();
std::thread([](customType &obj) {
// some delay
obj.doSomething();
obj.close();
// can now be destructed
}).detach();
// similarly for std::async
std::async(std::launch::async, [](customType &obj){
obj.doSomething();
obj.close();
}
// there might not be any use of obj here
// should not be destructed here because std::thread might not get it.
}
In above code, an CustomType
type object is constructed for which copy constructor is deleted. 在上面的代码中,构造了一个CustomType
类型对象,为其删除了副本构造函数。 So I must pass it by reference everywhere, or create it from scratch in relevant scope. 因此,我必须在任何地方通过引用传递它,或者在相关范围内从头开始创建它。 However for 1 scenario I'm currently dealing with, it is not quite possible to create it in relevant scope which is inside std::thread
's execution method. 但是,对于我目前正在处理的1种情况,不可能在std::thread
的执行方法内的相关范围内创建它。
What I'm afraid of is obj
might be destructed before std::thread
even completes its job and then I've no idea what's going to happen. 我担心的是obj
可能在std::thread
甚至完成其工作之前就被破坏了,然后我不知道会发生什么。 So how should I solve this problem of extending it's scope to std::thread's lambda. 因此,我该如何解决将其范围扩展到std :: thread的lambda的问题。
Btw your code is incorrect, you do not pass your object, so your code should be instead: 顺便说一句,您的代码不正确,您没有传递对象,因此您的代码应改为:
auto obj = getCustomTypeObj();
std::thread([](customType &obj) {
// some delay
obj.doSomething();
obj.close();
// can now be destructed
}, std::ref( obj ) ).detach();
To avoid issue with object lifetime pass your object to the lambda or function by value and move your object there: 为避免对象生存期出现问题,请按值将对象传递给lambda或函数,然后将对象移动到该位置:
auto obj = getCustomTypeObj();
std::thread([](customType arg) { // note by value, not reference
// some delay
arg.doSomething();
arg.close();
// arg will be destroyed here
}, std::move( obj ) ).detach(); // object moved
now lambda or function owns that object and it will be destroyed at the end of the function. 现在,lambda或函数拥有该对象,并且该对象将在函数末尾销毁。 Here is the live example , I just used std::unique_ptr
there instead of customType
as type that has copying disabled to validate that moving works. 这是一个实时示例 ,我只是在那里使用std::unique_ptr
而不是customType
作为已禁用复制以验证移动有效的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.