Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a pointer to a vector element

Tags:

c++

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?

like image 791
johnbakers Avatar asked May 06 '13 02:05

johnbakers


People also ask

How do you access a vector element from a pointer?

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.

How do I return a vector element?

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.

Can you return a pointer in C++?

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.


1 Answers

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();
}
like image 113
Benjamin Lindley Avatar answered Oct 11 '22 01:10

Benjamin Lindley