Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the reference to an object in the member initialzation list of its constructor

Is it okay to pass the reference to an object (of type) Container in the member initialization list of its constructor in order to initialize a member of Container as follows: (code on ideone).

#include <cstdlib>
#include <iostream>

struct Container;

struct Member
{
    Member( Container& container ) : m_container( container )
    {
    }

    Container& m_container;
};

struct Container
{
    Container() : m_member( *this )
    {
    }

    Member m_member;
};

int main()
{
    Container c;
    return EXIT_SUCCESS;
}

The code compiles but I'm not sure if its standard.

like image 672
Olumide Avatar asked Jan 17 '23 23:01

Olumide


2 Answers

That's fine; the member reference is initialised to refer to the object that was passed as an argument.

However, since the Container is still under construction, you mustn't access it in that constructor; the only thing you can do with the reference is initialise another reference.

You must also make sure that you don't use that reference after the container is destroyed. In this example, it's fine - m_member, and the reference it contains, are destroyed along with the container.

like image 185
Mike Seymour Avatar answered Feb 24 '23 16:02

Mike Seymour


That's ok, but do note that container in Member's constructor is not completely constructed yet, so you can't do anything with it except store that reference.

like image 44
Mat Avatar answered Feb 24 '23 14:02

Mat