Any advantage of using shared_ptr over scoped_ptr at the top level?

My team has some controversy regarding the use of a pointer container for a specific context. Please consider:

int main() { // Top level. This is an important fact to the context // ie that the following instance is at this level // so that its members are essentially at program scope. MainClass mainClass; mainClass.run(); } // A instance of a class derived from Buffer does something very complex // (it has various handles to resources/allocated memory) so that you would // never want to copy an instance. class Buffer; class MainClass { #make_decision_here_based_on_stack_overflow_responses shared_ptr<Buffer> buffer; // 1 scoped_ptr<Buffer> buffer; // 2 #end_decision MainClass() { // non-trivial initialisation of buffer with any of a number of derived classes: buffer.reset( ... ) } void run() { #make_decision_here_based_on_stack_overflow_responses SomeSubservientClass sub(*buffer); // a SomeSubservientClass sub(buffer.get()); // b SomeSubservientClass sub(buffer); // c #end_decision sub.do_stuff() } }; 

(I hope you can understand here the special preprocessor code that actually does not exist, but it would be nice if it :)

The code we have is currently in state “1b” (member of shared_ptr, pass down bare ptr), but we think this is not the way it should be. I would be interested to know what someone thinks at first glance would be the most natural / reasonable and safe thing and excuse. Or if someone wants to suggest "3" or "d". I have my own opinion, but I do not want to share it.

+4
source share
1 answer

Choosing a smart pointer is a choice of ownership strategy. You should ask yourself this question:

  • Is MainClass sole owner of the Buffer instance? Or does it make sense for the Buffer instance stored in MainClass to survive the MainClass object? (Or would it be reasonable if MainClass became a component of a larger system and lost the status of the application-life?)

If the answer makes sense, go with a generic pointer. If the answer is the sole owner / does not make sense, use what expresses a unique property - scoped_ptr (or std::unique_ptr , if available).

If you get a unique property, use the 'a' option to transfer the property. A function should only ever take a pointer parameter if the null pointer is valid for it.

If you end the co-ownership, two situations are possible. To transfer the buffer to locations sharing property, skip shared_ptr . To transfer it to places that simply observe / change, use "a" as above.

+7
source

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


All Articles