简体   繁体   中英

Would this simple code cause a memory leak?

Say you have the following C++ code snippet:

class base {};
class derived : public base {
public:
    std::string str;
};

int main() {
    base *b = new derived();
    delete b;
}

This would leak, right? derived 's string's destructor is never being called because base 's destructor isn't marked as virtual. Or am I misunderstanding something?

You are delete -ing a derived through a pointer of type base* , and base does not have a virtual destructor.

That is Undefined Behavior (UB) , which means anything may happen.

While causing a memory-leak if the std::string has allocated any memory (think short-string-optimization, which would mean no extra memory needs to be allocated for an empty string), is one possible (and a quite likely) manifestation of UB, that's not the worst that could happen.

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