为什么这个代码试图调用复制构造函数? [英] Why is this code trying to call the copy constructor?
问题描述
我只是花费了大量的时间在Visual Studio中编译错误。我已经将代码转换成下面的小编译示例,并尝试了在IdeOne,并得到了同样的错误,你可以看到在这里。
我想知道为什么下面的代码试图调用 B(const B&)
而不是 B (B&&)
:
#include< iostream&
using namespace std;
class A {
public:
A():data(53){}
A(& dying):data(dying.data) {dying.data = 0; }
int data;
private:
//未实现,这是一个不可复制的类
A(const A&);
A& operator =(const A&);
};
class B:public A {};
int main(){
B binst;
char * buf = new char [sizeof(B)];
B * bptr = new(buf)B(std :: move(binst));
cout<< bptr-> data<< endl;
delete [] buf;
}
我没有明确定义任何构造函数,因此 B(std :: move(binst))
应该调用编译器生成的 B(B&& amp;)
,否? b
$ b
当我将 B
更改为
class B:public A {
public:
B(){}
B(B&&){}
};
它编译得很好。为什么是这样的?
如果不能从基类中解决这将是非常不方便的,因为我有一个模板类使用placement new和move构造函数,如示例,并且它将要求每个不可复制的类(它不是绝对不应该与我的模板类一起使用的)具有一个显式定义的move构造函数。
如果您使用Visual Studio 2010或2012,请注意:编译器不会 自动为您生成移动构造函数。这没有实现。所以你需要自己写。
I just spent an inordinate amount of time fiddling with a complilation error in Visual Studio. I have distilled the code into the small compilable example below and tried it on IdeOne and got the same error which you can see here.
I am wondering why the following code tries to call B(const B&)
instead of B(B&&)
:
#include <iostream>
using namespace std;
class A {
public:
A() : data(53) { }
A(A&& dying) : data(dying.data) { dying.data = 0; }
int data;
private:
// not implemented, this is a noncopyable class
A(const A&);
A& operator=(const A&);
};
class B : public A { };
int main() {
B binst;
char* buf = new char[sizeof(B)];
B* bptr = new (buf) B(std::move(binst));
cout << bptr->data << endl;
delete[] buf;
}
I didn't explicitly define any constructors, so B(std::move(binst))
should call the compiler generated B(B&&)
, no?
When I change B
to
class B : public A {
public:
B() { }
B(B&&) { }
};
It compiles fine. Why is this?
It will be extremely inconvenient if this can't be fixed from the base class because I have a template class which uses placement new and move constructors like the example, and it will require every class that is not copyable (which is not and definitely should not be a requirement for use with my template class) to have an explicitly defined move constructor.
If you are using Visual Studio 2010 or 2012, be advised: the compiler does not automatically generate move constructors for you. That wasn't implemented. So you need to write them yourself.
这篇关于为什么这个代码试图调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!