简体   繁体   中英

Conserving memory/programming efficiently when using `std::shared_ptr`

I am trying to create a bunch of shared pointers and put them into various containers.

Using raw pointers I would think to do the following:

Container a, b, c;
MyClass *ptr;
while(!finishedCreating){
    ptr = new MyClass(SOME_CHANGING_THING);
    a.add(ptr);
    b.add(ptr);
    c.add(ptr);
}

But of course now if I want to destruct a , b , and c I would need to delete the pointers that they contain. If I did the following:

~Container{
    delete[] myListOfPointers;
}

I would get an error when destructing because deleting a would delete the same memory that b and c are supposed to get rid of.

Enter smart pointers, specifically, std::shared_ptr . I would like to do something similar to before where I can create a single entity and use it to point to tons of memory locations but I'm not sure how to do this?

Would I want to create a pointer to a std::shared_ptr so that I can reallocate that pointer such as

std::shared_ptr<MyClass> *ptr = new std::shared_ptr<MyClass>(new MyClass(THING));

shared_ptr are here to allocate memory for you... Do not use new with them !

The basic usage would be:

std::shared_ptr<MyClass> ptr(new MyClass(THING));

But even better:

auto ptr = std::make_shared<MyClass>(THING);

The latter provide a lot more guarantee over exception handling and also ensure you won't use new anymore.

Your container will now be something like:

typedef std::vector<std::shared_ptr<MyClass>> Container;

For more information read shared_ptr on cppreference .

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