I'm trying to figure out best way to hold a pointer to an element in a vector that has just been created and added to the member variable vector:
SceneGraphNode* addChild(std::string name){
SceneGraphNode child(this,name);
m_children.push_back(child);
return &child;
}
The compiler rightfully gives me a warning since I am returning the address of an object created on the stack, and that object will go out of scope as the function ends. However, the object lives on in the vector
, right?
So, should I ignore the warning or is there a better way to do this?
Use -> Notation to Access Member Functions From Pointer to a Vector. vector member functions can be called from the pointer to the vector with the -> operator.
Use the vector<T> func() Notation to Return Vector From a Function. The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics.
Return Pointer from Functions in C++ Second point to remember is that, it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.
However, the object lives on in the vector, right?
No, a copy of it does. You want to return the address of the copy.
return &m_children.back();
However, it is not a good idea to store a pointer to an object that resides in a vector. Because when the vector needs to reallocate, the pointer will be invalidated. Perhaps you should store pointers (preferably smart pointers) in your vector instead.
For example:
// in your class
std::vector<std::unique_ptr<SceneGraphNode>> m_children;
SceneGraphNode* addChild(std::string name)
{
std::unique_ptr<SceneGraphNode> child(new SceneGraphNode(this,name));
m_children.push_back(std::move(child));
return m_children.back().get();
}
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