Zor*_*war 4 c++ move-semantics c++11
我想知道我是否正确行事.我有一个包含一些数据的类:
class Foo {
// ...
Type a_;
Type b_;
Type c_;
};
Run Code Online (Sandbox Code Playgroud)
还有一个不同的类,它可以用其他东西构建class Foo.所以,我认为这样的ctor声明:
class Bar {
Type a_;
Type b_;
Type c_;
AnotherType A_;
AnotherType B_;
// ...
public:
typedef std::tuple<Type, Type, Type> Tuple;
Bar(const Tuple&);
Bar(Tuple&&);
};
Run Code Online (Sandbox Code Playgroud)
我现在需要创建一个Foo方法,它将返回Bar需要的数据成员的元组,我可以传递给它Bar的ctor.我也做了一个rvalue参考,Tuple因为class Foo除了via之外不再需要那些数据成员了class Bar,所以为什么在我移动数据时还要复制数据呢?
所以,我创建的方法class Foo将返回a Tuple.特别是,我需要一个可以由Bar使用右值引用的ctor使用的方法.以下是否正确?
auto Foo::move_data() -> Tuple&& {
return std::move( Tuple(a_, b_, c_) );
}
Run Code Online (Sandbox Code Playgroud)
或者这完全错了?(指出其他任何愚蠢的东西也会受到赞赏.当然,我遗漏了一些typedef和其他不必要的细节.)
不,这不对.这个:
Tuple&& Foo::move_data() {
return std::move( Tuple(a_, b_, c_) );
}
Run Code Online (Sandbox Code Playgroud)
将你的元素复制到一个Tuple,然后move是Tuple自身...而不是你的元素.你有什么想要做的是它们移动到的Tuple,然后返回值是:
Tuple Foo::move_data() {
return Tuple(std::move(a_), std::move(b_), std::move(c_) );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |