简体   繁体   English

C ++:传递std :: unique_ptr(move-only type)rvalue作为参数时复制elision

[英]C++: Copy elision when passing std::unique_ptr (move-only type) rvalue as parameter

I'm able to pass a std::unique_ptr rvalue as a parameter to a function like below because of copy elision. 由于copy elision,我能够将std::unique_ptr rvalue作为参数传递给下面的函数。 Is the copy guaranteed to be elided by the C++11 standard or can this fail to compile on some implementations? 是否保证C ++ 11标准可以省略该副本,或者在某些实现中无法编译?

void take_unique_ptr_by_value(std::unique_ptr<int> sp) {
  cout << "Value is " << *sp.get() << std::endl;
}
// I am able to call the function above like this:
take_unique_ptr_by_value(std::make_unique<int>(3));

because of copy elision 因为复制省略

No, it is because of move constructor . 不,这是因为移动构造函数

In addition, copy elision is just a optimization and still requires the code to be valid. 此外,复制省略只是一种优化,仍然要求代码有效。 So 所以

struct S
{
    S() = default;
    S(const S&) = delete;
    S(S&&) = delete;
};

S s = S(); // Won't compile prior C++17

C++17 introduces "guarantied copy elision" (in some contexts) which remove this constraint. C ++ 17引入了“保证副本省略”(在某些情况下),它消除了这种约束。

More details on copy_elision's doc 有关copy_elision文档的更多详细信息

To piece together some of the answers more explicitly as @Jarod42 mentioned even if copy elision were to take place the copy/move constructor being elided still has to exist. 将@ Jarod42提到的一些答案更明确地拼凑在一起,即使要进行复制省略,仍然必须存在被删除的复制/移动构造函数。 Secondly, what I was forgetting is that the parameter I'm passing in is an rvalue so it will invoke the move constructor if it needs to be "copied". 其次,我忘记的是我传入的参数是一个右值,因此如果需要“复制”它将调用移动构造函数。 So copy elision or not the example code is correct because std::unique_ptr has a move constructor and I am passing in an rvalue. 所以复制elision或不是示例代码是正确的,因为std::unique_ptr有一个移动构造函数,我传入一个右值。 This other answer is pretty comprehensive. 这个答案非常全面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM