How to manually destroy member variables?

▼魔方 西西 提交于 2019-12-23 15:29:17

问题


I have a basic question on destructors.

Suppose I have the following class

class A
{
public:

int z;
int* ptr;

A(){z=5 ; ptr = new int[3]; } ;
~A() {delete[] ptr;};

}

Now destructors are supposed to destroy an instantiation of an object. The destructor above does exactly that, in freeing the dynamically alloctaed memory allocated by new.

But what about the variable z? How should I manually destroy it / free the memory allocated by z? Does it get destroyed automatically when the class goes out of scope?


回答1:


It gets "destroyed" automatically, although since in your example int z is a POD-type, there is no explicit destructor ... the memory is simply reclaimed. Otherwise, if there was a destructor for the object, it would be called to properly clean-up the resources of that non-static data member after the body of the destructor for the main class A had completed, but not exited.




回答2:


z is automatically destroyed. This happens for every "automatic" variable. Even for pointers like int*, float*, some_class*, etc. However, when raw pointers are destroyed, they are not automatically deleted. That's how smart pointers behave.

Because of that property, one should always use smart pointers to express ownership semantics. They also don't need any special mentioning in the copy / move constructor / assignment operator, most of the time you don't even need to write them when using smart pointers, as they do all that's needed by themselves.




回答3:


Destroying an object will destroy all the member variables of that object too. You only need to delete the pointer because destroying a pointer doesn't do anything - in particular it doesn't destroy the object that the pointer points to or free its memory.




回答4:


It does, in fact, get automatically destroyed when the class goes out of scope. A very good way to guess if that's the case is that there's no * after its declaration.




回答5:


For PODS (plain old data types) like ints, floats and so on, they are automatically destroyed. If you have objects as data members (e.g. std::string aStr;), their destructors will be automatically called. You only have to manually handle memory freeing (like above) or any other manual object or data cleanup (like closing files, freeing resources and so on).



来源:https://stackoverflow.com/questions/8825339/how-to-manually-destroy-member-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!