在最近学习C++的过程中,笔者书写了以下的代码尝试测试各种类型的构造函数
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Teacher {
private:
char* name = NULL;
short age;
public:
Teacher() = default;
Teacher(const char* name, short age);
Teacher(Teacher&& teacher);
void showInfo();
};
Teacher getNum();
int main() {
Teacher teacher_move(getNum());
teacher_move.showInfo();
return 0;
}
Teacher::Teacher(const char* name, short age) {
cout << "简单参数类型初始化" << endl;
this->name = (char*)malloc(sizeof(char) * (strlen(name) + 1));
strcpy(this->name, name);
this->age = age;
}
Teacher::Teacher(Teacher&& teacher) {
cout << "移动构造函数" << endl;
this->age = teacher.age;
this->name = teacher.name;
teacher.name = NULL;
}
void Teacher::showInfo() {
if (name != NULL)
cout << "Name: " << name;
else
cout << "The pointer of name is NULL!";
cout << "\t" << "Age: " << age << endl;
}
Teacher getNum() {
Teacher tmp("lll", 45);
return tmp;
}
运行结果为:

然而在运行过程中从输出的结果来看似乎并没有调用移动构造函数。因而笔者将移动构造函数注释后重新编译运行,发现仍可以正常运行。查阅资料后,发现因编译器使用RVO优化,因而省去了不必要的拷贝等等,从而提高程序运行效率。
解决方案:
若想要强制查看移动构造函数的调用,可以禁用这种优化,使用编译选项-fno-elide-constructors.
例如,使用g++编译:
g++ -std=c++11 -fno-elide-constructors your_code.cpp -o your_program
此时运行结果为:

另:对于本程序,若编译器要编译后中文字符不出现乱码,还需指定字符集,即
g++ -std=c++11 -fno-elide-constructors your_code.cpp -o your_program -fexec-charset=GBK
1万+

被折叠的 条评论
为什么被折叠?



