论函数的设计应如何才好,返回临时变量 | 返回引用 | 传递引用

时间:2022-07-26
本文章向大家介绍论函数的设计应如何才好,返回临时变量 | 返回引用 | 传递引用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这个就涉及效率的问题,怎么要写,才会尽可能的少调用构造函数。

先设计如下的类

class tempTest{
public:
    tempTest(){
        cout <<"hello tempTest() "<<count++ << endl; 
    }
    tempTest(tempTest& ){
        cout <<"hello copy tempTest() "<<count++ << endl; 
    }
    ~tempTest(){
        cout << "good bye "<<count--<<endl;
    }
    tempTest& operator=(tempTest& r){
        cout <<"hello operator= "<<count++ << endl; 
        return *this;
    }
private:
    static int count;
};
int tempTest::count = 0;

首先这个函数里面,会发生两次构造函数,一次是 变量t,另外一次是return 前,做的一次拷贝构造

tempTest testTemp(){
    tempTest t;
    return t;
}

第一种,返回临时变量,这里的话,就会再发生一次 tt 构造函数,接着再触发 operator=(assign),这样的话,如果是存有大数据的结构体的话,性能就很差了。

        cout << " tt = testTemp"<<endl;
        //这样写,就3次构造函数
        tempTest tt;
        tt = testTemp();

第二种,如果是这样写的话,就只有 testTemp() 函数里面的两次对象的产生! 比第一种少了两次。

        cout << "tempTest tt = testTemp"<<endl;
        //这样写,就2次构造函数
        tempTest tt2 = testTemp();

首先这个函数的话,只会发生一次构造函数,返回引用

tempTest& testTemp2(){
    tempTest * t = new tempTest();
    return *t;
}

第三种,然后,注意这里的变量要用引用,这样,总得来说,只发生一次构造函数!一次是最少了,但是如果返回引用的话,就得注意一个问题,内存泄露,所以不用得时候,要delete掉。返回指针同理。

        cout << "tempTest& tt = testTemp"<<endl;
        tempTest& tt3 = testTemp2();
        _CrtDumpMemoryLeaks();
        delete &tt3;

这个函数,就通过传入引用来修改变量。

void testTemp3(tempTest& t){

}

这样的话,只需要一次构造函数,然后,如果是临时变量的话,超过使用范围,还会自动析构,更方便的样子。

        cout << "testTemp3(tempTest&)"<<endl;
        tempTest tt4;
        testTemp3(tt4);

所以,最终,我的结论是,需要处理,或者获得某个数据的时候,用传引用会更好。