简体   繁体   中英

C++ need clarification about destructors and scope

I have a problem, and I'm pretty sure I know the cause of it. I'd just like some clarification. I have a class that contains other classes, but I'll limit my example to two classes for simplicity.

Class A contains class B. In class A's constructor, it initializes class B by calling B's constructor. At the end of class A's constructor, class B's destructor gets called, which wasn't the behavior I was expecting. Here's an example...

ah

#include "b.h"

class a {
    public:
        b classB;

        a(int someParam);
};

a.cpp

#include "a.h"

//Class A's constructor
a::a(int someParam) {
    //Set class B by calling it's constructor
    classB = b(someParam);
    //Now class B's destructor gets called when exiting A's constructor...
}

I know that if you declare a variable without using "new", it gets destroyed when it leaves the current scope. But I always thought that applied to the variable's scope, and not to the scope at which you assign a value to it. That is the problem, right? If it is, there's nothing wrong with doing classB = *new b(someParam); is there? Or should I just use pointers instead?

In this line:

classB = b(someParam);

The expression b(someParam) creates a temporary, nameless b object, which is then asssigned to the member object, classB . It is the destructor of this nameless temporary which is called, not the destructor of your member object. If you want avoid the creation of this temporary, and instead directly initialize your member object with the appropriate constructor, use the initialization list:

a::a(int someParam)
    :classB(someParam)
{}

And this:

classB = *new b(someParam);

Is an instant memory leak. You're allocating an object on the free store, copy assigning from it to classB , and losing the pointer.

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