C++ 唯一指针的复制语义
Copy semantics for C++ unique pointer
我这样写有没有问题:
Try<std::unique_ptr<int> > some_function() {
std::unique_ptr<int> s(new int(2));
return s;
}
是否调用了复制构造函数?我应该使用 std::move 吗?
std::unique_ptr
doesn't have a copy constructor. What you're doing there is the same as assigning with a unique_ptr: 指针被移动。 (虽然在某些情况下你必须显式 move()
指针,否则你会得到一个编译错误;但如果编译器没有报错,那么它会悄悄地移动指针)
在 return 语句中,可以执行重载决策,就好像 return 语句中的 id-expression 指定了一个右值:
When the criteria for elision of a copy/move operation are met, [..], or when the expression in a return statement is a (possibly
parenthesized) id-expression that names an object with automatic storage duration declared in the body [..], overload resolution
to select the constructor for the copy is first performed as if the object were designated by an rvalue.
因此您的案例确实符合 NRVO 条件,因为 s
是在函数主体中声明的,因此 std::move()
不是必需的,因为重载解析可以将 s
视为右值。
请注意,如果您的编译器不支持在 return 表达式的类型不支持时将 s
视为右值的重载决议的第一阶段,则可能仍需要 std::move()
没有与函数的 return 类型相同的 cv-unqualified 类型。 clang but not gcc. More info in this thread.
的主干版本似乎就是这种情况
我这样写有没有问题:
Try<std::unique_ptr<int> > some_function() {
std::unique_ptr<int> s(new int(2));
return s;
}
是否调用了复制构造函数?我应该使用 std::move 吗?
std::unique_ptr
doesn't have a copy constructor. What you're doing there is the same as assigning with a unique_ptr: 指针被移动。 (虽然在某些情况下你必须显式 move()
指针,否则你会得到一个编译错误;但如果编译器没有报错,那么它会悄悄地移动指针)
在 return 语句中,可以执行重载决策,就好像 return 语句中的 id-expression 指定了一个右值:
When the criteria for elision of a copy/move operation are met, [..], or when the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body [..], overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
因此您的案例确实符合 NRVO 条件,因为 s
是在函数主体中声明的,因此 std::move()
不是必需的,因为重载解析可以将 s
视为右值。
请注意,如果您的编译器不支持在 return 表达式的类型不支持时将 s
视为右值的重载决议的第一阶段,则可能仍需要 std::move()
没有与函数的 return 类型相同的 cv-unqualified 类型。 clang but not gcc. More info in this thread.