C++ 在单元测试中初始化unique_ptr

C++ 在单元测试中初始化unique_ptr,c++,c++11,shared-ptr,smart-pointers,unique-ptr,C++,C++11,Shared Ptr,Smart Pointers,Unique Ptr,我有以下代码: class foo { public: foo(); void setMean(std::shared_ptr<std::valarray<double>> input); private: std::shared_ptr<std::valarray<double>> mean; } 现在,在单元测试文件中: std::shared_ptr<std::va

我有以下代码:

class foo {

    public:
        foo();
        void setMean(std::shared_ptr<std::valarray<double>> input);
    private:

        std::shared_ptr<std::valarray<double>> mean;

}
现在,在单元测试文件中:

std::shared_ptr<std::valarray<double>> input = std::make_shared<std::valarray<double>>(std::initializer_list<double>{0.0, 0.0});

std::unique_ptr<foo> meanObj;

meanObj->setMean(input);
当控件进入setMean函数时,代码中断


唯一ptr的初始化是否有问题?

是的。您需要使用实际对象对其进行初始化,如下所示:

std::unique_ptr<foo> meanObj(std::make_unique<foo>());

否则,您将调用std::unique_ptr的默认构造函数,该构造函数将指向底层的成员设置为nullptr。因此,您对下一行的尊重是空指针取消引用。

是的,您在哪里初始化std::unique\u ptr

您不是,这就是为什么std::unique_ptr将指向nullptr,并且您不能遵从它,因此您将遇到分段错误

使用std::make_unique初始化它:


使用原始指针重写的示例的最后两行是

foo* meanObj = nullptr;
meanObj->setMean(input);
你看到问题了吗?你正在取消对nullptr的引用。您需要首先创建一个由unique_ptr管理的foo对象

您没有将meanObj设置为指向/拥有任何东西。您需要使用foo对象初始化智能指针

如果您不使用C++14,并且不想在声明的同一位置初始化您的唯一\u ptr,您可以这样做

meanObj.reset( new foo() );

我知道你已经接受了答案,但从我看来,你根本不需要使用唯一的ptr。只需使用对象本身:

foo meanObj;
meanObj.setMean(input);

你在哪里初始化meanObj?实际上任何地方都没有foo对象为什么你甚至需要一个唯一的\u ptr?只需做foo meanObj;meanObj.setMeaninput;谢谢你的回答。由于某些原因,我不能使用std::make_unique。但是使用另一种方法,它是有效的。@chintans make_unique是在C++14中添加的,因此您需要一个支持该版本的stdlib实现。我发布的代码是一个精简版本,实际的代码太复杂了。
auto meanObj(std::make_unique<foo>());
// or std::unique_ptr<foo> meanObj(new foo);
meanObj->setMean(input);
meanObj.reset( new foo() );
foo meanObj;
meanObj.setMean(input);