문제

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:

  1. 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
  2. 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
  3. In the case of #2, the constructor is not declared as explicit
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top