Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad form 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 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.

like image 225
Charlie Avatar asked Sep 06 '10 16:09

Charlie


People also ask

Is move constructor faster than copy constructor?

The move constructor is much faster than a copy constructor because it doesn't allocate memory nor does it copy memory buffers.

Why do we use move constructor?

A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying.

Are move constructors automatically generated?

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.

Should move constructor be Noexcept?

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.


1 Answers

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.

like image 126
Puppy Avatar answered Nov 01 '22 03:11

Puppy