Create non-shared_ptr?

I am new to C ++ 11, and now I am working on improving my skills in C ++, trying to avoid using direct pointers. I am trying to write a sprite manager that tracks previously loaded sprites and frees unused ones. I am trying to use shared_ptr (pointer to a bitmap image) for this, but the manager should also support shared_ptr to create sprites with - so the link count does not drop to 0. Can I somehow declare the "parent" shared_ptr in my non-own manager, so it is not considered a link (and still creates its own copies of this shared_ptr)?

+6
source share
3 answers

Use weak_ptr . This will solve your problem. You will not need to release them, as they will be automatically released. Use the lock on the slide to get the actual shared_ptr.

Use_count will also provide you with the current number of links.

+11
source

shared_ptr are the owners. If you want a pointer without rights in some part of your program to use weak_ptr like this:

 std::shared_ptr<Object> sp(new Object); std::weak_ptr<Object>(sp); 
+3
source

You are trying to make a backseat driver management style for memory management; you want to use shared-ptr , but you also want to control when shared_ptr frees up resources!

There are a few obvious things you could do here.

  • Just use shared_ptr and don't worry about any memory management or resource ownership in your sprite manager class. Trust shared_ptr to get the job done. If you need to know when a resource is destroyed, you can always use the observer pattern or the like, and your message from the resource class to the manager when it is destroyed. Of course, this means that you cannot ask your sprite manager to provide additional links to an existing sprite, which is not so large.

  • Write your own smart pointer. This is not necessarily trivial, but writing a special pointer for resource-oriented link counting is not rocket science (it's damn simpler than writing, for example, shared_ptr ). Then the manager can stop using the resources when there is only one link to them (for example, his own link).

  • Everyone else has already mentioned weak_ptr . It has all the advantages (1), only you can create additional instances of shared_ptr that reference the same base resource.

You can also consider resource usage patterns and resource loading costs. You may not want to destroy the resource as soon as your application stops referencing it; if it is requested again after a second, it may take some time to restart it. Lazy release of resources when they have not been used for some time may be the best approach. Just a thought.

+1
source

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


All Articles