1
#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?

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
陈培鸿
  • 31
  • 7

2 Answers2

3

Yes. The internal counter will reach 0 and the memory will be released safely.

Ayxan Haqverdili
  • 17,764
  • 5
  • 27
  • 57
2

Yes. shared_ptrs 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.

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184