Why is a (remote) copy instance preferable to an implicit conversion?

Consider the code below:

struct Bar{};

struct Foo
{
    Foo() = default;
    Foo(const Bar&) {}
    Foo(const Foo&) = delete;

    // IMPLICIT conversion to Bar
    operator Bar(){return {};}
};

int main() 
{
    Foo f1;
    Foo f2(static_cast<Bar>(f1)); // this is OK
    Foo f3(f1); // does not compile, why not implicit conversion to `Bar`?
}

The class Barhas a custom conversion operator in Foo, which takes Bar&s. However, in the last line, mainI expected it to Foo f1be converted to Bar, and then passed to Foo(const Bar&). However, only the remote constructor is considered Foo(const Foo&) = delete;. I understand that this constructor is better suited, but why is it not Foo(const Bar&)also in the overload set, and why does the compiler not perform the implicit conversion?

+4
source share
1 answer

, , -.

, delete :

Foo f3(f1);

, f1 Foo, Foo(const Foo&) . , , Foo(const Bar&).

+6

Source: https://habr.com/ru/post/1616443/


All Articles