简体   繁体   中英

Shared pointer of list with shared pointers

I'm implementing big structures (something like struct A has struct B and struct B has struct C and so on...). In one of the nested level, one structure has a pointer to itself. Which solution will be better to manage with this?

struct MyStruct
{
    //1st version
    std::shared_ptr<std::list<std::shared_ptr<MyStruct>>> myStructPrtList;
    //2nd version
    std::list<MyStruct*> *myStructPrtList;
};

I know that managing by raw pointers must take care of creating and deleting objects. What about smart pointers? Are there any dangerous by creating list something like that?

EDIT

This is how this struct will be used:

void createStruct()
{
    //Here will be created pointer to main struct
    std::shared_ptr<StructA> structA = fillStruct();

    //Here get everything what is needed from this struct and this struct wont be used nymore
}

fillStruct function:

std::shared_ptr<StructA> fillStruct()
{
    std::shared_ptr<StructA> structA = std::make_shared<StructA>();
    //Here fill whole structA
    //Somewhere create struct B included in struct A
    structA->structB = std::make_shared<StructB>();
    //Now fill struct B
    //and so on...
    //Now somewhere in nested struct create MyStruct

    //return this whole created struct
    return structA;
}

Thank you for your answers.

The big problem with "pointers to yourself" is that you can end up with an object that holds the last pointer to itself. As this object has no other pointers, it's unreachable and undeleteable.

A slightly more complex variant is when two objects hold a pointer to each other, but no other pointers to them exist. Either of the two would take the other down, but ther's no way to delete the first of the two.

I'm not talking about smart or dumb pointers here, the problem is fundamental. If you're writing Garbage Collection algorithms, you will know this as the "cycle" problem. Object relationships can be expressed using graph theory, and generally these relationships are directional. A owns B, and that usually means B does not own A. But if it does, you have a cycle A->B->A.

One common approach to sidestep the problem is to have a second graph that does not contain cycles. You say you have a nested structure. Perhaps the parent level can own every MyStruct ? And if there's no unique parent that could act as an owner, multiple parents could perhaps use shared_ptr<myStruct> to share ownership - still at a higher level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM