-2

I am self-learning C++ and have got a piece of C++ code which reads like:

boost::make_shared<Something<Some_Other_thing> >()

I failed to comprehend what the above line is doing and why it may be required.

What would be an alternative way to achieve the same?

Could you please help me to understand in relatively simple language?

Any pointer will be highly appreciated.

underscore_d
  • 5,331
  • 3
  • 29
  • 56
Daniel
  • 121
  • 4
  • We really can't tell what it does without knowing what type it creates. It's important to understand what the constructor and destructor of that type does. Otherwise, you will get an answer that may leave you still confused. – David Schwartz Sep 10 '20 at 15:21
  • 4
    What about it don't you understand? Did you read the documentation for the function? Do you know what a function template is? Do you know how to explicitly specify the template parameter(s) for a function template? – NathanOliver Sep 10 '20 at 15:21
  • "Any *pointer*" -- heh. – Quentin Sep 10 '20 at 15:49

1 Answers1

-1

By calling that function you are creating a shared pointer to Something<Some_Other_thing> type. A shared smart pointer is used to manage resources, when there are no more variables holding that pointer, the resource is deleted. More info here and here

Andrea Nisticò
  • 333
  • 1
  • 2
  • 9
  • 1
    This doesn't give the real answer, i.e. why one would use `make_shared()` instead of just `boost::shared_ptr< Something >( new Something )`. The answers are (a) that looks horrible & `make_shared()` avoids the repetition, (b) one should basically never need to write `new` or `delete` in client code, & (c) `make_shared()` can allocate the use-count with the object, whereas the construct-from-`new` way of phrasing can't. These have all been answered already though, but I don't know that I found the best duplicate of it yet. Also, now it's `std::shared_ptr`. – underscore_d Sep 10 '20 at 15:31
  • @underscore_d - Okay. Now I understand that the line "boost::make_shared >()" is basically creating a new shared-pointer to some object of class "Something >". But, I still don't understand that, what is name of that pointer? Why is it not clearly defined? Or, is it not required to define explicitly? In that case, how can I later access/manipulate that pointer? – Daniel Sep 11 '20 at 12:48
  • @Daniel It was not clear in your Q whether you omitted the variable name or the code did, as you also said "like" and gave fake type names. If the code did that, it will just construct and destroy the object in the same line, which might have some side effect that is useful but seems odd as normally one would wrap such effects in a function, not a transient instance of an object. And even in the object case, stack allocation might suffice, unless it is somehow so large that such is infeasible. And without side effects it should be optimised away. Bottom line I think: just ask the code's author – underscore_d Sep 12 '20 at 13:55