[英]Is move elision guaranteed in this case?
Consider the following C++20 code;考虑以下 C++20 代码; assume T
to be non-movable and non-copyable:假设T
是不可移动和不可复制的:
struct Cell
{
Cell(T&& instance) : obj(std::move(instance)) {}
private:
T obj;
};
Cell cell(T{/* arguments */});
Is move elision guaranteed in the constructor of Cell
? Cell
的构造函数中是否保证了移动省略?
If T
were movable, would it be guaranteed that only the regular (non-move) constructor would be invoked?如果T
是可移动的,是否保证只会调用常规(非移动)构造函数?
Is move elision guaranteed in the constructor of Cell? Cell的构造函数中是否保证了移动省略?
No, the parameter instance
of Cell::Cell(T&& instance)
is of rvalue reference type T&&
, so there can be no move elision here.不, Cell::Cell(T&& instance)
的参数instance
是右值引用类型T&&
,所以这里不能有移动省略。 The parameter instance
must bind to the materialized temporary T{/* arguments */}
.参数instance
必须绑定到具体化的临时T{/* arguments */}
。 Then, std::move(instance)
will be used to direct initialize obj
.然后, std::move(instance)
将用于直接初始化obj
。
But note that obj(std::move(instance)
won't work because you're trying to initialize obj
with std::move(instance)
when T
is neither movable neither copyable. Demo但请注意obj(std::move(instance)
将不起作用,因为当T
既不可移动也不可复制时,您正在尝试使用std::move(instance)
初始化obj
。演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.