有一个类是可复制但不可移动的任何用例? [英] Are there any use cases for a class which is copyable but not movable?

查看:191
本文介绍了有一个类是可复制但不可移动的任何用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读此最新问题 by @Mehrdad,其中类应该是不可移动,因此不可复制,我开始怀疑是否有一个类可以复制但不移动<强>。从技术上讲,这是可能的:

After reading this recent question by @Mehrdad on which classes should be made non-movable and therefore non-copyable, I starting wondering if there are use cases for a class which can be copied but not moved. Technically, this is possible:

struct S
{
    S() { }
    S(S const& s) { }
    S(S&&) = delete;
};

S foo()
{
    S s1;
    S s2(s1); // OK (copyable)
    return s1; // ERROR! (non-movable)
}

虽然 S 有一个复制构造函数,它显然不会对 CopyConstructible 概念建模,因为这又是 MoveConstructible 概念,其需要存在(未删除的)移动构造函数(见第17.6.3.1/2节,表21)。

Although S has a copy constructor, it obviously does not model the CopyConstructible concept, because that is in turn a refinement of the MoveConstructible concept, which requires the presence of a (non-deleted) move constructor (see § 17.6.3.1/2, Table 21).

上面的 S 类型是否有用例,可复制, strong> CopyConstructible 和不可移动?如果没有,为什么不禁止在同一个类中声明复制构造函数删除的move构造函数

Is there any use case for a type like S above, which is copyable but not CopyConstructible and non-movable? If not, why is it not forbidden to declare a copy constructor and a deleted move constructor in the same class?

推荐答案

假设你有一个类,它不是更便宜的移动,而不是复制(也许它包含 std :: array

Suppose you have a class that is no cheaper to move than it is to copy (perhaps it contains a std::array of a POD type).

在功能上,你应该使它MoveConstructible,使 S x = std :: move(y); 表现得像 S x = y; ,这就是为什么CopyConstructible是MoveConstructible的子概念。通常如果你没有声明任何构造函数,这个只是工作。

Functionally, you "should" make it MoveConstructible so that S x = std::move(y); behaves like S x = y;, and that's why CopyConstructible is a sub-concept of MoveConstructible. Usually if you declare no constructors at all, this "just works".

在实践中,我想你可能想暂时移动构造函数,以便通过移动 S 的实例来检测您的程序中是否有任何代码比实际更有效。 对我来说,似乎过多禁止。在完成的代码中执行良好的界面设计不是标准的工作: - )

In practice, I suppose that you might want to temporarily disable the move constructor in order to detect whether there is any code in your program that appears more efficient than it really is, by moving instances of S. To me it seems excessive to forbid that. It's not the standard's job to enforce good interface design in completed code :-)

这篇关于有一个类是可复制但不可移动的任何用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆