Home > database >  Allocating on heap and then use shared pointer, how to free the data
Allocating on heap and then use shared pointer, how to free the data

Time:10-27

I have the following scenario. I have a allocated a chunk of data using new, then assigned the block of data to a smart pointer in the class DNA_ImageBlob, how do I free T*blob data ?

template <class T>
void DNA_ImageBlob<T>::Reset(int h, int w, int c)
{
    SetWidth(w);
    SetHeight(h);
    SetDepth(c);
    T *blob = alocData(h, w, c);
    data_ = std::make_shared<T>(blob);
    compressed_ = false;
}

template <class T>
T *DNA_ImageBlob<T>::alocData(unsigned int h, unsigned int w, unsigned int d)
{
    if (w * h * d == 0)
    {
        return nullptr;
    }
    T *blob = new T[w * h * d];
    return blob;
}

and the usage of that class is in :

DNA_Mask::DNA_Mask(int id, int xSize, int ySize, int zSize)
        : DNA_BinaryImageBlob(xSize, ySize, zSize)
    {
        mID = id;
        height_ = xSize;
        width_ = ySize;
        depth_ = zSize;
        data_ = std::shared_ptr<BinaryType>(this->alocData(height_, width_, depth_));

CodePudding user response:

Here is an example, if you have questions just ask.

#include <vector> 
#include <cstdint>
#include <iostream>

// Blob is a RAII class, meaning its destructor will 
// cleanup all resources it owns (in this case memory held by vector)
class Blob
{
public:
    Blob(std::size_t width, std::size_t depth, std::size_t height) :
        m_blob_data(width * depth * height, 0) // allocates memory and sets it to 0. (last parameter is optional)
    {
    }

    // provide read only access to data
    const auto& get_data() const noexcept
    {
        return m_blob_data;
    }

    ~Blob() = default; 

private:
    std::vector<std::uint8_t> m_blob_data; // when destructor is called, vector gets destructed which will free memory
};

int main()
{
    // start a scope (yes this has meaning in C  , and is important with respect to RAII)
    {
        Blob blob{ 2,2,2 };
        std::cout << blob.get_data().size() << "\n"; // 2*2*2 = 8 items.
    } // blob goes out of scope here, so from here on memory is freed.

    return 0;
}
  •  Tags:  
  • c
  • Related