我有以下情況。我使用 new 分配了一塊資料,然后將資料塊分配給 DNA_ImageBlob 類中的智能指標,我如何釋放 T*blob 資料?
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;
}
該類的用法是:
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_));
uj5u.com熱心網友回復:
這是一個例子,如果您有問題,請提出。
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521614.html
標籤:C
上一篇:在C 中確定陣列中的重復項/對
