0

One can quickly make a type noncopyable by inheriting boost::noncopyable_::noncopyable. Is there anything similar for preventing a type from being moveable?

isekaijin
  • 19,076
  • 18
  • 85
  • 153
  • You may be able to do this by making the move constructor private. Why would you need to do this, though? – Taywee Jun 01 '13 at 01:34
  • @Taywee: To guarantee some classes in my program cannot possibly be used in an improper way. These classes have a fairly complicated system of "ownership relations", which would be completely broken if I allowed move semantics. – isekaijin Jun 01 '13 at 01:47
  • I see. Keep in mind that many container types internally use move construction, like vectors, so those will also be off-limits. – Taywee Jun 01 '13 at 02:08

1 Answers1

1

If you declare a copy constructor but not a move constructor, no move constructor will be generated. Same for assignment. So:

struct not_movable {
    not_movable(const not_movable&) = default;
    not_movable& operator=(const not_movable&) = default;
};
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • In c++11 you may also explicitly delete the move constructor: `not_movable(const not_movable&&) = delete;` – Taywee Jun 01 '13 at 02:05
  • 1
    Obviously, I didn't intend for the const to be there: `not_movable(not_movable&&) = delete;` – Taywee Jun 01 '13 at 02:12
  • I cannot make a (meaningful) copy constructor/assignment pair. My classes already have noncopyable members (e.g., a `std::map`), and that is why I only care about making it nonmoveable. – isekaijin Jun 01 '13 at 03:22
  • In that case, either explicit move constructor deletion or a private move constructor should be sufficient. – Taywee Jun 01 '13 at 03:29
  • 1
    @Taywee - do **not** delete the move constructor. You'll get **very** surprising results. `not_movable f(); not_movable nm = f();` That last statement is an error; it does **not** use the copy constructor, but tries to use the deleted move constructor. – Pete Becker Jun 01 '13 at 16:28
  • @EduardoLeón - then simply declaring but not defining the copy constructor, just as Boost's `noncopyable` does, will take care of things. Declaring the copy constructor suppresses the compiler-generated move constructor. – Pete Becker Jun 01 '13 at 16:29
  • @Pete - You are correct. Thank you for informing me. I wasn't aware of the potentially disastrous effects of constructor deletion. More info: http://stackoverflow.com/q/13703186/1362309 - http://stackoverflow.com/q/14640366/1362309 - http://stackoverflow.com/q/16703798/1362309 – Taywee Jun 04 '13 at 11:31
  • @Taywee - it's high on my list because I just came across it in some code that I wrote. The interaction between `= delete` and move constructors is not intuitive. – Pete Becker Jun 04 '13 at 17:29