gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:34:03 24 4
gpt4 key购买 nike

以下是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com