Set shared_ptr to point existing object

前端 未结 2 447
终归单人心
终归单人心 2021-01-04 20:18

For the code below, I would like to know how to set std::shared_ptr to point the given objects in the two member functions. The Vector3 object whic

2条回答
  •  我在风中等你
    2021-01-04 20:35

    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  > vtx;
    

    and adding a pointer like this:

    vtx.push_back( shared_ptr( &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. enter image description here

提交回复
热议问题