传递和返回引用

Sof*_*mur 1 c++ reference

我已经定义了一个普通的类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;}
};
Run Code Online (Sandbox Code Playgroud)

并且有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; }
Run Code Online (Sandbox Code Playgroud)

有谁知道哪一个是错的?

das*_*ght 5

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

按值传递的参数将被复制.它们的副本是传递给它们的函数的本地副本 - 一旦函数返回它们就会超出范围.