简体   繁体   中英

Is it safe to return a vector of std::shared_ptr?

Is my code in risk of memory-leak for returning vector of std::shared_ptr? I think it's safe because the reference count will not be zero till the end of main function. Am I right?

#include <iostream>
#include <vector>
#include <memory>

using namespace std;

class A {
    public:
    A(int v):a(v){}
    int a;
};

typedef std::shared_ptr<A> APtr;

vector<APtr> test() {
    APtr x(new A(1));
    APtr y(new A(2));
    APtr z(new A(3));
    APtr a(new A(4));
    return vector<APtr>({x, y, z, a});
}

int main()
{
   cout << "Hello World" << endl; 
   vector<APtr> b = test();
   for(auto k : b) {
       cout << k->a << "\n";
   }
   return 0;
}

Yes, this is safe and memory-leak free. Your test function creates the pointers, and they'll all have a reference count of one. Once the function returns, they're copied into b which increases the reference count, then they go out of scope and decrease the reference count back down to 1. The A are all cleaned up correctly at the end of main .

Putting a breakpoint (or cout statement) in ~A should also show you this correctly. One final minor note, you should prefer make_shared over new

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM