【发布时间】:2017-02-27 03:57:14
【问题描述】:
下面是用于测试构造函数的 sn-p。它在 VS 2015 中运行。
在我看来,“B b(B())”与“B b = B()”具有相同的功能,但是,我的代码似乎表明它们的行为不同。
我知道编译器优化存在复制省略,但我认为至少在执行“B b(B())”时应该调用默认构造函数。 谁能帮忙指出我的误解在哪里?
class B
{
public:
B() {
++i;
x = new int[100];
cout << "default constructor!"<<" "<<i << endl;
cout << "x address:" << x << endl << "--------" << endl;
}
B(const B &b) //copy constructor
{
++i;
cout << "Copy constructor & called " << i<< endl
<< "--------" << endl;
}
B(B &&b)//move constructor
{
x = b.x;
++i;
b.x = nullptr;
cout << "Copy constructor && called" << i << endl
<<"x address:"<< x << endl << "--------" << endl;
}
void print()
{
cout << "b address:" << x << endl << "--------" << endl;
}
private:
static int i;
int *x;
};
int B::i = 0;
int main()
{
B b1; //default constructor
b1.print();
B b2 = B(); //default constructor only
b2.print();
B b3(B()); //????nothing called... why???
B b4 = b2; //copy constructor
B b5 = move(b2); //move constructor
b2.print();
return 0;
}
【问题讨论】:
标签: c++ copy-constructor default-constructor move-constructor most-vexing-parse