在C++中如果函数返回值是对象的时候,那么该直接返回临时对象呢,还是先在函数体内构造好一个本地
对象,然后返回。如果可以直接返回临时对象,那么我们就返回临时对象来代替返回本地对象,因为这样代码
的效率会比返回本地对象的效率高。以下通过代码说明两者的区别
(更多讲解在注释中已说明):
1.返回本地对象代码示例:
- #include <iostream>
- using namespace std;
-
- class A {
- public:
- int m_k;
- int m_t;
- A(int k, int t) :m_k(k), m_t(t) {
- cout << "construct...." << endl;
- }
- ~A() {
- cout << "destruct...." << endl;
- }
- A(A &a) {
- cout << "copy construct..." << endl;
- }
- };
-
-
- A getObj() {
-
-
-
-
-
-
-
- A a(3, 4);
- return a;
- }
- int main() {
- getObj();
- return 0;
- }
运行结果:
2.返回临时对象代码示例:
- #include <iostream>
- using namespace std;
-
- class A {
- public:
- int m_k;
- int m_t;
- A(int k, int t) :m_k(k), m_t(t) {
- cout << "construct...." << endl;
- }
- ~A() {
- cout << "destruct...." << endl;
- }
- A(A &a) {
- cout << "copy construct..." << endl;
- }
- };
-
-
- A getObj() {
-
-
-
-
-
- return A(3, 4);
- }
- int main() {
- getObj();
- return 0;
- }
运行结果:
所以总的来说返回临时对象能减少多余的拷贝构造函数和析构函数的调用,从而提高了效率。