c++ - 为什么具有非常量复制构造函数的类不被视为可复制构造?

标签 c++ copy-constructor

给定

struct Foo 
{
    Foo(Foo&) {} 
};

std::is_copy_constructible<Foo>::valuefalse

Foo 具有有效的复制构造函数:来自 draft n4659:

15.8.1 Copy/move constructors [class.copy.ctor]
1
A non-template constructor for class X is a copy constructor if its first parameter is of type X& , const X& ,
volatile X& or const volatile X& , and either there are no other parameters or else all other parameters
have default arguments (11.3.6). [Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.

但是is_copy_constructible测试 is_constructible_v<T, const T&> (const) 根据标准。

为什么具有非常量复制构造函数的类不被视为可复制构造?

最佳答案

虽然这确实是一个有效的复制构造函数,is_copy_constructible type-trait 被定义为给出与 is_constructible_v<T, const T&> 相同的结果,因为它旨在对应于 CopyConstructible标准也定义了这个概念。

[utility.arg.requirements]/1它说

The template definitions in the C++ standard library refer to various named requirements whose details are set out in Tables 20–27. In these tables, T is an object or reference type to be supplied by a C++ program instantiating a template;[...] and v is an lvalue of type (possibly const) T or an rvalue of type const T.

CopyConstructible 概念在 Table 24 中定义作为

Table 24 — CopyConstructible requirements (in addition to MoveConstructible)
Expression     Post-condition
T u = v;           the value of v is unchanged and is equivalent to u
T(v)                 the value of v is unchanged and is equivalent to T(v)

因此,由于您的对象不能从 const Foo 构造左值,这是 CopyConstructible 的要求之一, 它不被认为是这样。

关于c++ - 为什么具有非常量复制构造函数的类不被视为可复制构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43606777/

相关文章:

c++ - 在 C++98 中实现移动构造函数和移动赋值运算符以获得更好的性能

c++ - 使用另一个(现有)对象创建新对象时会发生什么?

c++ - 传递通用函数以使用梯形规则进行数值积分

c++ - 使用 boost 正则表达式匹配二进制数据

c++ - 创建对象的拷贝

c++ - 通过删除复制构造函数等按值(无指针)在 C++ <vector> 中存储具有相同基类的对象

c++ - 复制构造函数首先复制指针,然后取消引用它以获得 "deep"拷贝

c++ - vtk 图表 - 如何在轴线末端绘制轴标签?

c++ - 在编译时检查 tr1 数组的大小

c++ - 使用 QAbstractItemModel (C++) 支持多重添加/删除(以及撤消/重做)