Returning a pointer to a vector element

I am trying to find a better way to hold a pointer to an element in a vector that has just been created and added to a 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 this object goes out of scope as the function completes. However, the object lives in vector , right?

So, should I ignore the warning, or is there a better way to do this?

+6
source share
4 answers

However, the object lives in a vector, right?

No, a copy of it. You want to return the copy address.

 return &m_children.back(); 

However, it is not recommended to store a pointer to an object that is in the vector. Because when the vector needs to be redistributed, the pointer will be invalidated. Perhaps you should store pointers (preferably smart pointers) in your vector instead.

For instance:

 // 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(); } 
+10
source

However, the object lives in a vector, right?

When you insert a vector, it actually presses copies objects, not the object itself, into the vector. STL containers have copy in, copy out . However, as pointed out by the compiler, you should not return the address of an object created on the stack .

0
source

When you add it to std :: vector you essentially make a copy. You must return a reference to the object stored in the vector.

 return &(m_children.back()); 
0
source

The object does not exactly live in the vector, because when you push_back it, you make a copy of this element.

This code could work if you changed the return to something like this (Ryan's form would be simpler):

 return &m_children[m_children.size() - 1]; 

Thus, you are actually returning a pointer to an element living in your vector.

0
source

Source: https://habr.com/ru/post/944337/


All Articles