繁体   English   中英

当类同时包装STL容器和指针时,是否应该在类的析构函数中销毁STL容器?

[英]Should I destroy STL containers in my class's destructor, when the class wraps both a STL container and a pointer?

我有点理解这样的事实,当该类的实例超出范围时,该类的包装STL容器将被自动销毁。 因此,当类仅包装STL容器时,我不必编写析构函数。 但是,如果该类还必须管理一些指针,该怎么办?

在某些CUDA开发中,我想要一个类来处理设备指针和STL容器。

class Image{
    private:
        float *data_device;
        std::array<int, 2> shape;
    public:
        // some constructors and methods
        ~Image(){
            cudaFree(data_device);
            // what to do with the STL array?
        }
};

在上述情况下,我需要析构函数为data_device释放内存。 但是我应该处理STL数组吗? 如果是这样,我如何正确地破坏shape

但是我应该处理STL数组吗?

不,你不应该。

std::array析构函数自动销毁std::array每个元素。

您应该创建一个析构函数来手动拆除您班级管理的所有内容。

但是,这样做不会阻止其他所有内容的破坏。 析构函数运行 ,您的成员仍将自动被破坏; 您的析构函数是另外的

所以您做对了。

您可以想象一下,析构函数的右大括号还具有对每个成员(和基础)析构函数的调用,其调用顺序与构造相反。

因此,您无需对所有std容器都正确设计的成员做任何额外的事情。 但是,让我们备份一下。

但是,如果该类还必须管理一些指针,该怎么办?

您不应编写此类。 取而代之的是,您使用一个类的唯一任务是完全管理一个指针,以替代“某些指针”。 另外,您现在不必担心双重释放,因为Image没有默认的副本构造函数

// cuda Deleter for std::unique_ptr
struct CudaFree
{
    void operator()(float * ptr) { cudaFree(ptr); }
}

class Image{
    private:
        std::unique_ptr<float, CudaFree> data_device;
        std::array<int, 2> shape;
    public:
        Image(/* ? */)
          : data_device(cudaAlloc()/* ? */), 
            shape(/* ? */) 
        {/* ? */}
        // similarly other constructors
        // other members
        // implicit destructor does the right thing
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM