Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

So, how are basic classes written these days in C++11?

Update: I use MSVC10, which doesn't not give me default move-semantics

Let's say I want to create a regular class with a couple of non-pod members;

class Foo {
NonPodTypeA a_;
NonPodTypeB b_;
}

As usual I implement a copy-constructor, and an assignment operator in which I utilize the copy-constructor:

Foo(const Foo& other) : a_(other.a_), b_(other.b_) {}
Foo& operator=(const Foo& other) { 
  Foo constructed(other);
  *this = std::move(constructed);
  return *this;
}

Then I implement the move-constructor and move-assignment, which utilizes std::swap instead of std::move for all member's as they might be written before move-semantics were available, as move-semantics is implemented, I can omit implementing a swap member function:

Foo(Foo&& other) {
  ::std::swap(a_, other._a);
  ::std::swap(b_, other._b);
}
Foo& operator=(Foo&& other) { 
  ::std::swap(a_, other._a);
  ::std::swap(b_, other._b);
  return *this;
}

And here goes my question; can something here be done more general, assuming I don't know anything about the members?

For example, the move-constructor is not compatible with const declared members, but if I implement the move constructor as Foo(Foo&& other) : a_(std::move(other.a_)), b_(std::move(other.b_)){} I cant be sure classes without move-semantics are not copied? Can I utilize the move-constructor in the move-assignment in some clever way?

like image 980
Viktor Sehr Avatar asked Nov 26 '25 10:11

Viktor Sehr


1 Answers

Erm, do nothing. All those things are generated automatically for you1. The only time you need to write them by hand is when the class handles resources (and then you need to follow the Rule of Three). This is also exactly how it was before. The only difference now is that after you considered the Rule of Three you may want to implement the move members either for semantic (i.e. making move-only objects) or performance (moves are usually faster than copies) reasons.


1. MSVC 10 doesn't generate move constructors automatically. In that case you may want to write the move members yourself :(

like image 178
R. Martinho Fernandes Avatar answered Dec 01 '25 06:12

R. Martinho Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!