2013-10-07 57 views
0

我已经定义了一个普通的类T:传递和返回引用

class T { 
    public: 
    T() { cout << "default constructor " << this << "\n" } 
    T(const & T a) { cout <<"constructor by copy " << this << "\n"} 
    ~T() { cout << "destructor "<< this << "\n"} 
    T & operator=(T & a) { 
     cout << " assignemnt operator :" << this << " = " << &a << endl;} 
}; 

而且有4个功能,其中之一是错误的:

T f1(T a){ return a; } 
T f2(T &a){ return a; } 
T &f3(T a){ return a; } 
T &f4(T &a){ return a; } 

有谁知道哪一个是错的?

+1

顺便说一句:在'operator ='中,'T&a'通常是const。 – luiscubal

+0

这是一个糟糕的问题 - 任何编译器都会给出答案! –

+0

'T(const&T a)'在'T'的类定义中是乱码。 –

回答

5

f3是错误的,因为它返回的是对本地对象的引用。

复制按值传递的参数。它们的副本对于它们传递的函数是局部的 - 只要函数返回,它们就会超出范围。