Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error when calling a move overloaded function with an implicitly convertible object

This program does not compile using clang++ test.cpp -std=c++0x:

class A
{
public:
    A() {}
    A(const A&) {}
    A(A&&) {}
    A& operator = (const A&) { return *this; }
    A& operator = (A&&) { return *this; }
};

class B
{
    A m_a;
public:
    operator const A &() const
    {
        return m_a;
    }
};

int main(int, char**)
{
    A a;
    B b;
    a = b; // compile error
}

Compile errors:

Apple clang version 3.0 (tags/Apple/clang-211.10.1) (based on LLVM 3.0svn)

test.cpp:25:9: error: no viable conversion from 'B' to 'A'
    a = b;
        ^
test.cpp:5:5: note: candidate constructor not viable: no known conversion from 'B' to
      'const A &' for 1st argument
    A(const A&) {}
    ^
test.cpp:6:5: note: candidate constructor not viable: no known conversion from 'B' to 'A &&'
      for 1st argument
    A(A&&) {}
    ^
test.cpp:15:5: note: candidate function
    operator const A &() const
    ^
test.cpp:8:23: note: passing argument to parameter here
    A& operator = (A&&) { return *this; }
                      ^

Why does it not compile? Why does the compiler prefer A::operator = (A&&) over A::operator = (const A&)?

In addition, why would A a = b; compile while both A a; a = b; (the above program) and A a(b); do not?

like image 857
David Lin Avatar asked Oct 09 '22 03:10

David Lin


1 Answers

I'm not sure what bug this is, but the version of Clang you are testing is fairly old, especially with respect to C++11 features. You probably want to use at the very least the 3.0 release of Clang, which correctly accepts this AFAIK. I tested it with a recent revision of the Clang SVN trunk, and it worked fine.

Given that Clang's C++11 support is still under very active development, don't be surprised if there are also bugs in the 3.0 release. You may have more success with a build directly from the SVN trunk. There are instructions here for checking out the code from subversion and building a fresh set of Clang binaries.

like image 68
Chandler Carruth Avatar answered Oct 12 '22 23:10

Chandler Carruth