Lol Pallau
Lol Pallau

Reputation: 199

Difference between T and T&?

hi i would like to know what is the difference between doing

template <typename T> class List :
   T& getData();        
AND
   T getData();
};     

Upvotes: 3

Views: 7748

Answers (2)

Agentlien
Agentlien

Reputation: 5136

Given that T is a type, T& is a reference to an object of type T.

T getData(); is a function which returns an object of type T. This means that, whatever the function returns will be copied and the caller will receive this copy. This is called "return by copy". In practice, it is not always necessary to produce a copy, and a compiler can optimize it away (which is called "copy elision").

T& getData(); is a function which returns a reference to an object of type T. This is, quite understandably, called "return by reference" and means that the object returned is not copied. Instead, you simply return a reference to its location in memory, through which the original object can be accessed. When using this, care has to be taken that the returned reference isn't used beyond the lifetime of the object to which it refers.

If you do not know exactly what a reference is, it is essentially an alias which is used to refer to some variable. It's often used as a safer alternative to a pointer, though unlike a pointer it is itself not an object, and you can never refer to the reference itself, and hence cannot change what it refers to.

If you want to know more, the Wikipedia page is surprisingly helpful.

Upvotes: 11

billz
billz

Reputation: 45450

 T& getData(); returns a reference to T        

 T getData(); returns a copy of T

What is C++ reference: link

Upvotes: 2

Related Questions