问题
Basically, I have a block of memory allocated using malloc that I want to start placing objects into using placement new. I know that the destructors for these objects will have to be explicitly called when I'm deleting them, but I want to make sure that I understand this completely, and that I'm going about it the right way. I'm almost certainly going to scrap this approach and go about things in a more straightforward manner, but I figured that I'd ask just for understanding's sake.
I have a class WordIndex that contains the following private member variables:
struct Word
{
std::string word;
std::vector<unsigned int> index;
};
Word* m_words;
std::string* m_lines;
Memory is allocated/reallocated for both pointers using malloc/realloc, and objects are being created using the following code (they're not overwriting any preexisting objects):
new (&m_words[pos]) Word();
new (&m_lines[m_numoflines]) std::string();
I have a destructor as follows, but I'm almost 100% sure that it's not doing things correctly, despite not showing any errors when running.
WordIndex::~WordIndex()
{
unsigned int i;
for( i = 0; i < m_numofwords; i++)
{
m_words[i].~Word();
}
free(m_words);
free(m_lines);
}
My questions are as follows:
- Considering the Word struct has a vector, is it enough to simply call ~Word, or do I need to call the destructor for the vector separately beforehand?
- Do I need to call a destructor for a string (both for m_lines and for Word.word), and if so, how do I do that? It doesn't appear to have a function like ~string that I can call.
- Have I missed anything else? I'm fairly certain that I have.
Thanks in advance!
回答1:
- Considering the Word struct has a vector, is it enough to simply call ~Word, or do I need to call the destructor for the vector separately beforehand?
You can write a destructor for your struct
if you want, but in this case it's not necessary.
- Do I need to call a destructor for a string (both for m_lines and for Word.word), and if so, how do I do that? It doesn't appear to have a function like ~string that I can call.
Yes, you do. The destructor should be there, it's typedef
ed from basic_string
, so you should be calling ~basic_string()
on it.
- Have I missed anything else? I'm fairly certain that I have.
The destructor for string
.
Also, make sure you calculate the space for malloc
correctly, you don't show that code, but verify its what its supposed to be.
回答2:
The only thing you're missing is the call to all the string
s' destructors. It's called ~basic_string
(string
is actually just a typedef
for basic_string
with some template parameters).
No, you don't need to call the vector
s' destructors, because they're called by the compiler-provided destructor for your Word
struct.
来源:https://stackoverflow.com/questions/7960556/using-placement-new-malloc-and-free