Non-const copy constructor and implicit conversions on return value

前端 未结 4 718
长发绾君心
长发绾君心 2020-12-31 23:51

Consider the following C++ code:

struct B { };
struct A
{
        A(int);
        A(A&); // missing const is intentional
        A(B);
        operator B         


        
4条回答
  •  温柔的废话
    2021-01-01 00:18

    I don't think that "too many steps to figure on its own" as DeadMG pointed out is the reason. I've had constructs with 3-4 conversions, and the compiler always figured them out just fine.

    I believe the problem is rather that the compiler is not allowed to convert a const reference to a non-constreference on its own behalf (it is only allowed to do that when you explicitly tell it with a cast).
    And since the reference to the temporary object that is passed to the copy constructor is const, but the copy constructor is not, it doesn't find a suitable function.

    EDIT: I didn't find any "real" code (see comments below) but constructed a multi-zigzag-convert example that actually compiles without errors under gcc 4.5. Note that this compiles just fine with -Wall -Wextra too, which frankly surprises me.

    struct B
    {
        signed int v;
        B(unsigned short in) : v(in){}
    };
    
    struct C
    {
        char v;
        C(int in) : v(in){}
    };
    
    struct A
    {
        int v;
        A(B const& in) : v(in.v){}
        operator C() { return C(*this); }
    };
    
    enum X{ x = 1 };
    
    int main()
    {
        C c = A(x);
        return 0;
    }
    

提交回复
热议问题