Std :: Array with unique_ptr

时间:2016-09-19 13:56:32

标签: c++ arrays templates smart-pointers

我有一个类,我希望通过传递一个值数组来实例化它。这里的对象有两个成员,但为了说明这已经减少了。将来我将从磁盘读取值,然后从这些值创建一个对象,从而创建数组。该对象稍后会有多个指针,因此shared_ptr。

首先,我想知道这是否会阻止内存泄漏。其次,我想知道是否有更少膨胀的方法来实例化对象,然后在以后确定性地销毁它们。

类头文件:

//MyClass.hpp
#pragma once
#include "stdafx.h"
#include <array>

class SimpleClass{
    private:
        //Per object
        double var1;
        double var2;
    public static:
        //For calling when using templates such as std::array<>
        //Using __int8 as will not be > 256
        static const uint8_t varCount 2;
        SimpleBody(std::array<double, varCount> inputArray);
        ~SimpleBody();
}

班级实施

//MyClass.cpp
#pragma once
#include "stdafx.h"
#include <array>
#include "body.hpp"

SimpleBody::SimpleBody(std::array<double, SimpleBody::varCount> inputArray ) {
    //Assign var1
    MyClass::var1= inputArray[0];
    //Assign var2
    MyClass::var2= inputArray[1];
};

SimpleBody::~SimpleBody() {
    //Add in code here when children need deleting
}; 

入口点

// EntryPoint.cpp
//

#include "stdafx.h"
#include "MyClass.hpp"
#include <array>
#include <memory>

int main()
{
    //Create an array with a smart pointer for memory management
    std::unique_ptr< std::array<double, MyClass::varCount> > initArray =
        std::make_unique< std::array<double, MyClass::varCount> >();
    //Define values
    *initArray = { 1.0,2.0 };
    //Use array to create object
    std::shared_ptr<MyClass> object = std::make_shared<MyClass>(*initArray );

    //Free memory
    initArray.reset();
    object.reset();

    return 0;
}

2 个答案:

答案 0 :(得分:2)

首先,如果你在SimpleBody构造函数中按值传递数组,那就太糟糕了。更好地使用参考

 SimpleBody(const std::array<int, varCount> &inputArray);

目前,您构建了shared_ptr,unique_ptr失去了数组的所有权。您不需要手动重置。此外,目前,你的程序命中}行,内存将被释放。

答案 1 :(得分:2)

在您的示例中,您可以跳过唯一指针,因为您只想要值

int main()
{
    std::array<double, MyClass::varCount> initArray = { 1.0,2.0 };
    std::shared_ptr<MyClass> object = std::make_shared<MyClass>(initArray );
    return 0;
}

这样做也是如此。

对于&#34;少臃肿&#34;:

始终有auto

int main()
{
    auto initArray = std::make_unique< std::array<double,  MyClass::varCount> >();
    *initArray = {1.0,2.0};
    auto object = std::make_shared<MyClass>(*initArray );
    return 0;
}