Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make std::shared_ptr not call delete()

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.

like image 971
Ken Li Avatar asked Nov 21 '13 21:11

Ken Li


People also ask

Do I have to delete shared_ptr?

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.

What does shared_ptr get () do?

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.

What happens when shared_ptr goes out of scope?

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.

Why is shared_ptr unique deprecated?

this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.


2 Answers

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)); } 
like image 42
Angew is no longer proud of SO Avatar answered Oct 11 '22 09:10

Angew is no longer proud of SO


MyType t; nasty_function(std::shared_ptr<MyType>(&t, [](MyType*){})); 
like image 169
ronag Avatar answered Oct 11 '22 11:10

ronag