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析构)

相关推荐
Raas10021 分钟前
AI网关部署方案?从部署到上线全流程
java·开发语言·人工智能·gateway·ai网关·企业级ai网关·企业级ai产品
专注仿真1 小时前
线性回归和逻辑回归算法详解
开发语言·人工智能·python·大模型训练·控制算法
jimy12 小时前
C++ 中的 `T&&`:右值引用与转发引用
开发语言·c++
呆呆虫122 小时前
用 orjson 加速 SerpBase 响应解析:基准对比与注意事项
开发语言·php
心疼你的一切3 小时前
Python自动发邮件实战定时发报表
大数据·开发语言·python
Wang's Blog4 小时前
Java 项目实战:交友项目 - 用户体系集成总结
java·开发语言·交友
会编程的小孩4 小时前
C++ 定时器
c++
中科三方4 小时前
IPv6检测常见问题:AAAA记录检测不通过是什么原因?
开发语言·php
沫璃染墨5 小时前
从零入门计算机网络系列(十一):HTTP协议进阶——从重定向原理到GET/POST与Fiddler抓包
linux·服务器·开发语言·网络·c++·tcp/ip·html
刚入门的大一新生5 小时前
Linux-线程互斥
java·开发语言