先说点背景知识,调用复制构造函数的三种情况:
当用类一个对象去初始化另一个对象时。
如果函数形参是类对象。
如果函数返回值是类对象,函数执行完成返回调用时。
请看下面的例子:
#include <stdio.h>
#include <unistd.h>
#include <iostream>
class A
{
public:
A() { std::cout << "A Constructor" << std::endl; }
A(const A&) { std::cout << "A Copy Constructor" << std::endl; }
A &operator=(const A&) { std::cout << "A operator = " << std::endl; }
~A() {std::cout << "A Destructor" << std::endl;}
};
class B
{
public:
B() { std::cout << "B Constructor" << std::endl; }
B(const B&) { std::cout << "B Copy Constructor" << std::endl; }
~B() {std::cout << "B Destructor" << std::endl;}
};
A getA(A ta, B tb)
{
std::cout << "====-2" << std::endl;
A a1; //-----A Constructor
std::cout << "====-2" << std::endl;
return a1; //-----A Copy Constructor temp=a1, A Destructor a1
}
int main()
{
A a; //----A Constructor
B b; //----B Constructor
std::cout << "====-1" << std::endl;
A a2 = getA(a,b); //---- B Copy Constructor, A Copy Constructor.......(a2=temp) A Copy Constructor.....A Destructor(temp des)
A a2; //如果此处先定义了a2,然后再进行a2对象的再次赋值,会发生什么????而不是像上面那种直接进行定义赋值。结果见下面3图
a2= getA(a,b);
std::cout << "====-1" << std::endl;
return 0;
}
编译:g++ -fno-elide-constructors
执行:./moveConstruct
结果:
1、这是我加了编译选项的结果: -fno-elide-constructors
编译:g++ moveConstruct.cpp -o moveConstruct
执行:./moveConstruct
结果:
2、这是我不加了编译选项的结果:
有两个问题???
A a1; 构造和析构发生在什么时候????
A a2 = getA(a,b); a2构造和析构发生在什么时候????
难道a1和a2合体了。。。
3、先定义了a2,然后再进行a2对象的再次赋值
“-fno-elide-constructors”选项起了作用,有图为证。下面中加上这个参数后,编译完看到的提示信息: