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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With