看下面的示例,返回一个可选的UserName
- 一个可移动/可复制的类。
std::optional<UserName> CreateUser()
{
UserName u;
return {u}; // this one will cause a copy of UserName
return u; // this one moves UserName
}
int main()
{
auto d = CreateUser();
}
为什么
return {u}
会导致复制,而return u
会导致移动?这是相关的coliru示例:http://coliru.stacked-crooked.com/a/6bf853750b38d110 另一个案例(感谢@Slava的评论):
std::unique_ptr<int> foo()
{
std::unique_ptr<int> p;
return {p}; // uses copy of unique_ptr and so it breaks...
}
std::unique_ptr foo()
{
std::unique_ptr p;
return {p};
}
- Slava