shared_ptr throw error:未分配释放的指针

时间:2014-07-25 08:17:35

标签: c++ c++11 malloc shared-ptr

#include <memory>
using namespace std;

shared_ptr<int> tmpfunc1(int* p)
{
    return shared_ptr<int>(p);
}

void tmpfunc2(int * px)
{
    shared_ptr<int> ptr1 = tmpfunc1(px);
}

int main()
{   
    int x = 1;
    tmpfunc2(&x);   
    return 0;
}

以下代码将在tmpfunc2()返回之前中止(并且在销毁ptr1时)。谁能解释一下发生了什么?我认为从tmpfunc1返回的临时对象导致了问题,但无法找出原因。

返回shared_ptr的最佳做法是什么?

谢谢!

更新

感谢大家的回复。我这样做是因为最近我正在开发一个以下面的方式实现的代码库(一个最小的例子):

#include <memory>
#include <vector>
using namespace std;

shared_ptr<int> tmpfunc1(int* p)
{
    return shared_ptr<int>(p);
}

void tmpfunc2(int * px)
{
    shared_ptr<int> ptr1 = tmpfunc1(px);
}


class A
{
public:
    vector<int*> ptrvec;
    vector<shared_ptr<int> > shrptrvec;
    A() {};
    ~A() {};
};

int main()
{
    A a;
    for (int i = 0; i < 100; ++i)
    {
        shared_ptr<int> tmpptr(new int);
        a.ptrvec.push_back(tmpptr.get());
        a.shrptrvec.push_back(tmpptr);
    }
    tmpfunc2(a.ptrvec[0]);

    return 0;
}

此代码仍然会失败,可能是因为只提供a.ptrvec [0],临时shared_ptr没有现有计数器的信息,并且会使a.shrptrvec中的所有shared_ptr指向无效位置。

我说错了吗?

再次感谢大家。

1 个答案:

答案 0 :(得分:3)

Shared_ptr仅适用于动态分配!它无法释放堆栈分配的资源。

#include <memory>
using namespace std;

shared_ptr<int> tmpfunc1(int* p)
{
    return shared_ptr<int>(p);
}

void tmpfunc2(int * px)
{
    shared_ptr<int> ptr1 = tmpfunc1(px);
}

int main()
{   
    int* x = new int(1);
    tmpfunc2(x);

    return 0;
}

可能更好的解决方案

#include <memory>
using namespace std;

void tmpfunc(int px)
{
    shared_ptr<int> ptr1 = make_shared(px);
}

int main()
{   
    int x(1);
    tmpfunc(x);

    return 0;
}
相关问题