Why is the copy constructor called instead of the move constructor?

1k views Asked by At

Consider the following code:

class Outer
{   
class Inner
{
public:
    Inner(Inner&& i):outers(std::move(i.outers)),test(std::move(test))
    {}

    void addOuter(const Outer& o) {outers.push_back(std::move(o));} 
private:
    std::vector<Outer> outers;      
    std::unique_ptr<std::string> test;      
};

public:
Outer(Outer&& o):inners(std::move(o.inners))
{}
private:
std::vector<Inner> inners;

};

When I try to compile the code above on Visual Studio 2012, I get the following error:

Error 1 error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

Apparently the compiler invokes the copy constructor instead of the move constructor in the push_back found in the addOuter method. Is this a compiler bug? If not why, for this specific case, isn't the move constructor called?

1

There are 1 answers

2
Andrey Mishchenko On

Because o is passed as a const reference to addOuter.