I'm wondering whether smart pointers on static objects are reasonable. For example let's say I have some static resource and want to pass a reference to that static resource to some other objects which need these resource to work with.
One way would be to use the RAW-Pointers pointing to that resource. But now I'm wondering whether smart pointers (shared_ptr) are the better way and if so, how to do it correctly. (should the smart pointer be static as well?).
Background of the question: if no more objects holding a smart pointer anymore, the static object which the smart pointer is point to, would be freed (which is not the best idea...).
One example (which ends in a crash at the end of runtime):
struct SomeType {
SomeType() { cout << "ctor..." << endl; }
~SomeType() { cout << "dtor..." << endl; }
void sayHello() { cout << "Hello!" << endl; }
};
void someFunction(shared_ptr<SomeType> smartPointer) {
smartPointer->sayHello();
}
static SomeType st;
static shared_ptr<SomeType> pt{ &st };
void anotherFunction() {
someFunction(pt);
}
int main() {
anotherFunction();
cin.get();
}
The following two lines are not valid.
When
pt
is destroyed at the end of your process' lifetime, it willdelete st
.st
was never allocated with a matchingnew
. This is undefined behavior.shared_ptr
is useful for managing the complex lifetime of shared objects whilestatic
objects have very simple lifetimes. It is incorrect to useshared_ptr
to managestatic
objects and there would be nothing to gain in doing so.Code that needs to be agnostic absolutely should use
shared_ptr<T>
.This code you gave is invalid, because it causes deletion of an object with static lifetime.
This is just fine:
and that
pt
can be used interchangeably with "normal" shared_ptr instances.std::shared_ptr
is particularly convenient in this regard, because the presence or absence of a deleter doesn't affect the pointer type (in contrast,std::unique_ptr<T, custom_deleter<T>>
is a different type from `std::unique_ptr>)This and other ways to specify a deleter that doesn't do anything are described at: