c ++如何断言向量中的所有std :: shared_ptr都指的是某些东西

时间:2016-12-08 10:43:53

标签: c++ c++11 vector shared-ptr assert

当我有一个函数接收一个应该引用某个东西的(智能)指针时,我总是按如下方式开始:

class Foo;
void doSomething(const std::shared_ptr<Foo>& pFoo)
{
    assert(pFoo);
    // ...
}

现在我正在为(智能)指针的向量(或其他容器)寻找类似的断言条件。我能想到的最好的是:

void doSomething(const std::vector<std::shared_ptr<Foo> >& pFoos)
{
    assert(std::all_of(pFoos.begin(), pFoos.end(), [](const std::shared_ptr<Foo>& pFoo) { return pFoo; }));
    // ...
}

我想知道这是否可以改善..可以避免lambda吗? (我尝试使用shared_ptr的get()方法,但模板推导失败)或者是否存在另一种断言整个容器的方法?

3 个答案:

答案 0 :(得分:10)

另一种方法:

assert(std::find(pFoos.begin(), pFoos.end(), nullptr) == pFoos.end());

答案 1 :(得分:9)

仅使用标准功能表达它的另一种有点复杂的方式:

assert(std::none_of(pFoos.begin(), pFoos.end(), std::logical_not<std::shared_ptr<Foo>>{}));

从C ++ 14开始,您可以使用std::logical_not

的通用专精
assert(std::none_of(pFoos.begin(), pFoos.end(), std::logical_not<>{}));

答案 2 :(得分:1)

您可以使用实现自己的实用程序谓词:

struct is_nullptr
{
    template <typename T>
    bool operator()(T&& x) const noexcept { return x == nullptr; }
};

void doSomething(const std::vector<std::shared_ptr<Foo> >& pFoos)
{
    assert(!std::any_of(pFoos.begin(), pFoos.end(), is_nullptr{});
    // ...
}

和/或你自己的“范围断言”:

template <typename TContainer, typename TPredicate>
void range_assert(TContainer&& container, TPredicate&& p)
{
    for(auto&& x : container)
    {
        assert(p(x));
    }
}

void doSomething(const std::vector<std::shared_ptr<Foo> >& pFoos)
{
    range_assert(pFoos, [](const std::shared_ptr<Foo>& x) { return x; });
    // ...
}