new
should disappear altogether (well, at least when the absence of std::make_unique
in C ++ 14). All dynamic memory allocations must be encapsulated in either the standard library, or containers of type std::vector
, or smart pointers.std::unique_ptr
, which has its own deletion tool, which releases the memory to the DLL.USE_PROBLEMATIC_FACTORY_AND_CAUSE_HEAP_CORRUPTION
, you can see that the debugger detects heap corruption. // main.cpp #include <ProblematicFactory.h> #include <SafeFactory.h> // undef define, assert' #undef USE_PROBLEMATIC_FACTORY_AND_CAUSE_HEAP_CORRUPTION int main() { #ifdef USE_PROBLEMATIC_FACTORY_AND_CAUSE_HEAP_CORRUPTION { // DLL auto wMyObject = ProblematicFactory::getInstance().create(); // delete wMyObject; // DLL CLR DLL, // , - } #endif { auto wMyObject = SafeFactory::getInstance().create(); // , wMyObject // , , // MyClass.h (. ), // } { std::shared_ptr< MyClass > wMyObject = SafeFactory::getInstance().create(); } return 0; }
// ProblematicFactory.h #pragma once #include "DllSwitch.h" #include "MyClass.h" class LIBRARYFACTORY_API ProblematicFactory { public: static ProblematicFactory & getInstance() { static ProblematicFactory wProblematicFactory; return wProblematicFactory; } MyClass * create() const { return new MyClass; } private: ProblematicFactory() {}; };
std::unique_ptr
, and not std::shared_ptr
. // SaveFactory.h #pragma once #include "DllSwitch.h" #include "MyClass.h" #include <memory> class LIBRARYFACTORY_API SafeFactory { public: static SafeFactory & getInstance(); // std::unique_ptr , // .. DLL. // , std::unique_ptr . // , // , MyClass std::default_delete inline std::unique_ptr< MyClass > create() const { return std::unique_ptr< MyClass >(doCreate()); } private: SafeFactory(); MyClass * doCreate() const; };
// MyClass.h #pragma once #include "DllSwitch.h" #include <memory> class LIBRARYFACTORY_API MyClass { }; namespace std { template<> class LIBRARYFACTORY_API default_delete< MyClass > { public: void operator()(MyClass *iToDelete) { delete iToDelete; } }; }
DllSwitch.h
, which defines LIBRARYFACTORY_API
, its contents: // DllSwitch.h #pragma once #ifdef LIBRARYFACTORY_EXPORTS #define LIBRARYFACTORY_API __declspec(dllexport) #else #define LIBRARYFACTORY_API __declspec(dllimport) #endif
Source: https://habr.com/ru/post/182970/
All Articles