Title
Weighting of conversion functions in direct-initialization
Status
nad
Section
12.2.4.2.3 [over.ics.user]
Submitter
Steve Adamczyk

Created on 2000-09-05.00:00:00 last changed 26 months ago

Messages

Date: 2001-10-15.00:00:00

Notes from 10/01 meeting:

It turns out that there is existing practice both ways on this issue, so it's not clear that it is "broken". There is some reason to feel that something that looks like a "constructor call" should call a constructor if possible, rather than a conversion function. The CWG decided to leave it alone.

Date: 2022-02-18.07:47:23

Suggested resolution:

In a direct-initialization overload resolution case, if the candidate function being called is a copy constructor and its argument (after any implicit conversions) is a temporary that is the return value of a conversion function, and the temporary can be optimized away, the cost of the argument match for the copy constructor should be considered to be the cost of the argument match on the conversion function argument.

Date: 2022-02-18.07:47:23

There is a moderately serious problem with the definition of overload resolution. Consider this example:

    struct B;
    struct A {
        A(B);
    };
    struct B {
        operator A();
    } b;
    int main() {
        (void)A(b);
    }

This is pretty much the definition of "ambiguous," right? You want to convert a B to an A, and there are two equally good ways of doing that: a constructor of A that takes a B, and a conversion function of B that returns an A.

What we discover when we trace this through the standard, unfortunately, is that the constructor is favored over the conversion function. The definition of direct-initialization (the parenthesized form) of a class considers only constructors of that class. In this case, the constructors are the A(B) constructor and the (implicitly-generated) A(const A&) copy constructor. Here's how they are ranked on the argument match:

A(B) exact match (need a B, have a B)
A(const A&) user-defined conversion (B::operator A used to convert B to A)

In other words, the conversion function does get considered, but it's operating with, in effect, a handicap of one user defined conversion. To put that a different way, this problem is a problem of weighting, not a problem that certain conversion paths are not considered.

I believe the reason that the standard's approach doesn't yield the "intuitive" result is that programmers expect copy constructor elision to be done whenever reasonable, so the intuitive cost of using the conversion function in the example above is simply the cost of the conversion function, not the cost of the conversion function plus the cost of the copy constructor (which is what the standard counts).

History
Date User Action Args
2022-02-18 07:47:23adminsetmessages: + msg6658
2001-11-09 00:00:00adminsetmessages: + msg579
2001-11-09 00:00:00adminsetstatus: open -> nad
2000-09-05 00:00:00admincreate