Is there any way to destroy a std::shared_ptr
from within a function? In the following example if I set the sptr
to nullptr
in main()
it "destroys" the object so calling it's Print()
fails. However, doing so inside the Delete()
function doesn't do this. Guessing it increments it's ref count as it's passed in. I get that's the idea, BUT is there any way to override that and decrease that ref count inside Delete()
so the obj = nullptr
destroys it in this case?
I get this isn't normally what you'd want to do, but this is a case where an external scripting language needs to be able to call a function to actually destroy the pointed to object so having a Delete(obj)
would be ideal.
#include <memory>
#include <string>
#include <iostream>
using namespace std;
class Test{
private:
string name;
public:
Test(string _name) { name = _name; }
void Print() const { cout << name; }
};
void Delete(std::shared_ptr<Test> obj)
{
obj = nullptr;
}
int main(){
shared_ptr<Test> sptr(new Test("Test"));
Delete(sptr);
//sptr = nullptr;
sptr.get()->Print();
}