Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does C++ define a class that can only generate objects on the heap or stack

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains how C++ defines a class that can only generate objects on the heap or stack. Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how C++ defines a class that can only generate objects on the heap or stack.

In C++, there are two types of object creation for a class:

One is the static establishment, such as AA; the static establishment of a class object, in which the compiler allocates memory for the object in the stack space by directly moving the pointer at the top of the stack to move the appropriate space. then call the constructor in this memory space to form a stack object. Using this method, the constructor of the class is called directly. One is to build dynamically, such as A* ptr=new A; there is a difference between the two ways. To create class objects dynamically is to use the new operator to build objects in the heap space. This process is divided into two steps: the first step is to execute the operator new () function to search for the appropriate memory in the heap space and allocate it; the second step is to call the constructor to construct the object to initialize the memory space. This method calls the constructor of the class indirectly. 1 can only be on the heap

Method: set the destructor to private

Reason: C++ is a statically binding language, and the compiler manages the life cycle of objects on the stack. When allocating stack space for class objects, the compiler first checks the accessibility of the class's destructor. If the destructor is not accessible, you cannot create an object on the stack.

Idea: it's easy to think of making the constructor private. After the constructor is private, you cannot call the constructor outside the class to construct the class object, you can only use the new operator to create the object. However, as mentioned earlier, the execution of the new operator is divided into two steps. C++ provides overloading of the new operator, which only allows you to overload the operator new () function, while the operator () function allocates memory and does not provide construction functionality. Therefore, this method is not allowed.

When the object is built on top of the stack, the memory space is allocated by the compiler and the constructor is called to construct the stack object. When the object is finished, the compiler calls the destructor to free up the space occupied by the stack object. The compiler manages the entire lifecycle of the object. What happens if the compiler cannot call the class's destructor? For example, the destructor of a class is private and the compiler cannot call the destructor to free memory. Therefore, when allocating stack space to a class object, the compiler will first check the accessibility of the class destructor, not only the destructor, but also as long as it is a non-static function. If the class's destructor is private, the compiler does not allocate memory for the class object on the stack space.

If the destructor is made private, the class object cannot be built on the stack.

Code:

# include

Using namespace std

/ / only open 2020.05.22 on the stack

Class A

{

Public:

A () {}

Void destory ()

{

Delete this

}

Private:

~ A () {}

}

Int main ()

{

An a

Return 0

}

Use AA to create objects and compile error reports

Indicates that the destructor cannot be accessed. In this way, the object can only be created using the new operator, and the constructor is public and can be called directly. A destory function must be provided in the class to free up memory space. After the class object is used, the destory function must be called.

One of the disadvantages of the above approach is that it cannot solve the inheritance problem. If An is the base class of other classes, the destructor is usually set to virtual and then rewritten in the subclass to achieve polymorphism. Therefore, the destructor cannot be set to private. Fortunately, C++ provides a third kind of access control, protected. Setting the destructor to protected can effectively solve this problem. Protected members cannot be accessed outside the class, but can be accessed by subclasses.

Another problem is that the use of classes is inconvenient, using new to create objects, but using destory functions to release objects instead of using delete. (using delete will report an error because the pointer to the delete object invokes the object's destructor, which is not accessible outside the destructor class.) this is a strange way to use it. For unification, you can set the constructor to protected, and then provide a static function of public to complete the construction, so that instead of using new, you can use a function to construct and a function to destruct. The code is as follows, similar to the singleton pattern:

# include

Using namespace std

/ / only open 2020.05.22 on the stack

Class A

{

Protected:

A () {}

~ A () {}

Public:

Static A * create ()

{

Return new A ()

}

Void destory ()

{

Delete this

}

}

Int main ()

{

A * ptr = A::create ()

Ptr- > destory ()

Return 0

}

In this way, the create () function is called to create a class An object on the heap, and the destory () function is called to free memory.

2 can only be on the stack

Method: overload new and delete as private

Reason: the process of generating objects on the heap using the new keyword operation is divided into two stages: the first stage, using new to find available memory on the heap and allocating to objects; the second stage, calling the constructor to generate objects. If the new operation is made private, the first phase cannot be completed and objects cannot be generated on the heap.

Idea: objects are built on the heap only if you use the new operator, so as long as you disable the new operator, you can realize that class objects can only be built on the stack. Just make operator new () private.

Code:

Class A

{

Private:

Void * operator new (size_t t) {} / / Note that the first argument and return value of the function are fixed.

Void operator delete (void * ptr) {} / / if you overload new, you need to reload delete.

Public:

A () {}

~ A () {}

Now that you have a better understanding of how C++ defines a class that can only generate objects on the heap or stack, you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report