C + + memory allocation (New,operator new) detailed

Source: Internet
Author: User

Reference: C + + memory allocation (New,operator new) detailed

How to restrict an object to be built on a heap or on a stack

New operator and operator new ()

NEW: Refers to the operators we commonly use in C + +, such as a * a = new A; For new, there is new and:: New, the former is in STD

Operator new (): Refers to the overloaded form of new, which is a function , not an operator. For operator new, the global overloads are divided into global overloads and class overloads , which are void*:: operator new (size_t size), overloaded form void* a::operator new (size_t size) in the class. It is also important to note that the operator new () operation is generally just allocating memory, in fact the system defaults to the global : operator new (size_t size) just calls malloc to allocate memory, and returns a void* pointer . The constructor's call, if needed, is done in the new operator.

Relationship between new and operator new * a = new A; We know there are two steps here:1. Allocate memory, 2. Call a () construct object. In fact, allocating memory is done by operator new (size_t), and if Class A overloads operator new, A::operator new (size_t) is called, and if there is no overload, it is called: operator new ( size_t), the global new operator is provided by C + + by default. So the previous two steps are:1. Call operator new 2. Call the constructor.

(1) NEW: cannot be overloaded, its behavior is always consistent. It first calls operator new to allocate memory, and then calls the constructor to initialize that piece of memory.

The new operator executes the procedure:
1. Call operator new to allocate memory;
2. Call the constructor to generate the class object;
3. Return the appropriate pointer.

(2) operator NEW: To implement different memory allocation behavior, operator new should be overloaded instead of new.

operator new is like Operator +, which can be overloaded. If operator new is not overloaded in the class, then the call is global: operator new to complete the heap allocation. Similarly, operator new[], operator delete, operator delete[] can also be overloaded.

How to restrict an object to be built on a heap or on a stack

In C + +, the object of a class is built into two types, one is static, such as a A, and the other is dynamic, such as a * ptr=new A;

Statically establishes a class object that is allocated by the compiler to the object in the stack space, by directly moving the stack top pointer, to move the appropriate space, and then call the constructor on this memory space to form a stack object. Using this method, the constructor of the class is called directly.

A class object is created dynamically by using the new operator to build the object in the heap space . This is a two-step process, the first step is to execute the operator new () function , search for the appropriate memory in the heap space and allocate it, and the second step is to call the constructor to construct the object and initialize the memory space. This method indirectly invokes the constructor of the class.

So how do you restrict a class object to be built on a heap or stack? The following are discussed separately.

Can only be built on the heap (set destructor to protected)

A class object can only be built on a heap, or it cannot statically establish a class object, that is, the constructor of a class cannot be called directly.

It is easy to think of setting the constructor to private. After the constructor is private, the constructor cannot be called outside the class to construct the class object, only the new operator can be used to build the object. However, as mentioned earlier, the execution of the new operator is a two-step process, and C + + provides overloads of the new operator, in fact, only allowing the operator new () function to be overloaded, while the operator () function allocates memory and does not provide a construction capability. Therefore, this method is not possible.

When the object is built on top of the stack, the compiler allocates memory space and calls the constructor 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 life cycle of an object. What would happen if the compiler could not call the class's destructor? For example, the destructor for a class is private, and the compiler cannot call the destructor to free memory. So, when the compiler allocates stack space for a class object, it checks the class's destructor for access, in fact not just the destructor, as long as the non-static function, the compiler will check. If a class's destructor is private, the compiler does not allocate memory on the stack space for the class object.

Therefore, the destructor is set to private, and the class object cannot be built on the stack. The code is as follows:

class A  {  public:      A () {}      void destory () {Deletethis;}   Private:      ~A () {}  };  

try to use A; To build an object, compile an error, and indicate that the destructor cannot be accessed. This allows the object to be built using the new operator, which is public and can be called directly. A destory function must be provided in the class to release the memory space. After the class object is used, you must call the Destory function.

One drawback of the above approach is that inheritance issues cannot be resolved. If a is a base class for other classes, the destructor is usually set to virtual and then overridden in subclasses to implement polymorphism. Therefore, destructors cannot be set to private. Fortunately C + + provides a third type of access control, protected. Setting the destructor to protected can solve this problem effectively, the protected member cannot be accessed outside the class, and the subclass can be accessed.

Another problem is that the use of classes is inconvenient, using new to create objects, but using the Destory function to dispose of objects instead of using Delete. (using delete will cause an error, because a pointer to the delete object will call the object's destructor, and the destructor is not accessible outside the class) This is a weird way to use it. For the sake of unification, you can set the constructor to protected and then provide a public static function to complete the construction, so that you do not use new, but instead use a function to construct it, using a function to deconstruct it. The code looks like the singleton pattern:

class A  {  protected:      A () {}      ~A () {}  public:       Static A * Create (      )          {returnnew  A ()      ;      } void destory ()      {          deletethis;      }  };  

In this way, the call to create () function creates a Class A object on the heap and calls the Destory () function to free memory.

Can only be built on the stack (the overloaded new function is set to private)

Objects are built on the heap only with the new operator, so the class object can only be built on the stack as long as the new operator is disabled. Set operator new () to private. The code is as follows:

class A  {  private:      voidoperatornew(size_t t) {}     //  Note that the  first and return values of a function are fixed    voidoperatorDelete(void  //  Reload the new to overload delete  public:      A () {}      ~A () {}  };

C + + memory allocation (New,operator new) detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.