我想知道我是否做得对。我有一个包含一些数据的类:
class Foo {
// ...
Type a_;
Type b_;
Type c_;
};以及一个不同的类,它执行其他操作,但使用class Foo构造。所以,我想像这样宣布一个人:
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&&);
};现在我需要创建一个Foo方法,它将返回Bar所需的数据成员的一个元组,我可以将它传递给Bar的ctor。我还为Tuple做了一个rvalue引用,因为除了通过class Bar之外,不再需要class Foo的数据成员了,那么当我可以移动数据时,为什么还要去复制数据呢?
因此,我在class Foo中创建了将返回Tuple的方法。特别是,我需要一个可以被使用rvalue引用的Bar ctor使用的函数。下列内容正确吗?
auto Foo::move_data() -> Tuple&& {
return std::move( Tuple(a_, b_, c_) );
}还是完全错了?(指出任何其他愚蠢的东西也会受到赞赏。当然,我遗漏了一些类型和其他不必要的细节。)
发布于 2015-01-26 03:35:57
不不是的。这是:
Tuple&& Foo::move_data() {
return std::move( Tuple(a_, b_, c_) );
}将您的元素复制到Tuple中,然后move Tuple本身..。不是你的元素。您要做的是将它们移动到Tuple中,然后按值返回:
Tuple Foo::move_data() {
return Tuple(std::move(a_), std::move(b_), std::move(c_) );
}发布于 2015-01-26 04:11:49
这在很大程度上取决于整个代码,但从您的问题描述来看,我的问题是为什么不将a、b和c放在自己的结构中?
class Abc {
Type a_;
Type b_;
Type c_;
};
class Foo {
// ...
Abc abc_;
int somethingNotInBar_;
};
class Bar {
Abc abc_;
AnotherType A_;
AnotherType B_;
// ...
public:
Bar(const ABC&);
};一些优点:
d,或者不再需要b了)。https://stackoverflow.com/questions/28144447
复制相似问题