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

相关推荐
野生技术架构师1 小时前
牛客网Java 高频面试题总结(2025最新版)
java·开发语言·面试
一只鹿鹿鹿1 小时前
系统安全设计方案书(Word)
开发语言·人工智能·web安全·需求分析·软件系统
持梦远方2 小时前
【C++日志库】启程者团队开源:轻量级高性能VoyLog日志库完全指南
开发语言·c++·visual studio
聪明努力的积极向上2 小时前
【C#】HTTP中URL编码方式解析
开发语言·http·c#
嵌入式-老费2 小时前
自己动手写深度学习框架(快速学习python和关联库)
开发语言·python·学习
ctgu902 小时前
PyQt5(八):ui设置为可以手动随意拉伸功能
开发语言·qt·ui
许长安2 小时前
C++中指针和引用的区别
c++·经验分享·笔记
CVer儿2 小时前
libtorch ITK 部署 nnUNetV2 模型
开发语言
asyxchenchong8882 小时前
OpenLCA、GREET、R语言的生命周期评价方法、模型构建
开发语言·r语言
没有梦想的咸鱼185-1037-16633 小时前
【生命周期评价(LCA)】基于OpenLCA、GREET、R语言的生命周期评价方法、模型构建
开发语言·数据分析·r语言