Krystian S
Krystian S

Reputation: 1616

Direct initialization with conversion functions

This question is almost identical to Conversion operator in direct-initialization, however, this is about something I noticed in implementations.

Consider the following:

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

struct B { operator A(); };

void f() 
{
 B b;
 A a(b);
}

My reading of the standard says that because this direct-initialization, where the source and destination types differ, only constructors are considered. The constructor A(A&&) is selected, and the parameter is bound to the result the conversion function, yielding a total of two calls: operator A(), A(A&&), as [dcl.init]/17.6.2.1 is the only sub clause that would apply here.

However, this is not the behavior displayed by gcc, msvc, and clang, or icc which all say that only operator A() is called. Am I correct to assume that this is just compiler optimization?

I see no reason for the converting constructor not to be used here solely, other than the fact that I cannot find any wording that describes this behavior.

Upvotes: 1

Views: 80

Answers (1)

It's essentially all the aforementioned compilers going ahead and implementing the direction in CWG Issue 2327. You are correct that there is currently no wording to allow the behavior you observe. But as the issue notes, it'd be really good if there was.

Coming at the exact woding for it is tricky however, so the issue is still in a "drafting" stage. But compilers can and do implement the copy elision..

Upvotes: 1

Related Questions