仅提供移动构造函数是一种不好的形式吗?
我想从函数返回一个 Foo
类型的不可复制对象。这基本上是一个辅助对象,调用者将使用它来执行一组操作,并使用析构函数在操作完成后执行一些清理操作。
在右值引用出现之前,我会返回一个shared_ptr
或类似的东西。对于右值引用,另一种选择是将构造函数和复制构造函数设为私有,并让唯一的公共构造函数是移动构造函数。 Foo
看起来像这样:
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
我的问题是这样做是否是不好的形式,或者看起来是否合理。我想不出这会导致问题或难以阅读的任何原因,但在右值引用方面我仍然是个新手,所以可能有一些我没有想到的考虑因素。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这根本不是坏形式 - 考虑像互斥体这样的对象或像 unique_ptr 这样的作用域对象。 Unique_ptr 可移动但不可复制,它是 STL 的一部分。
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.