为什么调用复制构造函数而不是移动构造函数
Why is the copy constructor called instead of the move constructor?
考虑以下代码:
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
的。
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么调用复制构造函数而不是移动构造函数?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 具有已删除移动和复制构造函数的类的就地构造
- 移动构造函数和右值引用
- 使用移动调用对等构造函数unique_ptr默认构造函数
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- 构造函数采用std::string_view与std::string并移动
- C++:为什么不调用移动构造函数?
- 了解构造函数在移动、复制、赋值语义中的行为
- 没有移动的构造函数移动课程
- 引用绑定和复制构造函数/移动构造函数
- 构造函数移动
- C++ 向量实现 - 移动构造函数 - 移动与前进
- 我真的必须取消移动构造函数/移动结构中的所有成员还是只是指针
- 将类(没有默认构造函数)移动到另一个类的move构造函数中