Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been researching, and nothing relevant has come up, so I came here.

I am trying to avoid memory leaks, so I am wondering:

Say I have class MyClass with member ints a and b, and an int array c, which are filled in a member function:

class MyClass
{
    public:
        int a, b;
        int c[2];
        void setVariables() 
        {
            a, b = 0;
            for (int i = 0; i < 2; i++) 
            {
                c[i] = 3;
            }
        }
};
int main(int argc, char* argv[])
{
    MyClass* mc = new MyClass();
    mc->setVariables();
    delete mc;
} 

Now, after I call delete mc, will a, b, and all the contents of c be deleted as well? Or will I have to do that explicitly in the destructor of MyClass?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

The rule is very simple: every object created with new must be destroyed exactly once with delete; every array created with new[] must be destroyed exactly once with delete[]; everything else must not be deleted. So your code is correct; you are deleting mc after creating it with new, and not deleting the members which were not created with new.

Applying the rule can be quite tricky when the program flow gets complicated (especially when exceptions are involved); for that reason, it is much better not to delete objects yourself, but to immediately use the result of new to initialise a smart pointer to manage the object for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...