简体   繁体   中英

C++ std::queue pop() and destructor

I originally thought when a queue is destructed (eg when it goes out of scope), then the contained elements should be destructed (by calling their respective destructor). Similarly, when pop() is called, the first element in the queue is destructed and the queue's size is reduced by 1.

However, when I verified my understanding, it seems incorrect... I used something like this

string& str = myQueue.front();
myQueue.pop();

(where myQueue is a non-empty queue containing strings).

According to front() spec, it should return a reference to the first element it holds, as seen here .

This means, when I pop the queue, the first element is gone. It turns out "str" is still a valid string afterwards!

Is there something wrong?

Thanks!

The only thing wrong is that you're relying on undefined behavior. It could work, or it could crash, or it could produce the next Facebook. Anything is possible with undefined behavior, and you got one of the possibilities.

You are correct that the destructor runs, but it's not required to zero out the string. It presumably calls operator delete to return the memory occupied by the string for reuse. But the pointer to that memory, and the characters in it, may be left untouched.

C++ is designed primarily for performance. If the library doesn't have to do something at runtime, it probably won't. You might have a debugging mode that you can activate which may cause this program to have a runtime problem, but it will also slow execution and maybe consume extra memory.

One good tool for catching this kind of error is Valgrind. It runs your program in a transparent virtual machine and keeps track of malloc and free calls, and tells you if invalid or uninitialized memory is accessed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM