shared_ptr不能为null?

Tob*_*ann 7 c++ smart-pointers invariants null-pointer preconditions

使用std::shared_ptr表达共享所有权和可选性(可能为null).

我发现自己处于只想在代码中表达共享所有权的情况,而且没有选择性.当使用a shared_ptr作为函数参数时,我必须让函数检查它是否为null以保持一致/安全.

在许多情况下,传递引用而不是当然是一种选择,但我有时也希望转移所有权,因为它可以使用shared_ptr.

是否有一个类可以替换shared_ptr而没有可能为null,一些常规来处理这个问题,或者我的问题没有多大意义?

Pio*_*ycz 8

你要求not_null包装类。幸运的是你的问题已解决由C ++专家指导,并已经有例子的实现-这样的一个。搜索not_null类模板。


Sim*_*mer 5

您可以编写一个std::shared_ptr只允许从非空创建的包装器:

#include <memory>
#include <cassert>

template <typename T>
class shared_reference
{
    std::shared_ptr<T> m_ptr;
    shared_reference(T* value) :m_ptr(value) { assert(value != nullptr);  }

public:
    shared_reference(const shared_reference&) = default;
    shared_reference(shared_reference&&) = default;
    ~shared_reference() = default;

    T* operator->() { return m_ptr.get(); }
    const T* operator->() const { return m_ptr.get(); }

    T& operator*() { return *m_ptr.get(); }
    const T& operator*() const { return *m_ptr.get(); }

    template <typename XT, typename...XTypes>
    friend shared_reference<XT> make_shared_reference(XTypes&&...args);

};


template <typename T, typename...Types>
shared_reference<T> make_shared_reference(Types&&...args)
{
    return shared_reference<T>(new T(std::forward<Types>(args)...));
}
Run Code Online (Sandbox Code Playgroud)

请注意,operator=还缺少。你绝对应该添加它。

你可以这样使用它:

#include <iostream>


using std::cout;
using std::endl;

struct test
{
    int m_x;

    test(int x)         :m_x(x)                 { cout << "test("<<m_x<<")" << endl; }
    test(const test& t) :m_x(t.m_x)             { cout << "test(const test& " << m_x << ")" << endl; }
    test(test&& t)      :m_x(std::move(t.m_x))  { cout << "test(test&& " << m_x << ")" << endl; }

    test& operator=(int x)          { m_x = x;                  cout << "test::operator=(" << m_x << ")" << endl; return *this;}
    test& operator=(const test& t)  { m_x = t.m_x;              cout << "test::operator=(const test& " << m_x << ")" << endl; return *this;}
    test& operator=(test&& t)       { m_x = std::move(t.m_x);   cout << "test::operator=(test&& " << m_x << ")" << endl; return *this;}

    ~test()             { cout << "~test(" << m_x << ")" << endl; }
};

#include <string>

int main() {

    {
        auto ref = make_shared_reference<test>(1);
        auto ref2 = ref;

        *ref2 = test(5);
    }
    {
        test o(2);
        auto ref = make_shared_reference<test>(std::move(o));
    }

    //Invalid case
    //{
    //  test& a = *(test*)nullptr;
    //  auto ref = make_shared_reference<test>(a);
    //}
}
Run Code Online (Sandbox Code Playgroud)

输出:

test(1)
test(5)
test::operator=(test&& 5)
~test(5)
~test(5)
test(2)
test(test&& 2)
~test(2)
~test(2)
Run Code Online (Sandbox Code Playgroud)

Coliru 示例

我希望我没有忘记任何可能导致未定义行为的事情。