Chinaunix首页 | 论坛 | 博客
  • 博客访问: 522753
  • 博文数量: 122
  • 博客积分: 2024
  • 博客等级: 上尉
  • 技术积分: 1484
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-08 21:17
文章分类

全部博文(122)

文章存档

2012年(2)

2011年(25)

2010年(95)

分类: C/C++

2012-05-23 00:46:39

#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是局部变量 返回对局部变量的引用是一件没有意义的事情

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

sandflee2012-05-24 00:20:35

-小Y头-: C++中临时变量是不是不能做为左值?.....
只所以有临时变量不能作为左值的说法,恐怕也是出于这个考虑。

sandflee2012-05-24 00:16:47

-小Y头-: C++中临时变量是不是不能做为左值?.....
可以做左值,把上面的例子稍改一下:
int main()
{
    foo a(2);
    test(1)=a;
    cout << "after test " << endl;
    return 0;
}
打印的结果是:
constructor
constructor
in test
copy_constructor
operator =
destructor
destructor
after test
destructor

-小Y头-2012-05-23 11:21:54

C++中临时变量是不是不能做为左值?