关于C++因RVO优化而不调移动构造函数的问题

在最近学习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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值