I would like to return a noncopyable object of type Foo
from a function. This is basically a helper object which the caller will use to perform a set of actions, with a destructor to perform some cleanup after the actions are complete.
Before the advent of rvalue references, I would have returned a shared_ptr<Foo>
or something similar. With rvalue references, another option would be to make the constructor and copy constructor private, and have the only public constructor be a move constructor. Foo
would 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 it would be bad form to do this, or whether it looks reasonable. I can't think of any reason why this would cause issues or be difficult to read, but I'm still somewhat of a newbie when it comes to rvalue references, so there might be considerations I'm not thinking of.
The move constructor is much faster than a copy constructor because it doesn't allocate memory nor does it copy memory buffers.
A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying.
If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.
Move constructors of all the types used with STL containers, for example, need to be declared noexcept . Otherwise STL will choose copy constructors instead. The same is valid for move assignment operations.
This isn't bad form at all- consider objects like mutexes or scoped objects like unique_ptr. Unique_ptr is movable but not copyable and it's part of the STL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With