为什么调用复制构造函数而不是移动构造函数

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

本文关键字:构造函数 移动 复制 为什么 调用      更新时间:2023-10-16

考虑以下代码:

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;
};

当我试图在Visual Studio 2012上编译上面的代码时,我得到了以下错误:

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

显然,编译器调用了复制构造函数,而不是addOuter方法中push_back中的移动构造函数。这是编译器错误吗?如果不是,对于这个特定的情况,为什么不调用move构造函数?

因为o是作为const引用传递给addOuter的。