#include <iostream>
#include <memory>
using namespace std;
shared_ptr<string> func()
{
shared_ptr<string> ptr = make_shared<string>("smart poiter");
return ptr;
}
int main(int argc, char const *argv[])
{
func();
cout << "pause" << endl;
return 0;
}
like code above, will the memory of string "smart poiter" be released?
Yes. shared_ptr
s aren't special here; any instance's destructor will be invoked promptly (when the statement finishes evaluation) if the instance is returned without being assigned; not doing so would break RAII in a critical way. shared_ptr
's destructor decrements the reference count, no other instances own a reference, so the destructor will release the associated memory.