C++ sending reference?

Viewed 57

let's suppose I have:

template<class S, class T>
class node
{
public:
  S key;

  node(const S& key)
    : key(key)
  {}
};

Will this save a new instance of key or simply point to the one sent as parameter to the function?

I'm quit not sure since on the one hand I am sending a reference "kind of a pointer", on the other hand key isn't a pointer so a new instance should be made...

3 Answers

To be asolutely certain, look at the adresses of the objects. Different objects have different adresses and the same object has the same adress.

template<class S, class T>
class node
{
public:
  S key;

  node(const S& key)
    : key(key)
  {}
};
    
int main()
{
    int x = 1;
    node<int,int> n(x);
    std::cout << &x << "\n";
    std::cout << &(n.key) << "\n";
}

Possible output :

0x7ffec1abb16c
0x7ffec1abb168

A reference is just an alias for a different object. Your member key on the other hand is an object of type S (not a reference), hence it cannot be the same object as the one the parameter to the constructor refers to. In the above example, the member is initialized with the value of x.

The code is perfectly sane, but using key twice makes it harder to describe what happens. So, small modification for the sake of discussion:

template<class S, class T>
class node {
public:
    S m_key;

node(const S &key) : m_key(key){}
};

key (the argument) is a reference. That means that the S object used as an argument is not copied to key. However, m_key (the member) is not a reference. m_key must be initialized by the node constructor. To do this, the S object referenced by key is copied to m_key.

There could be exceptions to this, if S is a bit unusual type. For instance, S could be a reference type itself: node<const int&, void>.

The value of the parameter key is being copied into this->key. Therefore, they are not the same object, but 2 identical objects, in different memory locations. If you'd like them to be the same object, I recommend using pointers in this scenario, like this:

template<class S, class T>
class node
{
public:
  S *key;

  node(const S& key)
    : key(&key)
  {}
};
Related