20220610 C++ destructor return value?

start

I thought of a question today: the destructor obviously has no return value, why can it be accessed with a pointer when instantiating a class?
After some searching, it is concluded that it is actually the function of the new keyword.

The original text is as follows

Reference content: https://blog.csdn.net/raoqiang19911215/article/details/51286869

The process of class to object is the process of instantiation. I often see two ways, one is like this:

class A{
    
    
	。。。
}

void main(){
    
    
	A a;
}

The other is this:

class A{
    
    
	。。。
}

void main(){
    
    
	A *a=new A();
}
//————————————————
//版权声明:本文为CSDN博主「raoqiang19911215」的原创文章,遵循CC 4.0 BY-SA#版权协议,转载请附上原文出处链接及本声明。
//原文链接:#https://blog.csdn.net/raoqiang19911215/article/details/51286869

One of the above two methods can be seen as defining an object in the main function, and the other can be seen as a new object. The main differences are as follows:

1. Their storage space is different, directly define an object on the stack, and put an new object on the heap

2. The usage occasions are different. Since the stack is small and is mainly used to store temporary variables, the life cycle of defining an object in the scope of {} is over. The new object is placed on the heap, and its pointer can be returned through the function, and You need to manually destroy this object or there will be a memory leak

3. The characteristics of new:

New creates a class object that needs to receive a pointer, one place is initialized, multiple places use
new to create a class object, delete is required to destroy
the new created object directly uses the heap space, and the local class object is defined without new and uses the stack space
The new object pointer has a wide range of uses, such as As a function return value, function parameter, etc.,
frequent calls are not suitable for new, just like new application and release of memory

Guess you like

Origin blog.csdn.net/Vissence/article/details/125216225