我试图理解rvalue引用并移动C++ 11的语义.
这些示例之间有什么区别,哪些不会执行矢量复制?
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud)
std::vector<int>&& return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud)
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud) 我一直在试图解决C++ 11中的移动语义应该如何工作,而且我很难理解移动对象需要满足的条件.看看这里的答案并没有真正解决我的问题,因为无法看到如何以合理的方式将它应用于pimpl对象,尽管移动语义的参数非常适合pimpls.
我的问题最简单的说明涉及pimpl习语,如下所示:
class Foo {
std::unique_ptr<FooImpl> impl_;
public:
// Inlining FooImpl's constructors for brevity's sake; otherwise it
// defeats the point.
Foo() : impl_(new FooImpl()) {}
Foo(const Foo & rhs) : impl_(new FooImpl(*rhs.impl_)) {}
Foo(Foo && rhs) : impl_(std::move(rhs.impl_)) {}
Foo & operator=(Foo rhs)
{
std::swap(impl_, rhs.impl_);
return *this;
}
void do_stuff ()
{
impl_->do_stuff;
}
};
Run Code Online (Sandbox Code Playgroud)
现在,一旦我离开了,我该怎么办Foo?我可以安全地销毁移动的物体,我可以分配给它,这两者都绝对是至关重要的.但是,如果我尝试do_stuff使用我的Foo,它会爆炸.在我为我的定义添加移动语义之前Foo,每个人都Foo满足了它的不变性do_stuff,而现在已不再是这样了.目前似乎并没有被大量的替代品,或者说,因为(例如)将被移至距离Foo …