Fatima Dhaybi Fatima Dhaybi - 28 days ago 20
C++ Question

How to initialize wchar_t pointer correctly in constructor and delete it in destructor

I'm trying to initialize a

wchar_t*
in my class.

This is my constructor:

Book::Book()
{
book = 0;
auth = 0;
setBook(TEXT(""));
setAuth(TEXT(""));
}


And this is my destructor:

Book::~Book()
{
if (book)
delete book;
if (auth)
delete auth;
}


and here is
setBook()
:

void Book::setBook(TCHAR *a) {
if (book)
delete book;
book = new TCHAR[lstrlen(a) + 1];
lstrcpy(book, a);
}


The problem is that when i'm trying to create new object and push it to vector, I get a run time error "The program has triggered a breakpoint" when delete book in destructor.

Here is my vector:

for (int i = 0; !feof(f); i++) {
reqBook.push_back(Book());
reqBook[i].read(f);
}


Please any idea about my problem, or how to initialize correctly?.

Answer

If you manage resources, you must have a copy constructor and a copy assignment operator (or delete them). This is The Rule of 3. With C++11, it's a good idea to have a move constructor and a move assignment operator too (the rule of 5).

If you try to make Book the class that manages resources, you will find there are some complexities involved with exception safety when you are part-way through copying or constructing book or auth.

The solution is to write a RAII class which encapsulates handling an array of wchar_t, and make both book and auth be objects of that class. When you have done that, you will find that you have made a poor-man's copy of std::wstring.

The only reason not to use std::wstring for this, is if it is a class assignment where you have been specifically forbidden from using it.

The specific reason for your crash, is that std::vector copies your original Book object. When it does so, it uses the compiler generated copy constructor (because you haven't provided one). This just copies the pointers. The destructor of the original object deletes the memory these pointers are pointing at, and now you are in the world of pain known as "undefined behaviour". When the object in the vector is deleted, it too will try to delete the same memory, and anything can happen - hitting a breakpoint is a particularly painless result.

Comments