这里发生了什么?我将结果分配给C ++ [英] What is going on here? I assign result to result in C++
问题描述
你能告诉我这里发生了什么吗?以及为什么可行?
Could you tell me what is going on here? And why it is possible?
std::make_unique<int>(1) = std::make_unique<int>(1);
我认为 make_unique
返回了r-值...
I thought that make_unique
returned an r-value...
编辑:
您能提供这种构造的一些有用示例吗?
Could you provide some useful example of this construction?
推荐答案
我认为make_unique的返回值是r值...
I thought that return of make_unique is r-value...
是。但是对于像 std :: unique_ptr< ...>
这样的类类型,赋值是对重载成员函数的调用。您可以将右值作为参数传递给函数。更具体地说,是在右值上调用成员函数。
It is. But for class types like std::unique_ptr<...>
, the assignment is a call to an overloaded member function. You can pass rvalues as arguments to functions. And more specifically, call member functions on rvalues.
例如,当您检查 std时:: bitset
,您会看到其引用
类型实际上是一个类类型。该类型的赋值运算符已重载。它接受 bool
,但实际上执行按位操作来操作 bitset
。
As an example, when you examine std::bitset
, you see that its reference
type is in fact a class type. The assignment operator for that type is overloaded. It accepts a bool
, but in fact performs a bit-wise operation to manipulate a flag in the packed memory of the bitset
.
它适用于 unique_ptr
右值,因为它已过载(并且是为其他类类型隐式生成的),而没有任何引用限定符。即
It works for unique_ptr
rvalues because it's overloaded (and is implicitly generated for other class types) without any ref-qualifiers. I.e.
unique_ptr& operator=( unique_ptr&& r ) noexcept;
...而不是...
... and not...
unique_ptr& operator=( unique_ptr&& r ) & noexcept;
// Can only be used on lvalues, no overload for rvalues
几乎没有收获。而且,隐式生成的值不可能只用于左值。许多代码(甚至早于C ++ 11的代码)都在rvalues上使用赋值,而没有对操作符进行ref限定。这样会破坏现有的代码库。
Which would have been for very little gain. And it's unlikely that the implicitly generated one would ever be for lvalues only. A lot of code (some that even predates C++11) uses assignment on rvalues, without ref-qualifying the operators. So that would break existing code bases.
这篇关于这里发生了什么?我将结果分配给C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!