gpt4 book ai didi

c++ - 基本类型的复制/分配

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:49 26 4
gpt4 key购买 nike

标准对基本类型的复制/赋值有何规定?

对于类类型,我们有复制构造函数、赋值运算符,它以右边作为引用(它必须是引用,否则我们有无限递归):

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

这是如何为基本类型定义的?

看这个例子:

const Foo foo;
Foo f = foo;

const int a = 2;
int b = a;

在这里,f = foo; odr-使用 foo,因为复制构造函数需要引用,对吗?如果基本类型的拷贝有一个引用参数,那么 b = a 也会 odr-use a。是这样吗?如果不是,如何处理?

最佳答案

我们可以追踪到它。从 [dcl.init] 开始。

(17.8) - Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression. Standard conversions will be used, if necessary, to convert the initializer expression to the cv-unqualified version of the destination type; no user-defined conversions are considered. If the conversion cannot be done, the initialization is ill-formed. When initializing a bit-field with a value that it cannot represent, the resulting value of the bit-field is implementation-defined.

这种情况下的标准转换是 a 上的左值到右值转换。但这不是 odr-use a。因为我们在 [basic.def.odr] 中看到

2 A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion to x yields a constant expression that does not invoke any non-trivial functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion is applied to e, or e is a discarded-value expression.

a 是一个常量表达式,上面用 a 替换 xex 表明它包含另一个一半的条件,所以它不是 odr-used。

关于c++ - 基本类型的复制/分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53429108/

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