atomSmasher atomSmasher - 1 year ago 66
C++ Question

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


template <typename T>
class ListNode

friend class List<T>;

ListNode<T>(const T &);

T data;



template<typename T>
class List
void insert_at_front(const T &);
ListNode<T> *get_new_node(const T &);


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);

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download