返回类类型的函数

如果一个函数返回类类型,在编译器无优化的情况下,如果函数返回值不用于赋值或初始化变量,则调用类的拷贝构造函数将返回值赋给一个临时变量;如果返回值用于赋值,则先调用类的拷贝构造函数将返回值赋给一个临时变量,再调用赋值运算符,将临时变量赋值给被赋值的变量;如果返回值用于初始化类变量,则函数返回时,调用类的拷贝构造函数将返回值拷贝给被初始化的变量。以上三种情况参见下面的测试代码和输出:


#include <iostream>
#include <string>

using namespace std;

class A {
    static int count;
    int indent;
public:
    A () : indent (count++) {
        string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
        cout << "A () called" << endl;
    }
    ~A () {
        --count;
        string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
        cout << "~A () called" << endl;
    }
    A (const A &a) :indent (count++) {
        string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
        cout << "A (const A &) called" << endl;
    }
    const A &operator= (const A &a) {
        string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
        cout << "A::operator= () called" << endl;
        return *this;
    }
};

int A::count = 0;

A g;

A fun()
{
    A a;
    return a;
}

int main(int argc, _TCHAR* argv[])
{
    // Case 1: 返回值不用于赋值或初始化
    { cout << "---------------------------" << endl;
    fun();
    }

    // Case 2: 返回值给变量赋值
    { cout << "---------------------------" << endl;
    g = fun();
    }

    // Case 3: 返回值初始化
    { cout << "---------------------------" << endl;
    A a = fun();
    }

    int in;
    cin >> in;
	return 0;
}

输出:

[0041B17C] A () called
---------------------------
    [0012FE34] A () called
        [0012FE70] A (const A &) called
    [0012FE34] ~A () called
        [0012FE70] ~A () called
---------------------------
    [0012FE34] A () called
        [0012FE7C] A (const A &) called
    [0012FE34] ~A () called
[0041B17C] A::operator= () called
        [0012FE7C] ~A () called
---------------------------
    [0012FE34] A () called
        [0012FF54] A (const A &) called
    [0012FE34] ~A () called
        [0012FF54] ~A () called
[0041B17C] ~A () called



注:以上输出是在VC8 Debug版本的输出,VC8 Debug版本的项目属性,默认配置时禁用优化(/Od)。

下面看一下Release版本的输出,Release版本项目属性,默认配置为(/O2)。

[00403378] A () called
---------------------------
	[0012FF5C] A () called
	[0012FF5C] ~A () called
---------------------------
	[0012FF5C] A () called
[00403378] A::operator= () called
	[0012FF5C] ~A () called
---------------------------
	[0012FF60] A () called
	[0012FF60] ~A () called
[00403378] ~A () called


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值