如何在带有引用的方法中返回 shared_ptr nullptr?

我的代码如下:

template<class T>
static shared_ptr<T>& getSharedPtr(lua_State* L, int32_t arg)
{
    return *static_cast<shared_ptr<T>*>(lua_touserdata(L, arg));
}

这个方法返回 shared_ptr 的一个引用,因此当以下函数超出作用域时,实际的引用计数器会减少:

int32_t luaADelete(lua_State* L) {
    auto& a = getSharedPtr<A>(L, 1); // 未增加引用计数
    if (a) {
        a.reset(); // 真实 shared_ptr 减少引用计数
    }

    return 0;
}

一切都运行得很好,但我遇到了一个问题,即我想能够在堆栈上的对象不是有效 userdata 的情况下返回 nullptr,然而这种情况下我不能在特定的方法中返回 nullptr,因为它总是想要返回一个引用。 static shared_ptr<T>& getSharedPtr(lua_State* L, int32_t arg)

以下方法可以工作,但看起来非常丑陋,我不知道这是否是正确的做法:

template<class T>
static shared_ptr<T>& getSharedPtr(lua_State* L, int32_t arg)
{
    if (!is<T>(L, arg)) {
        static shared_ptr<T> shared_empty;
        return shared_empty;
    }

    return *static_cast<shared_ptr<T>*>(lua_touserdata(L, arg));
}

我知道这种情况可以通过直接返回实际指针来处理,但我不希望它以这种方式工作,因为写起来更麻烦:

// shared_ptr->get()->method(...); 不好!

// shared_ptr.get(); 好!
// shared_ptr->method(...); 好!

如果有人能帮我,我将非常感激,我一直在搜索互联网,但我找不到类似的东西,所以我决定在这里写这个问题,非常感谢,祝你好运!

这是一个示例代码,您可以在线编译和测试它,以便更容易地帮助我:https://godbolt.org/z/of4cTMG5e

原文链接 https://stackoverflow.com/questions/69875068

点赞