I have the problem with using the polymorphism. The code here:
class A {
public:
A() {cout << "construct a" << endl;}
virtual ~A() {cout << "destroy a" << endl;}
};
class B : public A{
public:
B() {cout << "construct b" << endl;}
~B() {cout << "destroy b" << endl;}
};
void main() {
A *p = new B;
}
The result is:
construct a
construct b
Why 'p' can not be destroyed or may i be wrong somewhere. Thanks.
You need to invoke
delete p;
to delete the pointer and call the destructor. Dynamically allocated objects do not have their destructor called automatically, that's why you need to invoke the delete
operator, which first invokes the destructor then calls operator delete
to release the memory.
Because you are allocating data with the new
operator. If you want to have the destructors invoked make sure to delete the pointer with
delete p;
You can also declare p
as std::unqiue_ptr<A> p(new B);
- the unique pointer will delete the pointer at the end of scope.
By using ordinary pointers, you've said you want to manage the lifetime of your object yourself. Since you never said to destroy the object ( delete p;
will do that, so long as p
is pointing to the object), it never got destroyed.
Normally, you should let the lifetime of your objects be managed automatically. The two basic tools are:
std::unique_ptr<A> p { new B };
With unique_ptr
, only one pointer is allowed to "own" the object. When this pointer is gone, the object it points to will automatically be destroyed. The other tool is
std::shared_ptr<A> p { new B };
// or p = make_shared<B>();
Multiple shared pointers can "share" ownership of the object. When all of the shared pointers are gone, the object will be automatically destroyed.
A call to new allocates memory on the heap. You need to explicitly dealocate this memory using the delete
operator. Doing otherwise causes dreaded memory leaks. Since this is a common source of errors, you may be interested in using std::unique_ptr
or boost::scoped_ptr
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.