Is shared_ptr always passed as reference? | Sololearn: Learn to code for FREE!

+2

Is shared_ptr always passed as reference?

Hi Please refer below code : Method changes object outside of the function body as well because shared pointer refer to same memory location. In this way , we can get call by reference behaviour. Is there a way to discard changes done by the method TestObject? https://code.sololearn.com/c42Ri7U5YcHs/?ref=app

5/21/2021 5:01:10 PM

Ketan Lalcheta

3 Answers

New Answer

+4

You just make another shared_pointer that refers to the same object. If you use p.use_count() in the function, it will output 2, which are p in TestObject() and sp in main(). If you take the reference, it will output 1. I don't think it's possible to discard the change with only smart pointers as they point to the same object, so instead of taking a shared_ptr<test> parameter, taking a test is ideal.

+2

Seems so that it is not possible to discard the changes. But should we go ahead and create row pointer just to achieve this? Also it will ask for method signature change as well

+2

No I don't think it's possible and I don't see why anyone would want to do that. I mean let's forget that we are using smart pointers and let's assume that we are using the good old raw( C-stye ) pointers. It would not make much sense to expect that the TestObject function takes a pointer to a particular memory location and any changes made using that pointer won't affect the original variable. So, I don't it's possible to discard changes made by the TestObject function