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.
static SomeType st;
static shared_ptr<SomeType> pt{ &st };
When pt
is destroyed at the end of your process' lifetime, it will delete st
. st
was never allocated with a matching new
. This is undefined behavior.
shared_ptr
is useful for managing the complex lifetime of shared objects while static
objects have very simple lifetimes. It is incorrect to use shared_ptr
to manage static
objects and there would be nothing to gain in doing so.
let's assume that I (as the class author) don't know whether the object is static or dynamic
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.
static SomeType st;
static shared_ptr<SomeType> pt{ &st };
This is just fine:
static SomeType st;
static shared_ptr<SomeType> pt{ std::shared_ptr<SomeType>{}, &st };
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With