问题
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?
Look at this example:
const Foo foo;
Foo f = foo;
const int a = 2;
int b = 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?
回答1:
We can trace it. Starting at [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.
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 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
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.
来源:https://stackoverflow.com/questions/53429108/copy-assignment-of-fundamental-types