Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1111132
  • 博文数量: 300
  • 博客积分: 37
  • 博客等级: 民兵
  • 技术积分: 772
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-26 04:46
文章分类
文章存档

2017年(4)

2016年(7)

2015年(19)

2014年(72)

2013年(71)

2012年(127)

分类:

2012-05-23 22:18:59

原文地址:c++ 中的临时变量 作者:sandflee

#include

using namespace std;

class foo 
{
public:
    foo(int a1):a(a1){cout << "constructor" << endl;}
    foo(const foo& tmp)
    {   
        a = tmp.a;
        cout << "copy_constructor" << endl;
    }   

    foo& operator=(foo& tmp)
    {
        a = tmp.a;
        cout << "operator =" << endl;
        return *this;
    }
    ~foo()
    {
        cout << "destructor" << endl;
    }
private:
    int a;
};

foo test(foo a)
{
    cout << "in test" << endl;
    return a;
}

int main()
{
    test(1);
    cout << "after test " << endl;
    return 0;
}

在调用test(1)时发生了什么?
程序将参数1压栈,在编译阶段确定调用函数foo& test(foo a),call到对应的地址,利用参数1构造本地变量a,返回a的值,生成一个临时变量,同时由于栈回滚,本地变量a消除。return0 后临时变量消除。所以最后打印
constructor
in test
copy_constructor
destructor
destructor
after test

1,如果更改一下foo的定义:
foo test(foo& a),则编译出错,
错误:不能将类型为‘foo&’的非 const 引用初始化为类型为‘int’的临时变量
似乎不能为a找到一个foo类型的实体

2,如果将foo变为const
const foo& test(const foo& a)
能正常编译,并打印:
constructor
in test
destructor
after test
可见调用test时生成了临时对象,问题是为什么const就能编译通过?
如果没有const参数,我们可以在test函数中随意修改其内容。意义似乎不大,编译器就禁止了?这儿不是很清楚

3,如果更改返回类型,
foo& test(foo a)
警告:返回了对局部变量的‘a’的引用
a是局部变量 返回对局部变量的引用是一件没有意义的事情

阅读(1201) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~