[c ++ std :: weak_ptr堆栈对象

问题描述 投票:0回答:1

我需要一个指向可能超出范围的堆栈对象的指针。有人告诉我,弱指针可以实现此目的,但是以下代码引发了段错误:

#include <memory>
#include <cassert>
int main()
{

    std::weak_ptr<int> wp;

    {
        auto a = 4;

        wp = std::shared_ptr<int>(&a, [](auto){});
        assert(*wp.lock().get() == 4);
    }

    assert(wp.lock().get() == nullptr);

    return 0;
}

这是为什么?

edit

我找到了一个似乎可行的解决方案。

#include <memory>
#include <cassert>
int main()
{

    std::weak_ptr<int> wp;

    {
        auto a = 4;

        auto sp = std::shared_ptr<int>(&a, [](auto){});
        wp = sp;
        assert(*wp.lock().get() == 4);
    }

    assert(wp.lock().get() == nullptr);

    return 0;
}

但是评论者告诉我,这是未定义的行为。为什么这样做,为什么UB?]

c++ smart-pointers
1个回答
0
投票

这是不正确的。 std::weak_ptr无法判断堆栈对象何时超出范围。


0
投票

std::weak_ptr应该与std::shared_ptr结合使用。您不能将其与任意堆栈分配的对象一起使用。


0
投票

我已经找到解决方法。

#include <memory>
#include <cassert>
int main()
{

    std::weak_ptr<int> wp;

    {
        auto a = 4;

        auto sp = std::shared_ptr<int>(&a, [](auto){});
        wp = sp;
        assert(*wp.lock().get() == 4);
    }

    assert(wp.lock().get() == nullptr);

    return 0;
}

但是我不知道为什么会这样。

© www.soinside.com 2019 - 2024. All rights reserved.