Mateusz
Mateusz

Reputation: 624

Returning a reference from a function in c++

I would like to ask about returning a pointer from function.

Assuming that we have got

T *p;

This function should return a refrence to a T object. But it returns *p so it returns an value that it is pointing to. So is there no difference if we will write T& operator... or T operator...?

   T& operator*() const{
        if(p)
            return *p;
        throw std::runtime_error("unbound");
    };

What is a difference between returning a reference and a value normally?

Upvotes: 0

Views: 171

Answers (1)

jpo38
jpo38

Reputation: 21514

If you return a value (T operator...), you will return a new object, a copy of *p. If caller modifies the returned object, it won't affect your attribute variable. Returning by copy has a cost (CPU operations to create the copy + memory usage of the copied object). It also requires T to be capiable (to provide a valid copy constructor).

If you return by reference (T& operator...), you will return the address of the object (in the end, it's very similar to returning a poinetr T*, it costs the same, only syntax to use references is different than syntax to use pointers). If caller modifies the returned referenced object, it will affect your attribute variable (however, making the reference returned const T& will prevent that).

Reference is preferable (faster and better in term of memory usage), as far as you can guarantee that the referenced variable remains alive while caller will use the reference. For instance, if you are returning a local object created by the function, it must be returned by copy, not by reference).

Read more here: What are the differences between a pointer variable and a reference variable in C++?

Upvotes: 3

Related Questions