为什么这个复制构造函数而不是移动构造函数? [英] Why is this copy constructor called rather than the move constructor?

查看:575
本文介绍了为什么这个复制构造函数而不是移动构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段导致在我希望调用move构造函数的地方调用复制构造函数:

  #include < cstdio> 

struct Foo
{
Foo(){puts(Foo gets built! }
Foo(const Foo& foo){puts(Foo gets copied! }
Foo(Foo& foo){puts(Foo gets moved!); }
};

struct Bar {Foo foo; };
Bar Meow(){Bar bar;返回栏}
int main(){Bar bar(Meow()); }在VS11测试版,在调试模式下,这打印:







$ b < b $ b

  Foo构建! 
Foo被复制!
Foo被复制!

我检查了标准,并且 Bar 满足所有的要求,有一个默认的移动构造函数自动生成,但似乎没有发生,除非有另一个原因,为什么对象不能移动。我在这里看到了很多关于移动和复制构造函数的问题,但我不认为任何人都有这个具体问题。



任何指向这里发生的事?这是标准的行为吗?

解决方案

不幸的是,VS11不提供默认的移动构造函数。请参阅备注部分中的移动语义 - 引用: / p>


与默认的复制构造函数不同,编译器不提供
默认的移动构造函数。



The following code snippet causes the copy constructor to be called where I expected the move constructor to be called:

#include <cstdio>

struct Foo
{
    Foo() { puts("Foo gets built!"); }
    Foo(const Foo& foo) { puts("Foo gets copied!"); }
    Foo(Foo&& foo) { puts("Foo gets moved!"); }
};

struct Bar { Foo foo; };
Bar Meow() { Bar bar; return bar; }
int main() { Bar bar(Meow()); }

On VS11 Beta, in debug mode, this prints:

Foo gets built!
Foo gets copied!
Foo gets copied!

I checked the standard and Bar seems to meet all requirements to have a default move constructor automatically generated, yet that doesn't seem to happen unless there's another reason why the object cannot be moved. I've seen a lot of move and copy constructor related questions around here but I don't think anyone has had this specific issue.

Any pointers on what's going on here? Is this standard behaviour?

解决方案

Unfortunately, VS11 doesn't provide a default move constructor. See Move Semantics in the Remarks section - to quote:

Unlike the default copy constructor, the compiler does not provide a default move constructor.

这篇关于为什么这个复制构造函数而不是移动构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆