当前位置: 首页> 健康> 美食 > C++ 中的返回值优化

C++ 中的返回值优化

时间:2025/8/28 7:47:42来源:https://blog.csdn.net/wks19891215/article/details/140398674 浏览次数:0次

代码:

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

关键字:C++ 中的返回值优化

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: