Вопрос

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