Is this a bad shape to provide only a move constructor?

I would like to return a noncopyable object of type Foo from a function. This is basically a helper object that the caller uses to perform a set of actions, with a destructor to do some cleanup after the actions are completed.

Before rvalue links appeared, I would return shared_ptr<Foo> or something similar. With rvalue references, another option is to make the copy constructor and constructor private and have a single public constructor as the move constructor. Foo will look something like this:

 class Foo : boost::noncopyable { private: Foo( /* whatever the real ctor needs */ ); public: Foo( Foo && src ); // ... interesting stuff ... }; Foo a( SomethingThatReturnsFoo() ); // allowed Foo b; // error, no public default constructor Foo c( a ); // error, noncopyable Foo d = a; // error, noncopyable 

My question is whether this will be a bad form of doing it, or does it look reasonable. I can't think of any reason why this might cause problems or be difficult to read, but I'm still a little newbie when it comes to rvalue links, so there may be considerations that I don't think about.

+7
c ++ c ++ 11 rvalue-reference move-semantics move-constructor
source share
1 answer

This is not a bad form at all - consider objects like mutexes or cloud objects like unique_ptr. Unique_ptr is movable but not copyable, and it is part of the STL.

+9
source share

All Articles