Set shared_ptr to specify an existing object

In the code below, I would like to know how to set std::shared_ptrto indicate these objects in two member functions. An object Vector3that is allocated in the main function will not be deleted until the end of the program.

#include <memory>
#include <vector>

using std::vector;
using std::shared_ptr;

class Vector3
{
    // ...
};

class Face
{
    vector < shared_ptr <Vector3> > vtx;

    public:

    void addVtx (const Vector3& vt)
    {
        // vtx.push_back (); <-- how to push_back ?
    }

    void setVtx (const int v, const Vector3& vt)
    {
        if ( vtx.size() > 0 && v < vtx.size() )
        {
            // vtx[v] = &vt; <-- how to assign ?
        }
    }

};

int main ()
{
    vector <Vector3> vec (3);
    Face face;

    face.addVtx (vec[0]);
    face.setVtx (0, vec[0])

    return 0;
}
+4
source share
2 answers

It makes no sense to use shared_ptrfor an automatically assigned object.

Technically, you can do this by providing a shared_ptrdeletor that does nothing, and changing yours vtxas a vector of generic pointers to vectors const.

eg. change ad to

vector < shared_ptr <Vector3 const> > vtx;

and adding a pointer as follows:

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

: , .

, , , raw-. in-data.


. .

, , . .

. enter image description here

+7

, shared_ptr , , , 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);
    }
}
0

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


All Articles