+ 1

How to ensure function does not modify shared pointer

How to avoid function modifying shared or unique pointer modified by using ptr.reset

14th Jul 2025, 11:44 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
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.
14th Jul 2025, 3:42 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 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.
16th Jul 2025, 11:24 AM
Bob_Li
Bob_Li - avatar
0
check if pointer is null?
14th Jul 2025, 2:25 PM
Bob_Li
Bob_Li - avatar
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.
14th Jul 2025, 3:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
wouldn't it make sense to first do a null check? https://sololearn.com/compiler-playground/caC7H08qS4fy/?ref=app
14th Jul 2025, 3:39 PM
Bob_Li
Bob_Li - avatar
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?
14th Jul 2025, 3:55 PM
Bob_Li
Bob_Li - avatar
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
16th Jul 2025, 8:55 AM
Bonnie219Bailey
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.
16th Jul 2025, 9:14 AM
Bob_Li
Bob_Li - avatar
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 ?
16th Jul 2025, 10:00 AM
Ketan Lalcheta
Ketan Lalcheta - avatar