简体   繁体   中英

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.)

No it's not. This:

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

would copy your elements into a Tuple , and then move the Tuple itself... not your elements. What you want to do is move them into the Tuple , and then return it by value:

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

It highly depends on the overall code, but from your problem description my question would be why not put a, b and c together in their own structure?

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

Some advantages:

  • It you would save the trouble of resorting to tuples;
  • It would make the code easier to grasp (it's often more difficult to understand what a tuple is about, since names are lost in the process);
  • It would make modification easier (for that day you realize you also need d , or you don't need b anymore).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM