dimanche 25 janvier 2015

move class data members (C++)

I want to know if I'm doing this right. I have a class that holds some data:



class Foo {
// ...
Type a_;
Type b_;
Type c_;
};


And a different class that does something else, but is constructed using class Foo. So, I reckon declare a ctor like this:



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&&);
};


I now need to create a Foo method that will return a tuple of the data members that Bar needs, which I can pass to Bar's ctor. I also make a rvalue reference for Tuple because those data members of class Foo will not be needed anymore except via class Bar, so why bother copying data when I can move it?


So, I create methods in class Foo that will a return a Tuple. In particular, I need one that can be used by the Bar ctor that uses an rvalue reference. Is the following correct?



auto Foo::move_data() -> Tuple&& {
return std::move( Tuple(a_, b_, c_) );
}


Or is this completely wrong? (Pointing out anything else stupid will also be appreciated. Of course, I've left out some typedefs and other unnecessary details.)


Aucun commentaire:

Enregistrer un commentaire