Memory allocated in one dynamic library and then deleted in another library can often trigger problems as the Memory allocation and deallocation across dll boundaries shows. My question is related to objects of auto_ptr type. This type of object provided by a dll is very tricky as the program that uses the dll will delete the object automatically. However, it often happens that some memory reallocation operations may happen to the auto_ptr type object in the dll library. Therefore writing a function that destroys the auto_ptr type object is necessary. First, I give the following example, which illustrates the importance of destroying auto_ptr type objects in a dll library.
The header file for the .dll library is as follows:
dll.h
class __declspec(dllexport) Image
{
public:
Image()
{
mem = NULL;
}
~Image()
{
std::cout<<"Image is being deleted!"<<std::endl;
delete []mem;
mem = NULL;
}
int *mem;
};
typedef std::auto_ptr<Image> ImagePtr;
class __declspec(dllexport) ImageReader
{
public:
void memory_reset(Image &img)
{
img.mem = new int [20*30];
}
};
The executable program that invokes the dll library is as follows:
#include "dll.h"
#include <iostream>
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
int main()
{
ImagePtr my_img(new Image());
ImageReader bmp_reader;
bmp_reader.memory_reset(*my_img);
return 0;
}
If the run time library invoked is statically linked (Multi-threaded Debug (/MTd)
), an error will occur when runing the executable program:
In order to solve this problem, the auto_ptr object must be deleted by the library. Then the question arises: what is the best way of deleting this type of object? The way I can think of is to provide a Global function that can delete the auto_ptr object:
void Fun_destroy_memory(Image &img)
{
img.~Image();
}
So the executable program will become:
int main()
{
ImagePtr my_img(new Image());
ImageReader bmp_reader;
bmp_reader.memory_reset(*my_img);
Fun_destroy_memory(*my_img);
return 0;
}
I do not know whether there are other solutions in this situation. Additionally, I would like to know wheter it is a good practice of invoking class destructor directly as I did in Fun_destroy_memory
. Many thanks!