From 15d09d6c756b46b4d1c296d8bb13b85f82654ef9 Mon Sep 17 00:00:00 2001 From: Niels Dekker Date: Sun, 28 Aug 2022 19:48:41 +0200 Subject: [PATCH] STYLE: Replace `new T[n]` with `make_unique_for_overwrite` in cxx files Replaced `new T[n]` with `make_unique_for_overwrite(n)` calls, for the initialization of local variables in ITK "*.cxx" library files, and removed the corresponding `delete[]` statements. Following C++ Core Guidelines, April 10, 2022, "Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`" https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-smart --- .../Core/Common/src/itkWin32OutputWindow.cxx | 8 +-- .../Common/src/itkXMLFileOutputWindow.cxx | 10 ++- Modules/IO/BioRad/src/itkBioRadImageIO.cxx | 10 +-- Modules/IO/GDCM/src/itkGDCMImageIO.cxx | 38 +++++----- Modules/IO/GIPL/src/itkGiplImageIO.cxx | 23 +++---- .../src/itkNumericSeriesFileNames.cxx | 11 ++- .../ImageBase/src/itkRawImageIOUtilities.cxx | 19 +++-- Modules/IO/LSM/src/itkLSMImageIO.cxx | 8 +-- Modules/IO/MINC/src/itkMINCImageIO.cxx | 15 ++-- .../src/itkFreeSurferAsciiMeshIO.cxx | 6 +- .../src/itkFreeSurferBinaryMeshIO.cxx | 12 ++-- Modules/IO/MeshOBJ/src/itkOBJMeshIO.cxx | 7 +- Modules/IO/MeshOFF/src/itkOFFMeshIO.cxx | 25 ++++--- .../IO/MeshVTK/src/itkVTKPolyDataMeshIO.cxx | 14 ++-- Modules/IO/Meta/src/itkMetaImageIO.cxx | 44 ++++-------- Modules/IO/NIFTI/src/itkNiftiImageIO.cxx | 6 +- .../IO/Stimulate/src/itkStimulateImageIO.cxx | 22 +++--- Modules/IO/TIFF/src/itkTIFFImageIO.cxx | 8 +-- Modules/IO/VTK/src/itkVTKImageIO.cxx | 69 +++++++++---------- Modules/IO/XML/src/itkXMLFile.cxx | 8 +-- 20 files changed, 168 insertions(+), 195 deletions(-) diff --git a/Modules/Core/Common/src/itkWin32OutputWindow.cxx b/Modules/Core/Common/src/itkWin32OutputWindow.cxx index d723aa036a6..4e2b4ceb7bf 100644 --- a/Modules/Core/Common/src/itkWin32OutputWindow.cxx +++ b/Modules/Core/Common/src/itkWin32OutputWindow.cxx @@ -26,6 +26,7 @@ * *=========================================================================*/ #include "itkWin32OutputWindow.h" +#include "itkMakeUniqueForOverwrite.h" namespace itk { @@ -91,7 +92,7 @@ Win32OutputWindow::DisplayText(const char * text) } /** Create a buffer big enough to hold the entire text */ - char * buffer = new char[strlen(text) + 1]; + const auto buffer = make_unique_for_overwrite(strlen(text) + 1); /** Start at the beginning */ const char * NewLinePos = text; @@ -109,14 +110,13 @@ Win32OutputWindow::DisplayText(const char * text) else { int len = NewLinePos - text; - strncpy(buffer, text, len); + strncpy(buffer.get(), text, len); buffer[len] = 0; text = NewLinePos + 1; - Win32OutputWindow::AddText(buffer); + Win32OutputWindow::AddText(buffer.get()); Win32OutputWindow::AddText("\r\n"); } } - delete[] buffer; } /** Add some text to the EDIT control. */ diff --git a/Modules/Core/Common/src/itkXMLFileOutputWindow.cxx b/Modules/Core/Common/src/itkXMLFileOutputWindow.cxx index 5807d4526b5..c6db24e1359 100644 --- a/Modules/Core/Common/src/itkXMLFileOutputWindow.cxx +++ b/Modules/Core/Common/src/itkXMLFileOutputWindow.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkXMLFileOutputWindow.h" +#include "itkMakeUniqueForOverwrite.h" #include #include @@ -64,18 +65,16 @@ XMLFileOutputWindow::DisplayTag(const char * text) void XMLFileOutputWindow::DisplayXML(const char * tag, const char * text) { - char * xmlText; - if (!text) { return; } // allocate enough room for the worst case - xmlText = new char[strlen(text) * 6 + 1]; + const auto xmlText = make_unique_for_overwrite(strlen(text) * 6 + 1); const char * s = text; - char * x = xmlText; + char * x = xmlText.get(); *x = '\0'; // replace all special characters @@ -127,13 +126,12 @@ XMLFileOutputWindow::DisplayXML(const char * tag, const char * text) { this->Initialize(); } - *m_Stream << "<" << tag << ">" << xmlText << "" << std::endl; + *m_Stream << "<" << tag << ">" << xmlText.get() << "" << std::endl; if (m_Flush) { m_Stream->flush(); } - delete[] xmlText; } void diff --git a/Modules/IO/BioRad/src/itkBioRadImageIO.cxx b/Modules/IO/BioRad/src/itkBioRadImageIO.cxx index d1041fc553d..37f4c57e953 100644 --- a/Modules/IO/BioRad/src/itkBioRadImageIO.cxx +++ b/Modules/IO/BioRad/src/itkBioRadImageIO.cxx @@ -28,6 +28,7 @@ #include "itkBioRadImageIO.h" #include "itkByteSwapper.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" #define BIORAD_HEADER_LENGTH 76 #define BIORAD_NOTE_LENGTH 96 @@ -480,17 +481,16 @@ BioRadImageIO::Write(const void * buffer) const auto numberOfBytes = static_cast(this->GetImageSizeInBytes()); const auto numberOfComponents = static_cast(this->GetImageSizeInComponents()); - auto * tempmemory = new char[numberOfBytes]; - memcpy(tempmemory, buffer, numberOfBytes); + const auto tempmemory = make_unique_for_overwrite(numberOfBytes); + memcpy(tempmemory.get(), buffer, numberOfBytes); if (this->GetComponentType() == IOComponentEnum::USHORT) { - ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory), + ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory.get()), numberOfComponents); } // Write the actual pixel data - file.write(static_cast(tempmemory), numberOfBytes); - delete[] tempmemory; + file.write(static_cast(tempmemory.get()), numberOfBytes); file.close(); } diff --git a/Modules/IO/GDCM/src/itkGDCMImageIO.cxx b/Modules/IO/GDCM/src/itkGDCMImageIO.cxx index dab57de4fd6..b770c3b77f0 100644 --- a/Modules/IO/GDCM/src/itkGDCMImageIO.cxx +++ b/Modules/IO/GDCM/src/itkGDCMImageIO.cxx @@ -37,6 +37,7 @@ #include "itksys/SystemTools.hxx" #include "itksys/Base64.h" +#include "itkMakeUniqueForOverwrite.h" #include "gdcmImageHelper.h" #include "gdcmFileExplicitFilter.h" @@ -367,7 +368,7 @@ GDCMImageIO::Read(void * pointer) if (m_SingleBit) { - auto * copy = new unsigned char[len]; + const auto copy = make_unique_for_overwrite(len); unsigned char * t = reinterpret_cast(pointer); size_t j = 0; for (size_t i = 0; i < len / 8; ++i) @@ -383,8 +384,7 @@ GDCMImageIO::Read(void * pointer) copy[j + 7] = (c & 0x80) ? 255 : 0; j += 8; } - memcpy((char *)pointer, copy, len); - delete[] copy; + memcpy((char *)pointer, copy.get(), len); } else { @@ -405,10 +405,9 @@ GDCMImageIO::Read(void * pointer) r.SetSlope(m_RescaleSlope); r.SetPixelFormat(pixeltype); gdcm::PixelFormat outputpt = r.ComputeInterceptSlopePixelType(); - auto * copy = new char[len]; - memcpy(copy, (char *)pointer, len); - r.Rescale((char *)pointer, copy, len); - delete[] copy; + const auto copy = make_unique_for_overwrite(len); + memcpy(copy.get(), (char *)pointer, len); + r.Rescale((char *)pointer, copy.get(), len); // WARNING: sizeof(Real World Value) != sizeof(Stored Pixel) len = len * outputpt.GetPixelSize() / pixeltype.GetPixelSize(); } @@ -756,15 +755,14 @@ GDCMImageIO::InternalReadImageInformation() int encodedLengthEstimate = 2 * bv->GetLength(); encodedLengthEstimate = ((encodedLengthEstimate / 4) + 1) * 4; - auto * bin = new char[encodedLengthEstimate]; - auto encodedLengthActual = + const auto bin = make_unique_for_overwrite(encodedLengthEstimate); + auto encodedLengthActual = static_cast(itksysBase64_Encode((const unsigned char *)bv->GetPointer(), static_cast(bv->GetLength()), - (unsigned char *)bin, + (unsigned char *)bin.get(), 0)); - std::string encodedValue(bin, encodedLengthActual); + std::string encodedValue(bin.get(), encodedLengthActual); EncapsulateMetaData(dico, tag.PrintAsPipeSeparatedString(), encodedValue); - delete[] bin; } } } @@ -883,16 +881,16 @@ GDCMImageIO::Write(const void * buffer) { // Custom VR::VRBINARY // convert value from Base64 - auto * bin = new uint8_t[value.size()]; - auto decodedLengthActual = + const auto bin = make_unique_for_overwrite(value.size()); + auto decodedLengthActual = static_cast(itksysBase64_Decode((const unsigned char *)value.c_str(), static_cast(0), - (unsigned char *)bin, + (unsigned char *)bin.get(), static_cast(value.size()))); if (/*tag.GetGroup() != 0 ||*/ tag.GetElement() != 0) // ? { gdcm::DataElement de(tag); - de.SetByteValue((char *)bin, decodedLengthActual); + de.SetByteValue((char *)bin.get(), decodedLengthActual); de.SetVR(dictEntry.GetVR()); if (tag.GetGroup() == 0x2) { @@ -903,7 +901,6 @@ GDCMImageIO::Write(const void * buffer) header.Insert(de); } } - delete[] bin; } else // VRASCII { @@ -1297,11 +1294,10 @@ GDCMImageIO::Write(const void * buffer) image.SetIntercept(m_RescaleIntercept); image.SetSlope(m_RescaleSlope); - auto * copyBuffer = new char[len]; + const auto copyBuffer = make_unique_for_overwrite(len); const auto * inputBuffer = static_cast(buffer); - ir.InverseRescale(copyBuffer, inputBuffer, numberOfBytes); - pixeldata.SetByteValue(copyBuffer, static_cast(len)); - delete[] copyBuffer; + ir.InverseRescale(copyBuffer.get(), inputBuffer, numberOfBytes); + pixeldata.SetByteValue(copyBuffer.get(), static_cast(len)); } else { diff --git a/Modules/IO/GIPL/src/itkGiplImageIO.cxx b/Modules/IO/GIPL/src/itkGiplImageIO.cxx index 00659550929..f6ec6220fef 100644 --- a/Modules/IO/GIPL/src/itkGiplImageIO.cxx +++ b/Modules/IO/GIPL/src/itkGiplImageIO.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkGiplImageIO.h" #include "itkByteSwapper.h" +#include "itkMakeUniqueForOverwrite.h" #include #include "itk_zlib.h" @@ -1049,33 +1050,31 @@ GiplImageIO ::Write(const void * buffer) // Swap bytes if necessary if (m_ByteOrder == IOByteOrderEnum::LittleEndian) { - auto * tempBuffer = new char[numberOfBytes]; - memcpy(tempBuffer, buffer, numberOfBytes); - SwapBytesIfNecessary(tempBuffer, numberOfComponents); + const auto tempBuffer = make_unique_for_overwrite(numberOfBytes); + memcpy(tempBuffer.get(), buffer, numberOfBytes); + SwapBytesIfNecessary(tempBuffer.get(), numberOfComponents); if (m_IsCompressed) { - gzwrite(m_Internal->m_GzFile, tempBuffer, numberOfBytes); + gzwrite(m_Internal->m_GzFile, tempBuffer.get(), numberOfBytes); } else { - m_Ofstream.write(tempBuffer, numberOfBytes); + m_Ofstream.write(tempBuffer.get(), numberOfBytes); } - delete[] tempBuffer; } else if (m_ByteOrder == IOByteOrderEnum::BigEndian) { - auto * tempBuffer = new char[numberOfBytes]; - memcpy(tempBuffer, buffer, numberOfBytes); - SwapBytesIfNecessary(tempBuffer, numberOfComponents); + const auto tempBuffer = make_unique_for_overwrite(numberOfBytes); + memcpy(tempBuffer.get(), buffer, numberOfBytes); + SwapBytesIfNecessary(tempBuffer.get(), numberOfComponents); if (m_IsCompressed) { - gzwrite(m_Internal->m_GzFile, tempBuffer, numberOfBytes); + gzwrite(m_Internal->m_GzFile, tempBuffer.get(), numberOfBytes); } else { - m_Ofstream.write(tempBuffer, numberOfBytes); + m_Ofstream.write(tempBuffer.get(), numberOfBytes); } - delete[] tempBuffer; } else { diff --git a/Modules/IO/ImageBase/src/itkNumericSeriesFileNames.cxx b/Modules/IO/ImageBase/src/itkNumericSeriesFileNames.cxx index d737a60250f..1b6e022686e 100644 --- a/Modules/IO/ImageBase/src/itkNumericSeriesFileNames.cxx +++ b/Modules/IO/ImageBase/src/itkNumericSeriesFileNames.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkNumericSeriesFileNames.h" +#include "itkMakeUniqueForOverwrite.h" #include namespace itk @@ -55,19 +56,17 @@ NumericSeriesFileNames::GetFileNames() // absurdly long integer string. } OffsetValueType bufflen = nchars + 1; - auto * temp = new char[bufflen]; - OffsetValueType result = snprintf(temp, bufflen, m_SeriesFormat.c_str(), i); + const auto temp = make_unique_for_overwrite(bufflen); + OffsetValueType result = snprintf(temp.get(), bufflen, m_SeriesFormat.c_str(), i); if (result < 0 || result >= bufflen) { std::stringstream message_cache; message_cache << "The filename is too long for temp buffer." - << " Truncated form: " << temp << "." << std::endl + << " Truncated form: " << temp.get() << "." << std::endl << "nchars: " << nchars << " bufflen: " << bufflen << " result: " << result; - delete[] temp; itkExceptionMacro(<< message_cache.str()); } - std::string fileName(temp); - delete[] temp; + std::string fileName(temp.get()); m_FileNames.push_back(fileName); } return m_FileNames; diff --git a/Modules/IO/ImageBase/src/itkRawImageIOUtilities.cxx b/Modules/IO/ImageBase/src/itkRawImageIOUtilities.cxx index 8d947698c06..dd7e8985cdc 100644 --- a/Modules/IO/ImageBase/src/itkRawImageIOUtilities.cxx +++ b/Modules/IO/ImageBase/src/itkRawImageIOUtilities.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkImageIOBase.h" #include "itkByteSwapper.h" +#include "itkMakeUniqueForOverwrite.h" namespace { @@ -34,19 +35,17 @@ _WriteRawBytesAfterSwappingUtility(const void * buffer, const itk::SizeValueType numberOfPixels = numberOfBytes / (sizeof(TStrongType)); if (byteOrder == itk::IOByteOrderEnum::LittleEndian && InternalByteSwapperType::SystemIsBigEndian()) { - auto * tempBuffer = new TStrongType[numberOfPixels]; - memcpy((char *)tempBuffer, buffer, numberOfBytes); - InternalByteSwapperType::SwapRangeFromSystemToLittleEndian((TStrongType *)tempBuffer, numberOfComponents); - file.write((char *)tempBuffer, numberOfBytes); - delete[] tempBuffer; + const auto tempBuffer = itk::make_unique_for_overwrite(numberOfPixels); + memcpy(tempBuffer.get(), buffer, numberOfBytes); + InternalByteSwapperType::SwapRangeFromSystemToLittleEndian(tempBuffer.get(), numberOfComponents); + file.write(reinterpret_cast(tempBuffer.get()), numberOfBytes); } else if (byteOrder == itk::IOByteOrderEnum::BigEndian && InternalByteSwapperType::SystemIsLittleEndian()) { - auto * tempBuffer = new TStrongType[numberOfPixels]; - memcpy((char *)tempBuffer, buffer, numberOfBytes); - InternalByteSwapperType::SwapRangeFromSystemToBigEndian((TStrongType *)tempBuffer, numberOfComponents); - file.write((char *)tempBuffer, numberOfBytes); - delete[] tempBuffer; + const auto tempBuffer = itk::make_unique_for_overwrite(numberOfPixels); + memcpy(tempBuffer.get(), buffer, numberOfBytes); + InternalByteSwapperType::SwapRangeFromSystemToBigEndian(tempBuffer.get(), numberOfComponents); + file.write(reinterpret_cast(tempBuffer.get()), numberOfBytes); } else { diff --git a/Modules/IO/LSM/src/itkLSMImageIO.cxx b/Modules/IO/LSM/src/itkLSMImageIO.cxx index 32b068ec7ac..c675e3906f7 100644 --- a/Modules/IO/LSM/src/itkLSMImageIO.cxx +++ b/Modules/IO/LSM/src/itkLSMImageIO.cxx @@ -27,6 +27,7 @@ *=========================================================================*/ #include "itkLSMImageIO.h" #include "itkByteSwapper.h" +#include "itkMakeUniqueForOverwrite.h" #include "itk_tiff.h" @@ -301,16 +302,15 @@ LSMImageIO::Write(const void * buffer) { // if number of scalar components is greater than 3, that means we assume // there is alpha. - uint16_t extra_samples = scomponents - 3; - auto * sample_info = new uint16_t[scomponents - 3]; + uint16_t extra_samples = scomponents - 3; + const auto sample_info = make_unique_for_overwrite(scomponents - 3); sample_info[0] = EXTRASAMPLE_ASSOCALPHA; int cc; for (cc = 1; cc < scomponents - 3; ++cc) { sample_info[cc] = EXTRASAMPLE_UNSPECIFIED; } - TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_samples, sample_info); - delete[] sample_info; + TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_samples, sample_info.get()); } uint16_t compression; diff --git a/Modules/IO/MINC/src/itkMINCImageIO.cxx b/Modules/IO/MINC/src/itkMINCImageIO.cxx index e9459a3e791..9b978491348 100644 --- a/Modules/IO/MINC/src/itkMINCImageIO.cxx +++ b/Modules/IO/MINC/src/itkMINCImageIO.cxx @@ -23,6 +23,7 @@ #include "itkMetaDataObject.h" #include "itkArray.h" #include "itkPrintHelper.h" +#include "itkMakeUniqueForOverwrite.h" #include "itk_minc2.h" @@ -691,14 +692,13 @@ MINCImageIO::ReadImageInformation() size_t minc_history_length = 0; if (miget_attr_length(this->m_MINCPImpl->m_Volume, "", "history", &minc_history_length) == MI_NOERROR) { - auto * minc_history = new char[minc_history_length + 1]; + const auto minc_history = make_unique_for_overwrite(minc_history_length + 1); if (miget_attr_values( - this->m_MINCPImpl->m_Volume, MI_TYPE_STRING, "", "history", minc_history_length + 1, minc_history) == + this->m_MINCPImpl->m_Volume, MI_TYPE_STRING, "", "history", minc_history_length + 1, minc_history.get()) == MI_NOERROR) { - EncapsulateMetaData(thisDic, "history", std::string(minc_history)); + EncapsulateMetaData(thisDic, "history", std::string(minc_history.get())); } - delete[] minc_history; } if (this->m_MINCPImpl->m_DimensionIndices[4] != -1) // have time dimension @@ -794,14 +794,13 @@ MINCImageIO::ReadImageInformation() { case MI_TYPE_STRING: { - auto * tmp = new char[att_length + 1]; + const auto tmp = make_unique_for_overwrite(att_length + 1); if (miget_attr_values( - this->m_MINCPImpl->m_Volume, att_data_type, group_name, attribute, att_length + 1, tmp) == + this->m_MINCPImpl->m_Volume, att_data_type, group_name, attribute, att_length + 1, tmp.get()) == MI_NOERROR) { - EncapsulateMetaData(thisDic, entry_key, std::string(tmp)); + EncapsulateMetaData(thisDic, entry_key, std::string(tmp.get())); } - delete[] tmp; } break; case MI_TYPE_FLOAT: diff --git a/Modules/IO/MeshFreeSurfer/src/itkFreeSurferAsciiMeshIO.cxx b/Modules/IO/MeshFreeSurfer/src/itkFreeSurferAsciiMeshIO.cxx index c8dc8c74318..d242a01952e 100644 --- a/Modules/IO/MeshFreeSurfer/src/itkFreeSurferAsciiMeshIO.cxx +++ b/Modules/IO/MeshFreeSurfer/src/itkFreeSurferAsciiMeshIO.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkFreeSurferAsciiMeshIO.h" +#include "itkMakeUniqueForOverwrite.h" #include "itksys/SystemTools.hxx" @@ -166,7 +167,7 @@ FreeSurferAsciiMeshIO ::ReadCells(void * buffer) m_InputFile.precision(12); SizeValueType index = 0; constexpr unsigned int numberOfCellPoints = 3; - auto * data = new unsigned int[this->m_NumberOfCells * numberOfCellPoints]; + const auto data = make_unique_for_overwrite(this->m_NumberOfCells * numberOfCellPoints); float value; for (SizeValueType id = 0; id < this->m_NumberOfCells; ++id) @@ -179,8 +180,7 @@ FreeSurferAsciiMeshIO ::ReadCells(void * buffer) } this->WriteCellsBuffer( - data, static_cast(buffer), CellGeometryEnum::TRIANGLE_CELL, 3, this->m_NumberOfCells); - delete[] data; + data.get(), static_cast(buffer), CellGeometryEnum::TRIANGLE_CELL, 3, this->m_NumberOfCells); CloseFile(); } diff --git a/Modules/IO/MeshFreeSurfer/src/itkFreeSurferBinaryMeshIO.cxx b/Modules/IO/MeshFreeSurfer/src/itkFreeSurferBinaryMeshIO.cxx index 9ac16fa9645..13371d92c50 100644 --- a/Modules/IO/MeshFreeSurfer/src/itkFreeSurferBinaryMeshIO.cxx +++ b/Modules/IO/MeshFreeSurfer/src/itkFreeSurferBinaryMeshIO.cxx @@ -19,6 +19,7 @@ #include "itkFreeSurferBinaryMeshIO.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" namespace itk { @@ -243,14 +244,15 @@ void FreeSurferBinaryMeshIO ::ReadCells(void * buffer) { constexpr unsigned int numberOfCellPoints = 3; - auto * data = new itk::uint32_t[this->m_NumberOfCells * numberOfCellPoints]; + const auto data = make_unique_for_overwrite(this->m_NumberOfCells * numberOfCellPoints); - m_InputFile.read(reinterpret_cast(data), this->m_NumberOfCells * numberOfCellPoints * sizeof(itk::uint32_t)); - itk::ByteSwapper::SwapRangeFromSystemToBigEndian(data, this->m_NumberOfCells * numberOfCellPoints); + m_InputFile.read(reinterpret_cast(data.get()), + this->m_NumberOfCells * numberOfCellPoints * sizeof(itk::uint32_t)); + itk::ByteSwapper::SwapRangeFromSystemToBigEndian(data.get(), + this->m_NumberOfCells * numberOfCellPoints); this->WriteCellsBuffer( - data, static_cast(buffer), CellGeometryEnum::TRIANGLE_CELL, 3, this->m_NumberOfCells); - delete[] data; + data.get(), static_cast(buffer), CellGeometryEnum::TRIANGLE_CELL, 3, this->m_NumberOfCells); CloseFile(); } diff --git a/Modules/IO/MeshOBJ/src/itkOBJMeshIO.cxx b/Modules/IO/MeshOBJ/src/itkOBJMeshIO.cxx index bfee4a7efb3..428cf441f2e 100644 --- a/Modules/IO/MeshOBJ/src/itkOBJMeshIO.cxx +++ b/Modules/IO/MeshOBJ/src/itkOBJMeshIO.cxx @@ -19,6 +19,7 @@ #include "itkOBJMeshIO.h" #include "itkNumericTraits.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" #include #include @@ -251,7 +252,7 @@ OBJMeshIO ::ReadCells(void * buffer) OpenFile(); // Read and analyze the first line in the file - auto * data = new long[this->m_CellBufferSize - this->m_NumberOfCells]; + const auto data = make_unique_for_overwrite(this->m_CellBufferSize - this->m_NumberOfCells); SizeValueType index = 0; std::string line; @@ -294,10 +295,10 @@ OBJMeshIO ::ReadCells(void * buffer) CloseFile(); - this->WriteCellsBuffer(data, static_cast(buffer), CellGeometryEnum::POLYGON_CELL, this->m_NumberOfCells); + this->WriteCellsBuffer( + data.get(), static_cast(buffer), CellGeometryEnum::POLYGON_CELL, this->m_NumberOfCells); // this->WriteCellsBuffer(data, static_cast(buffer), // CellGeometryEnum::TRIANGLE_CELL, 3, this->m_NumberOfCells); - delete[] data; } void diff --git a/Modules/IO/MeshOFF/src/itkOFFMeshIO.cxx b/Modules/IO/MeshOFF/src/itkOFFMeshIO.cxx index 691b5d7a475..75fb85410b1 100644 --- a/Modules/IO/MeshOFF/src/itkOFFMeshIO.cxx +++ b/Modules/IO/MeshOFF/src/itkOFFMeshIO.cxx @@ -19,6 +19,7 @@ #include "itkOFFMeshIO.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" namespace itk { @@ -204,27 +205,27 @@ OFFMeshIO ::ReadMeshInformation() m_PointsStartPosition = m_InputFile.tellg(); // Read points - auto * pointsBuffer = new float[this->m_NumberOfPoints * this->m_PointDimension]; - this->ReadBufferAsBinary(pointsBuffer, m_InputFile, this->m_NumberOfPoints * this->m_PointDimension); - delete[] pointsBuffer; + const auto numberOfCoordinates = this->m_NumberOfPoints * this->m_PointDimension; + this->ReadBufferAsBinary(make_unique_for_overwrite(numberOfCoordinates).get(), + m_InputFile, + this->m_NumberOfPoints * this->m_PointDimension); // Set default cell component type this->m_CellBufferSize = this->m_NumberOfCells * 2; // Read cells itk::uint32_t numberOfCellPoints = 0; - auto * cellsBuffer = new itk::uint32_t[this->m_NumberOfCells]; + const auto cellsBuffer = make_unique_for_overwrite(this->m_NumberOfCells); for (unsigned long id = 0; id < this->m_NumberOfCells; ++id) { this->ReadBufferAsBinary(&numberOfCellPoints, m_InputFile, 1); this->m_CellBufferSize += numberOfCellPoints; - this->ReadBufferAsBinary(cellsBuffer, m_InputFile, numberOfCellPoints); + this->ReadBufferAsBinary(cellsBuffer.get(), m_InputFile, numberOfCellPoints); if (numberOfCellPoints != 3) { m_TriangleCellType = false; } } - delete[] cellsBuffer; } // Set default point component type @@ -283,15 +284,15 @@ OFFMeshIO ::ReadPoints(void * buffer) void OFFMeshIO ::ReadCells(void * buffer) { - auto * data = new itk::uint32_t[this->m_CellBufferSize - this->m_NumberOfCells]; + const auto data = make_unique_for_overwrite(this->m_CellBufferSize - this->m_NumberOfCells); if (this->m_FileType == IOFileEnum::ASCII) { - this->ReadCellsBufferAsAscii(data, m_InputFile); + this->ReadCellsBufferAsAscii(data.get(), m_InputFile); } else if (this->m_FileType == IOFileEnum::BINARY) { - this->ReadBufferAsBinary(data, m_InputFile, this->m_CellBufferSize - this->m_NumberOfCells); + this->ReadBufferAsBinary(data.get(), m_InputFile, this->m_CellBufferSize - this->m_NumberOfCells); } else { @@ -303,15 +304,13 @@ OFFMeshIO ::ReadCells(void * buffer) if (m_TriangleCellType) { this->WriteCellsBuffer( - data, static_cast(buffer), CellGeometryEnum::TRIANGLE_CELL, this->m_NumberOfCells); + data.get(), static_cast(buffer), CellGeometryEnum::TRIANGLE_CELL, this->m_NumberOfCells); } else { this->WriteCellsBuffer( - data, static_cast(buffer), CellGeometryEnum::POLYGON_CELL, this->m_NumberOfCells); + data.get(), static_cast(buffer), CellGeometryEnum::POLYGON_CELL, this->m_NumberOfCells); } - - delete[] data; } void diff --git a/Modules/IO/MeshVTK/src/itkVTKPolyDataMeshIO.cxx b/Modules/IO/MeshVTK/src/itkVTKPolyDataMeshIO.cxx index d02ec0486f5..4c365ca65f4 100644 --- a/Modules/IO/MeshVTK/src/itkVTKPolyDataMeshIO.cxx +++ b/Modules/IO/MeshVTK/src/itkVTKPolyDataMeshIO.cxx @@ -19,6 +19,7 @@ #include "itkVTKPolyDataMeshIO.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" #include @@ -985,10 +986,10 @@ VTKPolyDataMeshIO ::ReadCellsBufferAsBINARY(std::ifstream & inputFile, void * bu return; } - auto * inputBuffer = new unsigned int[this->m_CellBufferSize - this->m_NumberOfCells]; - void * pv = inputBuffer; - auto * startBuffer = static_cast(pv); - auto * outputBuffer = static_cast(buffer); + const auto inputBuffer = make_unique_for_overwrite(this->m_CellBufferSize - this->m_NumberOfCells); + void * pv = inputBuffer.get(); + auto * startBuffer = static_cast(pv); + auto * outputBuffer = static_cast(buffer); std::string line; MetaDataDictionary & metaDic = this->GetMetaDataDictionary(); @@ -1052,11 +1053,6 @@ VTKPolyDataMeshIO ::ReadCellsBufferAsBINARY(std::ifstream & inputFile, void * bu outputBuffer += (numberOfPolygonIndices + numberOfPolygons) * sizeof(unsigned int); } } - - if (this->m_CellBufferSize) - { - delete[] inputBuffer; - } } void diff --git a/Modules/IO/Meta/src/itkMetaImageIO.cxx b/Modules/IO/Meta/src/itkMetaImageIO.cxx index 5702475c262..7576827f620 100644 --- a/Modules/IO/Meta/src/itkMetaImageIO.cxx +++ b/Modules/IO/Meta/src/itkMetaImageIO.cxx @@ -22,6 +22,7 @@ #include "itksys/SystemTools.hxx" #include "itkMath.h" #include "itkSingleton.h" +#include "itkMakeUniqueForOverwrite.h" namespace itk { @@ -450,8 +451,8 @@ MetaImageIO::Read(void * buffer) if (largestRegion != m_IORegion) { - auto * indexMin = new int[nDims]; - auto * indexMax = new int[nDims]; + const auto indexMin = make_unique_for_overwrite(nDims); + const auto indexMax = make_unique_for_overwrite(nDims); for (unsigned int i = 0; i < nDims; ++i) { if (i < m_IORegion.GetImageDimension()) @@ -467,17 +468,12 @@ MetaImageIO::Read(void * buffer) } } - if (!m_MetaImage.ReadROI(indexMin, indexMax, m_FileName.c_str(), true, buffer, m_SubSamplingFactor)) + if (!m_MetaImage.ReadROI(indexMin.get(), indexMax.get(), m_FileName.c_str(), true, buffer, m_SubSamplingFactor)) { - delete[] indexMin; - delete[] indexMax; itkExceptionMacro("File cannot be read: " << this->GetFileName() << " for reading." << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } - delete[] indexMin; - delete[] indexMax; - m_MetaImage.ElementByteOrderFix(m_IORegion.GetNumberOfPixels()); } else @@ -785,9 +781,9 @@ MetaImageIO ::Write(const void * buffer) break; } - auto * dSize = new int[numberOfDimensions]; - auto * eSpacing = new double[numberOfDimensions]; - auto * eOrigin = new double[numberOfDimensions]; + const auto dSize = make_unique_for_overwrite(numberOfDimensions); + const auto eSpacing = make_unique_for_overwrite(numberOfDimensions); + const auto eOrigin = make_unique_for_overwrite(numberOfDimensions); for (unsigned int ii = 0; ii < numberOfDimensions; ++ii) { dSize[ii] = this->GetDimensions(ii); @@ -795,8 +791,9 @@ MetaImageIO ::Write(const void * buffer) eOrigin[ii] = this->GetOrigin(ii); } - m_MetaImage.InitializeEssential(numberOfDimensions, dSize, eSpacing, eType, nChannels, const_cast(buffer)); - m_MetaImage.Position(eOrigin); + m_MetaImage.InitializeEssential( + numberOfDimensions, dSize.get(), eSpacing.get(), eType, nChannels, const_cast(buffer)); + m_MetaImage.Position(eOrigin.get()); m_MetaImage.BinaryData(binaryData); // Write the image Information @@ -1082,8 +1079,8 @@ MetaImageIO ::Write(const void * buffer) } else if (largestRegion != m_IORegion) { - auto * indexMin = new int[numberOfDimensions]; - auto * indexMax = new int[numberOfDimensions]; + const auto indexMin = make_unique_for_overwrite(numberOfDimensions); + const auto indexMax = make_unique_for_overwrite(numberOfDimensions); for (unsigned int ii = 0; ii < numberOfDimensions; ++ii) { // the dimensions of m_IORegion should match out requested @@ -1093,35 +1090,20 @@ MetaImageIO ::Write(const void * buffer) indexMax[ii] = m_IORegion.GetIndex()[ii] + m_IORegion.GetSize()[ii] - 1; } - if (!m_MetaImage.WriteROI(indexMin, indexMax, m_FileName.c_str())) + if (!m_MetaImage.WriteROI(indexMin.get(), indexMax.get(), m_FileName.c_str())) { - delete[] dSize; - delete[] eSpacing; - delete[] eOrigin; - delete[] indexMin; - delete[] indexMax; itkExceptionMacro("File ROI cannot be written: " << this->GetFileName() << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } - - delete[] indexMin; - delete[] indexMax; } else { if (!m_MetaImage.Write(m_FileName.c_str())) { - delete[] dSize; - delete[] eSpacing; - delete[] eOrigin; itkExceptionMacro("File cannot be written: " << this->GetFileName() << std::endl << "Reason: " << itksys::SystemTools::GetLastSystemError()); } } - - delete[] dSize; - delete[] eSpacing; - delete[] eOrigin; } /** Given a requested region, determine what could be the region that we can diff --git a/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx b/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx index b442b951c57..3a05d70b159 100644 --- a/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx +++ b/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx @@ -21,6 +21,7 @@ #include "itkSpatialOrientationAdapter.h" #include #include "itkNiftiImageIOConfigurePrivate.h" +#include "itkMakeUniqueForOverwrite.h" namespace itk { @@ -2246,7 +2247,7 @@ NiftiImageIO ::Write(const void * buffer) const size_t buffer_size = numVoxels * numComponents // Number of components * this->m_NiftiImage->nbyper; - auto * nifti_buf = new char[buffer_size]; + const auto nifti_buf = make_unique_for_overwrite(buffer_size); const auto * const itkbuf = (const char *)buffer; // Data must be rearranged to meet nifti organzation. // nifti_layout[vec][t][z][y][x] = itk_layout[t][z][y][z][vec] @@ -2307,10 +2308,9 @@ NiftiImageIO ::Write(const void * buffer) dumpdata(buffer); // Need a const cast here so that we don't have to copy the memory for // writing. - this->m_NiftiImage->data = static_cast(nifti_buf); + this->m_NiftiImage->data = static_cast(nifti_buf.get()); const int nifti_write_status = nifti_image_write_status(this->m_NiftiImage); this->m_NiftiImage->data = nullptr; // if left pointing to data buffer - delete[] nifti_buf; if (nifti_write_status) { itkExceptionMacro(<< "ERROR: nifti library failed to write image" << this->GetFileName()); diff --git a/Modules/IO/Stimulate/src/itkStimulateImageIO.cxx b/Modules/IO/Stimulate/src/itkStimulateImageIO.cxx index dc693e06f35..bce5ea53986 100644 --- a/Modules/IO/Stimulate/src/itkStimulateImageIO.cxx +++ b/Modules/IO/Stimulate/src/itkStimulateImageIO.cxx @@ -29,6 +29,7 @@ #include "itksys/SystemTools.hxx" #include "itksys/RegularExpression.hxx" #include "itkByteSwapper.h" +#include "itkMakeUniqueForOverwrite.h" namespace itk { @@ -537,29 +538,33 @@ StimulateImageIO::Write(const void * buffer) file << "\ndataType: "; { - auto * tempmemory = new char[numberOfBytes]; - memcpy(tempmemory, buffer, numberOfBytes); + const auto tempmemory = make_unique_for_overwrite(numberOfBytes); + memcpy(tempmemory.get(), buffer, numberOfBytes); switch (this->GetComponentType()) { case IOComponentEnum::CHAR: file << "BYTE"; - ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory), numberOfComponents); + ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory.get()), + numberOfComponents); break; case IOComponentEnum::SHORT: file << "WORD"; - ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory), numberOfComponents); + ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory.get()), + numberOfComponents); break; case IOComponentEnum::INT: file << "LWORD"; - ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory), numberOfComponents); + ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory.get()), numberOfComponents); break; case IOComponentEnum::FLOAT: file << "REAL"; - ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory), numberOfComponents); + ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory.get()), + numberOfComponents); break; case IOComponentEnum::DOUBLE: file << "COMPLEX"; - ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory), numberOfComponents); + ByteSwapper::SwapRangeFromSystemToBigEndian(reinterpret_cast(tempmemory.get()), + numberOfComponents); break; default: break; @@ -579,8 +584,7 @@ StimulateImageIO::Write(const void * buffer) this->OpenFileForWriting(file_data, m_DataFileName); // Write the actual pixel data - file_data.write(static_cast(tempmemory), numberOfBytes); - delete[] tempmemory; + file_data.write(static_cast(tempmemory.get()), numberOfBytes); file_data.close(); } file.close(); diff --git a/Modules/IO/TIFF/src/itkTIFFImageIO.cxx b/Modules/IO/TIFF/src/itkTIFFImageIO.cxx index 29a5d2cca90..6d222bf4676 100644 --- a/Modules/IO/TIFF/src/itkTIFFImageIO.cxx +++ b/Modules/IO/TIFF/src/itkTIFFImageIO.cxx @@ -20,6 +20,7 @@ #include "itkTIFFReaderInternal.h" #include "itksys/SystemTools.hxx" #include "itkMetaDataObject.h" +#include "itkMakeUniqueForOverwrite.h" #include "itk_tiff.h" @@ -674,15 +675,14 @@ TIFFImageIO::InternalWrite(const void * buffer) { // if number of scalar components is greater than 3, that means we assume // there is alpha. - uint16_t extra_samples = scomponents - 3; - auto * sample_info = new uint16_t[scomponents - 3]; + uint16_t extra_samples = scomponents - 3; + const auto sample_info = make_unique_for_overwrite(scomponents - 3); sample_info[0] = EXTRASAMPLE_ASSOCALPHA; for (uint16_t cc = 1; cc < scomponents - 3; ++cc) { sample_info[cc] = EXTRASAMPLE_UNSPECIFIED; } - TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_samples, sample_info); - delete[] sample_info; + TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, extra_samples, sample_info.get()); } uint16_t compression; diff --git a/Modules/IO/VTK/src/itkVTKImageIO.cxx b/Modules/IO/VTK/src/itkVTKImageIO.cxx index 1fab3337f5e..eb47e52091d 100644 --- a/Modules/IO/VTK/src/itkVTKImageIO.cxx +++ b/Modules/IO/VTK/src/itkVTKImageIO.cxx @@ -19,6 +19,7 @@ #include "itkByteSwapper.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" namespace itk @@ -816,43 +817,41 @@ VTKImageIO::WriteBufferAsASCII(std::ostream & os, } } -#define WriteVTKImageBinaryBlockMACRO(storageType) \ - { \ - const ImageIOBase::BufferSizeType numbytes = \ - static_cast(this->GetImageSizeInBytes()); \ - const ImageIOBase::BufferSizeType numberImageComponents = \ - static_cast(this->GetImageSizeInComponents()); \ - const bool isSymmetricSecondRankTensor = (this->GetPixelType() == IOPixelEnum::SYMMETRICSECONDRANKTENSOR); \ - storageType * tempmemory = new storageType[numberImageComponents]; \ - memcpy(tempmemory, buffer, numbytes); \ - ByteSwapper::SwapRangeFromSystemToBigEndian(tempmemory, numberImageComponents); \ - /* write the image */ \ - if (isSymmetricSecondRankTensor) \ - { \ - this->WriteSymmetricTensorBufferAsBinary(file, tempmemory, numbytes); \ - } \ - else \ - { \ - if (!this->WriteBufferAsBinary(file, tempmemory, numbytes)) \ - { \ - itkExceptionMacro(<< "Could not write file: " << m_FileName); \ - } \ - } \ - delete[] tempmemory; \ +#define WriteVTKImageBinaryBlockMACRO(storageType) \ + { \ + const ImageIOBase::BufferSizeType numbytes = \ + static_cast(this->GetImageSizeInBytes()); \ + const ImageIOBase::BufferSizeType numberImageComponents = \ + static_cast(this->GetImageSizeInComponents()); \ + const bool isSymmetricSecondRankTensor = (this->GetPixelType() == IOPixelEnum::SYMMETRICSECONDRANKTENSOR); \ + const auto tempmemory = make_unique_for_overwrite(numberImageComponents); \ + memcpy(tempmemory.get(), buffer, numbytes); \ + ByteSwapper::SwapRangeFromSystemToBigEndian(tempmemory.get(), numberImageComponents); \ + /* write the image */ \ + if (isSymmetricSecondRankTensor) \ + { \ + this->WriteSymmetricTensorBufferAsBinary(file, tempmemory.get(), numbytes); \ + } \ + else \ + { \ + if (!this->WriteBufferAsBinary(file, tempmemory.get(), numbytes)) \ + { \ + itkExceptionMacro(<< "Could not write file: " << m_FileName); \ + } \ + } \ } -#define StreamWriteVTKImageBinaryBlockMACRO(storageType) \ - { \ - const ImageIOBase::BufferSizeType numbytes = \ - static_cast(this->GetIORegionSizeInBytes()); \ - const ImageIOBase::BufferSizeType numberImageComponents = \ - static_cast(this->GetIORegionSizeInComponents()); \ - storageType * tempmemory = new storageType[numberImageComponents]; \ - memcpy(tempmemory, buffer, numbytes); \ - ByteSwapper::SwapRangeFromSystemToBigEndian(tempmemory, numberImageComponents); \ - /* write the image */ \ - this->StreamWriteBufferAsBinary(file, tempmemory); \ - delete[] tempmemory; \ +#define StreamWriteVTKImageBinaryBlockMACRO(storageType) \ + { \ + const ImageIOBase::BufferSizeType numbytes = \ + static_cast(this->GetIORegionSizeInBytes()); \ + const ImageIOBase::BufferSizeType numberImageComponents = \ + static_cast(this->GetIORegionSizeInComponents()); \ + const auto tempmemory = make_unique_for_overwrite(numberImageComponents); \ + memcpy(tempmemory.get(), buffer, numbytes); \ + ByteSwapper::SwapRangeFromSystemToBigEndian(tempmemory.get(), numberImageComponents); \ + /* write the image */ \ + this->StreamWriteBufferAsBinary(file, tempmemory.get()); \ } void diff --git a/Modules/IO/XML/src/itkXMLFile.cxx b/Modules/IO/XML/src/itkXMLFile.cxx index 0f215b06c3c..23f94640ea8 100644 --- a/Modules/IO/XML/src/itkXMLFile.cxx +++ b/Modules/IO/XML/src/itkXMLFile.cxx @@ -17,6 +17,7 @@ *=========================================================================*/ #include "itkXMLFile.h" #include "itksys/SystemTools.hxx" +#include "itkMakeUniqueForOverwrite.h" #include #include "expat.h" @@ -86,9 +87,9 @@ XMLReaderBase::parse() // Default stream parser just reads a block at a time. std::streamsize filesize = itksys::SystemTools::FileLength(m_Filename.c_str()); - auto * buffer = new char[filesize]; + const auto buffer = make_unique_for_overwrite(filesize); - inputstream.read(buffer, filesize); + inputstream.read(buffer.get(), filesize); if (static_cast(inputstream.gcount()) != filesize) { @@ -96,8 +97,7 @@ XMLReaderBase::parse() exception.SetDescription("File Read Error"); throw exception; } - const auto result = XML_Parse(Parser, buffer, inputstream.gcount(), false); - delete[] buffer; + const auto result = XML_Parse(Parser, buffer.get(), inputstream.gcount(), false); if (!result) { ExceptionObject exception(__FILE__, __LINE__);