jeudi 23 juin 2016

How do I prevent the memory loose from unique_ptr

This code below will result in memory loss because rA is initialized as invalid when it is constructed. When can I do to fix this problem?

Use shared_ptr or hope for future compiler versions to catch this bad code?

#include <memory>
using namespace std;

struct A {};
void use(const A& a) {};

unique_ptr<A> foo()
{
    unique_ptr<A> pa(new A());
    return pa;
} // The temporary unique_ptr is destructed here since it goes out of scope

int main()
{
    const A& rA = *foo();
    use(rA);
}

Aucun commentaire:

Enregistrer un commentaire