Difference in object construction using “X x(42)” and “X x = 42”?
-
25-05-2021 - |
문제
Let's say we have class X with defined constructor X(int value)
.
Is this semantically equivalent or not?
X x = 42;
X x(42);
I believe the difference will appear only if we add explicit keyword to constructor of X.
Otherwise compiler will reduce expression X x = 42;
to X x(42);
Please, correct me if I'm wrong.
해결책
The form
X x = 42;
requires that the constructor be non-explicit and that there be an accessible copy-constructor. The implementation is allowed to construct a temporary and copy it over, but no implementation I know of does that.
다른 팁
Semantically the two operations are different per the language in the specification, but the effective results after compilation are the same in the following circumstances:
- There is a single argument constructor for
X
that can take an integral-type and the argument type is not a non-const l-value reference - There is a single argument constructor for
X
where an integral-type can be converted to the argument type, and where the argument is again not a non-const l-value reference - In the case of #2, the constructor is not declared as
explicit
제휴하지 않습니다 StackOverflow