+ 1
How to ensure function does not modify shared pointer
How to avoid function modifying shared or unique pointer modified by using ptr.reset
10 Respostas
+ 1
My question might not be drafted correctly or precisely.
It's not I want to reset. I want that function should not change ptr. It can change if we use reset.
Reset will throw error when function takes const ref . This is what I wanted.
+ 1
Ketan Lalcheta
I tried pass by value and the count did not go down
my intuition is because it is a copy, the counter also goes up by 1, so reset will only reset the copy inside the function. and you don't affect the original pointer.
but maybe it is what you need. I'm not saying it's the wrong way. it depends on what you're doing. maybe you just need a temporary copy.
0
check if pointer is null?
0
My bad. It works well and can discard this question.
https://sololearn.com/compiler-playground/cepsd2zZkYG5/?ref=app
I wanted to restrict last line of function and can do so by keeping const shared pointer ref as function argument.
0
wouldn't it make sense to first do a null check?
https://sololearn.com/compiler-playground/caC7H08qS4fy/?ref=app
0
ok, but in your code, ptr.reset() is not actually doing anything. you can remove it and everything works the same way. so why use it?
0
To ensure a function does not modify a std::shared_ptr or std::unique_ptr in a way that changes its ownership or target object (like calling ptr.reset()), you should pass the pointer by value or by const reference. https://www.liteblue.it.com
0
Bonnie219Bailey
(it's probably a bot, because it's adding an unrelated link...)
passing the pointer by value makes ptr.rest() useless. ptr.reset() doesn't actually reset if you do it this way.
passing it as const reference will throw you an error if you use ptr.reset().
the only sensible way is to pass it by reference if you're actually going to use ptr.reset(). relinquishing ownership is the point of using it.
0
Thanks Bob_Li
If it was pass by value, will it not reset ?
Not tried but my thought process :
Pass by value means copy of shared pointer
This copy points to same value on heap
Function comes out of it , but will it not be modified heap details ?