复制/分配基本类型 [英] Copy/assignment of fundamental types

查看:96
本文介绍了复制/分配基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准对基本类型的复制/分配有何看法?

What does the standard say about copy/assignment of fundamental types?

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

For class types, we have copy constructor, assignment operator, which takes the right hand side as a reference (it must be a reference, otherwise we had infinite recursion):

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

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

How does this defined for fundamental types?

看这个例子:

const Foo foo;
Foo f = foo;

const int a = 2;
int b = a;

在这里,f = foo; odr使用foo,因为复制构造函数需要引用,对吗?如果基本类型的副本具有参考参数,则b = a也将使用a.是这样吗如果没有,该如何处理?

Here, f = foo; odr-uses foo, as copy-constructor takes a reference, right?. If copy of fundamental types had a reference parameter, then b = a would odr-use a as well. Is it the case? If not, how is it handled?

推荐答案

我们可以跟踪它.从[dcl.init]开始.

We can trace it. Starting at [dcl.init].

(17.8)-否则,则为被初始化的对象 是初始化程序表达式的(可能是转换的)值. 如果需要,将使用标准转化来转换 初始化表达式表达为cv的非限定版本 目的地类型;不考虑用户定义的转换.如果 转换无法完成,初始化格式错误.什么时候 使用无法代表的值初始化位字段, 位字段的结果值是实现定义的.

(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上从左值到右值的转换.但这并不能使用a.我们在[basic.def.odr]

The standard conversion in this case would be the lvalue-to-rvalue conversion on a. But that doesn't odr-use a. For we see in [basic.def.odr]

2 变量 x 其名称显示为可能评估的表达式 除非应用左值到右值转换,否则 ex 会被 ex 使用 到 x 会产生一个常量表达式,该常量表达式不会调用任何非平凡的表达式 函数,并且如果 x 是一个对象,则 ex 是该集合的一个元素 表达式 e 的潜在结果,其中 左值到右值转换应用于 e ,或者 e 是丢弃值 表达.

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证明它拥有条件的另一半,因此不被滥用.

a is a constant expression and substitution of a for x and ex above demonstrates it holds the other half of the condition, so it's not odr-used.

这篇关于复制/分配基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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