SoftTimur
SoftTimur

Reputation: 5510

pass and return references

I have defined a normal class 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;}
};

And there are 4 functions, one of which is wrong:

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

Does anyone know which one is wrong?

Upvotes: 1

Views: 57

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

f3 is wrong, because it is returning a reference to a local object.

Parameters passed by value are copied. Their copies are local to functions to which they are passed - they go out of scope as soon as the function returns.

Upvotes: 5

Related Questions