返回一个指向矢量元素的指针 [英] Returning a pointer to a vector element

查看:148
本文介绍了返回一个指向矢量元素的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找出最好的方法来保存一个指针指向刚刚创建并添加到成员变量向量的向量中的元素:

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?

推荐答案


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.

例如:

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

这篇关于返回一个指向矢量元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆