views:

139

answers:

1

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.

+9  A: 

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.

DeadMG