开发者

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开发者_如何学Python be considerations I'm not thinking of.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜