C++ Destructors with Vectors, Pointers,

后端 未结 7 2032
清酒与你
清酒与你 2020-12-15 02:57

As far as I know, I should destroy in destructors everything I created with new and close opened filestreams and other streams. However, I have some doubts abou

7条回答
  •  心在旅途
    2020-12-15 03:31

    It depends. std::vector and std::string and MyClass all have 1 thing in common - if you declare a variable to be any of those types, then it will be allocated on stack, be local to the current block you're in, and be destructed when that block ends.

    E.g.

    {
        std::vector a;
        std::string b;
        MyClass c;
    } //at this point, first c will be destroyed, then b, then all strings in a, then a.
    

    If you get to pointers, you guessed correctly: Only the memory the pointer itself occupies (usually a 4 byte integer) will be automatically freed upon leaving scope. Nothing happens to the memory pointed to unless you explicitly delete it (whether it's in a vector or not). If you have a class that contains pointers to other objects you may have to delete them in the destructor (depending on whether or not that class owns those objects). Note that in C++11 there are pointer classes (called smart pointers) that let you treat pointers in a similar fashion to 'normal' objects:

    Ex:

    {
        std::unique_ptr a = make_unique("Hello World");
        function_that_wants_string_ptr(a.get());
    } //here a will call delete on it's internal string ptr and then be destroyed
    

提交回复
热议问题