I have a leaky code like this:
void f() {
SomeClass *sc = new SomeClass;
...
if (...) {
g(sc); // g() takes ownership of memory pointed to by sc
}
...
sc->SomeMethod();
...
}
I'd like to eliminate leaks by using smart pointers, thought of the following solution:
void f() {
smart_ptr<SomeClass> sc(new SomeClass);
...
if (...) {
g(sc.release()); // ownership is taken
}
...
sc->SomeMethod(); // sc points to the allocated memory regardless of whether ownership was taken or not
...
} // the memory is freed if ownership was not taken
Tried to use std::unique_ptr and std::shared_ptr. std::unique_ptr points to the null pointer after release, std::shared_ptr has no release() at all. Manual increase of reference counter of std::shared_ptr would have helped, but as I understand correctly there is no such an ability too.
Thought of using std::unique_ptr in addition to the raw pointer leaving the code as is and just calling release() each time the raw pointer is passed to the function that takes ownership, but it is a very muddy solution.
I wonder if there is a smart pointer from the standard library that fit for my goals, or maybe there is an ideom or common trick how to do in my case or may I missing something?
unique_ptr
and a raw pointer, it's the simplest solution. You do need to ensure thatg()
doesn'tdelete
the object before you callSomeMethod()
via the raw pointer. – Praetorianf()
is large, the pointer is frequently used and the ownership is transferred several times. – ayartsev