C++ 中的返回值优化

代码:

cpp 复制代码
//
// Created by w on 2024/6/19.
//
#include <iostream>

using namespace std;

template<typename T>
class myClass {
public:
    myClass() {
        data = NULL;
        cout << "default construct" << endl;
    }

    myClass(const T &para) {
        data = new T(para);
        cout << "construct with para" << endl;
    }

    myClass(const myClass &other) {
        if (&other == this) {
            return;
        }

        data = new T(*other.data);
        cout << "copy construct" << endl;
    }


    myClass &operator=(const myClass &other) {
        if (&other == this) {
            return *this;
        }
        if (data != NULL) {
            delete data;
        }
        data = new T(*other.data);
        cout << "copy operator =" << endl;

        return *this;
    }

    myClass(myClass &&other) {
        if (&other == this) {
            return;
        }

        data = other.data;
        other.data = NULL;
        cout << "move construct" << endl;
    }


    myClass &operator=(myClass &&other) {
        if (&other == this) {

            return *this;
        }

        if (data != NULL) {
            delete data;
        }

        data = other.data;
        other.data = NULL;
        cout << "move operator =" << endl;

        return *this;
    }

    ~myClass() {
        if (data != NULL) {
            delete data;
        }
        cout << "destruct" << endl;
    }

    void print() {
        cout << *data << endl;
    }

private:
    T *data;
};

template<typename T>
myClass<T> f1() {
    return myClass<int>(1000);
}

template<typename T>
myClass<T> f2() {
    myClass<T> namedObj = myClass<int>(1000);
    return namedObj;
}

int main() {
    {
        myClass<int> obj = f1<int>();
    }
    cout << "############" << endl;
    {
        myClass<int> obj = f2<int>();
    }
}

直接运行输出(gcc默认开启了返回值优化):

construct with para

destruct

############

construct with para

move construct

destruct

destruct

关闭返回值优化输出:

g++ -fno-elide-constructors classDemo.cpp -std=c++11 && ./a.out

construct with para (构造匿名对象)

move construct (f1 用前面的匿名对象构造一个临时对象返回)

destruct (匿名对象析构)

move construct (obj使用临时对象move构造)

destruct (临时对象析构)

destruct (obj析构)

############

construct with para (构造匿名对象)

move construct (使用匿名对象构造具名对象)

destruct (匿名对象析构)

move construct (使用具名对象构造临时对象)

destruct (具名对象析构)

move construct (使用临时对象构造obj)

destruct (临时对象析构)

destruct (obj析构)

相关推荐
程序员yu7 分钟前
数智码力:Python作用域完全梳理,全局变量局部变量不再混乱
开发语言·python·学习
anew___8 分钟前
舵机——让 Arduino 动起来
c++·stm32·单片机·嵌入式硬件·c
qq_3449205614 分钟前
Qt 鼠标双击QLabel全屏显示图像
c++·qt
不灭的黄金瞳12342 分钟前
Java数据类型与变量
java·开发语言·intellij-idea
f狐0狸x1 小时前
【C++修炼之路】C++继承的探索
c++·继承
虚无的纽扣1 小时前
【C++】C++11的魔法:不止右值引用,C++11赋予的编程神力
c++
小白学大数据1 小时前
Python 项目实战:用 Flask 构建生产级 MySQL 增删改查 REST API
开发语言·人工智能·python·mysql·flask
Nil2081 小时前
leetcode 20有效的括号
开发语言
jaysee-sjc1 小时前
【苍穹外卖】Day01:从零认识企业级项目开发
java·开发语言·数据库·mysql·spring·intellij-idea·mybatis
码匠许师傅1 小时前
【C++三方组件】RE2:工业级正则的安全与性能
c++