c++ - 为什么 CopyConstructible 定义提到 "rvalue expression of const T"?

标签 c++ constants language-lawyer copy-constructor

以下是 cppreference 的定义:

[ https://en.cppreference.com/w/cpp/named_req/CopyConstructible][1]

Requirements: The type T satisfies CopyConstructible if

The type T satisfies MoveConstructible, and Given

v, an lvalue expression of type T or const T or an rvalue expression of type const T u, an arbitrary identifier The following expressions must be valid and have their specified effects

Expression Post-conditions T u = v; The value of u is equivalent to the value of v. The value of v is unchanged

T(v) The value of T(v) is equivalent to the value of v. The value of v is unchanged.

我的问题如下:

v, an lvalue expression of type T or const T or an rvalue expression of type const T

我没理解这个“const T 类型的右值表达式”的部分内容?为什么这个“const T 类型的右值表达式”存在于 CopyConstructible 的定义中?有人可以举例说明吗? MoveConstructible 的定义(它是 CopyConstructible 的先决条件)已经包含了这个要求,不是吗?

最佳答案

没有,MoveConstructible的定义只关心非 const 右值表达式,因为你不能从 const 移出。

CopyConstructible 扩展了它以涵盖 T u = v;T(v); 的剩余可能性。

请注意,如果保留 rv 不变,仅复制类型仍然满足 MoveConstructible,因为“rv 的新值”涵盖了这一点> 未指定。”

举个例子

struct Foo {
    void Bar() { /* modify Foo somehow */ }
};

const Foo createFoo() { return {}; }

Foo foo = createFoo(); // Must copy, as the return value is const

这种构造出现在 C++11 之前的代码中,作者希望禁止像 createFoo().Bar(); 这样的构造,因为修改临时 Foo

关于c++ - 为什么 CopyConstructible 定义提到 "rvalue expression of const T"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51399471/

相关文章:

c++ - C 程序用不同的数字输出不同的值?

c++ - 奇怪的 const char* 行为

rust - 为什么固定大小的数组可以入栈,而str不可以?

c++ - 通过将其分配给 const std::tuple<int, int>& 来延长 std::tuple<int&,int> 的生命周期

c++ - C++ 编译器如何找到外部变量?

c++ - 在 C++ 中传递带有可变参数的函数指针作为参数

c++ - 使用扩张卷积在语义分割中进行上采样

c++ - "surprising"常量初始化因为定义顺序

c++ - 具有 C++ 重载函数的 SWIG 类型映射

c - 我无法确定为什么这个 C 程序会给我这个答案