how to call con/destructor without all/deallocator?
Posted: Tue Oct 11, 2011 1:16 am
Hi C++ experts,
I know this is a very bad programming practice, but I still have to do it. I need to have a vector of MyClass (NOT its pointers for some reason) which behaves like std::string (in fact, much more complicated).
If I have thousands of objects like std::string which is stored inside a resizable array, every time when the array resizes, not only the string objects gets copied over, every element in the old array will get destroyed and deallocated, and every element in the new array will be allocated and constructed, apart from copying over. This is too slow. So I want to do the following way, the array is always allocated and reallocated as a char buffer, everytime when an element is deleted, its destructor will be called and its internal buffers are freed, however, the object's storage space in the array (as a char buffer) is not freed, same for construction and assignment.
In that case, deleting an element from the array will need to invoke the object's destructor ~MyClass() to free its resources BUT WITHOUT freeing itself's storage space sizeof(MyClass) which is allocated as part of a char buffer. Anyway to do that?
Wang Xuancong
I know this is a very bad programming practice, but I still have to do it. I need to have a vector of MyClass (NOT its pointers for some reason) which behaves like std::string (in fact, much more complicated).
If I have thousands of objects like std::string which is stored inside a resizable array, every time when the array resizes, not only the string objects gets copied over, every element in the old array will get destroyed and deallocated, and every element in the new array will be allocated and constructed, apart from copying over. This is too slow. So I want to do the following way, the array is always allocated and reallocated as a char buffer, everytime when an element is deleted, its destructor will be called and its internal buffers are freed, however, the object's storage space in the array (as a char buffer) is not freed, same for construction and assignment.
In that case, deleting an element from the array will need to invoke the object's destructor ~MyClass() to free its resources BUT WITHOUT freeing itself's storage space sizeof(MyClass) which is allocated as part of a char buffer. Anyway to do that?
Wang Xuancong