c++ copy initialization & direct initialization, the weird case

感情迁移 提交于 2019-12-05 06:12:20

You declared your copy constructor explicit (BTW, why?), which means that it can no longer be used for implicit copying of class objects. In order to use this constructor for copying you are now forced to use direct-initialization syntax. See 12.3.1/2

2 An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used.

The issue can be illustrated by the following much shorter example

struct A {
  A() {}
  explicit A(const A&) {}
};

int main() {
  A a;
  A b = a; // ERROR: copy-initialization
  A c(a); // OK: direct-initialization
}

This is what blocks all of your conversions from working, since all of them rely on copy-initialization, which in turns relies on implicit copying. And you disabled implicit copying.

Additionally, see the Defect Report #152 which covers this specific issue. Although I'm not sure what the consequences of the "proposed resolution" are supposed to be...

As you mentioned, gcc doesn't compile the following code.

struct A {
  A( int ) {}
  explicit A( A const& ) {}
};

int main() {
  A a = 2;
}

I think this isn't standard conformant according to current standard 8.5 p15.
However, as for your first case,

struct A {
  A( int ) {}
  explicit A( A const& ) {}
};

struct B {
  operator A() { return 2; }
};

int main() {
  B b;
  A a = b;
}

I'm not convinced that allowing this is conformant.
As you may know, return will invoke copying twice conceptually.
return 2; constructs an A implicitly from an int 2, and it is used to direct-initialize a temporal return-value(R).
However, should direct-initialization be applied to the second copying from R to a?
I couldn't find the wording in current standard which explicitly states that direct-initialization should be applied twice.
Since it is certain that this sequence spoils explicit specification in a sense, I'm not surprised even if compiler developers thought allowing this is a defect.

Let me make an unnecessary addition.
A compiler's non-conformant behaviour doesn't mean that the compiler has a defect directly.
The standard already has defects as defect reports show.
For example, the C standard doesn't allow the conversion from a pointer to an array of type T, to a pointer to an array of const T.
This is allowed in C++, and I think it should be allowed semantically in C similarly.
Gcc issues a warning about this conversion. Comeau issues an error, and doesn't compile.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!