Set shared_ptr to point existing object

那年仲夏 提交于 2019-12-01 04:43:50

There is not much point in using a shared_ptr for an automatically allocated object.

Technically you can do it, by giving the shared_ptr a deleter that doesn't do anything, and changing your vtx to be a vector of shared pointers to const vectors.

E.g. changing the declaration to

vector < shared_ptr <Vector3 const> > vtx;

and adding a pointer like this:

vtx.push_back( shared_ptr<Vector3 const>( &vt, [](Vector3 const*){} ) );

Disclaimer: untested code, not touched by a compiler.

However, unless you're going to also add pointers to vectors that need to be deleted, just use a vector of raw pointers. Or, just use a vector of vectors, and copy the in-data.


It's not a good idea to use raw pointers to hold ownership. For that use smart pointers.

But conversely, it's not a good idea to use ownership smart pointers to hold pure references to static or automatic objects. For that, use raw pointers or references.

In general.

Disregarding the argument about whether using shared_ptr is a good idea or not, as explained by the accepted answer, you can use the following if you continue to use shared_ptr:

void addVtx (const Vector3& vt)
{
    vtx.push_back(std::make_shared<Vector3>(vt));
}

void setVtx (size_t v, const Vector3& vt)
{
    if ( vtx.size() > 0 && v < vtx.size() )
    {
       vtx[v] = std::make_shared<Vector3>(vt);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!