I have functions that take in std::shared_ptr as an argument so I am forced to use std::shared_ptr, but the object I am passing to the function is not dynamically allocated. How do I wrap the object in std::shared_ptr and have std::shared_ptr not call delete on it.
So no, you shouldn't. The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.
A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.
The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.
this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.
Specify a no-op deleter when creating the shared pointer. E.g. like this:
void null_deleter(MyType *) {} int main() { MyType t; nasty_function(std::shared_ptr<MyType>(&t, &null_deleter)); }
MyType t; nasty_function(std::shared_ptr<MyType>(&t, [](MyType*){}));
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