BaseContainer containers
-
Hi folks,
is it safe to access a BaseContainer held inside another BaseContainer by pointer? E.g.:
BaseContainer parent; BaseContainer child; parent.SetContainer(MY_CHILD_ID,child); // then somewhere else BaseContainer *bc = &parent.GetContainer(MY_CHILD_ID); // read from bc... variable value = bc->etc... // finish
Are there any issues with doing this?
WP.
-
Just some further thought here. I tried to return a pointer via a function so that I wasn't having to create a copy everywhere and everytime I needed to access it. Upon reflecting yesterday evening, I realised that returning it like this, the container might be going out of scope at the function return, and is therefore destroyed. I.e.
// let's say parent is class level container somewhere BaseContainer* My_Class::Get_ContainerP(void) { return &parent.GetContainer(MY_CHILD_ID); } void My_Class::Work_Container(void) { BaseContainer *bc = Get_ContainerP(); if(bc == nullptr) { return; } // bc passes nullptr check because the address was valid // however... if(bc->GetBool(MY_CHILD_BOOL,FALSE) == TRUE) { // crashes here with an access violation because the container was destroyed when the scope stopped after the Get_ContainerP() return. } }
I'm wondering if GetContainer() makes a copy itself. I was trying to use a pointer so that I wasn't creating copies of the nested container everywhere and everytime I wanted to access it (which will be frequently). But it looks I have to. Would this be right?
WP.
-
Hi,
you have two function to retrieve the BaseContainer from an object and a container inside a BaseContainer.
You can either retrieve a pointer or a reference.
All function retrieve a pointer to the data and the references are just returning a dereference's pointer.To retrieve the data from the object you have GetDataInstance and GetDataInstanceRef and to retrieve a BaseContainer inside another one you have GetContainer and GetContainerInstance.
Neither of them return a copy.
About the issue, there's no issue as long as the object exist in memory. Depending of the context (specially if you are using threads) this can be more or less safe.
Cheers,
Manuel