Search code examples
c++pass-by-referenceassignment-operatorclass-members

Defining class member via a reference passed through constructor


I am working on a linked list implementation in C++ and I was curious about the lifetime of the original data. Lets say a calling program creates a new ListNode with the following constructor. My concern is the original variable could vary well go out of scope leaving undefined behavior IF the data member assignment is not a copy of value.

ListNode<T>::ListNode(const T &value) : data(value) {}

When value is passed to data in the parameter list will it define data as a copy of value or will the class member be linked to the original variable passed to the constructor?

EDIT: Adding more information for clarity

list_node.hpp

template <typename T>
class ListNode
{

friend class List<T>;

public:
   ListNode<T>(const T &);

private:
   T data;

};

list.hpp

template<typename T>
class List
{
public:
   void insert_at_front(const T &);
private:
   ListNode<T> *get_new_node(const T &);
};

list.cpp

void List<T>::insert_at_front(const T &value)
{
   ListNode<T> *new_node_ptr = get_new_node(value);

   ...
}

ListNode<T> *List<T>::get_new_node(const T &value)
{
   return new ListNode<T>(value);
}

Solution

  • struct Foo {
        Foo(const Bar& b) : m_b(b) {}
    
        Bar m_b;    
    };
    
    struct Foo2 {
        Foo2(const Bar& b) : m_b(b) {}
    
        const Bar& m_b;    
    };
    

    As you can see, the constructor code is the same, but these two classes do something different. The first class will make a copy of the passed Bar, so it is "safe" if the local variable passed in goes out of scope. The second class simply grabs the reference. Effectively, this is like holding a reference to the variable that was passed in. So if the variable passed in goes out of scope, then Foo2 will have a dangling reference.