仅提供移动构造函数是一种不好的形式吗?

发布于 2024-09-18 02:14:33 字数 800 浏览 4 评论 0原文

我想从函数返回一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铁憨憨 2024-09-25 02:14:33

这根本不是坏形式 - 考虑像互斥体这样的对象或像 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文