C + + Knowledge essentials 6--Define classes that generate objects only on heaps/stacks

Source: Internet
Author: User


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;

Difference:

    • 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 limit the ability to generate objects on the heap or on the stack?


The first thing to look at is the condition to be met on the heap or on the stack to generate the object:


stack : In the stack space, the compiler manages the life cycle of the object, so the compiler checks that all non-static objects ' destructors are accessible and cannot generate this object on the stack if they cannot be accessed. So, to break this condition, set the destructor of the class to private, limiting the inability to generate objects on the stack.


heap : Generate objects on the heap, use the new () operation, allocate memory, and investigate the constructor for initialization. Overloading the new () operation, which is set to private, is not able to allocate memory space outside of the class and cannot generate objects on the heap.



The following detailed analysis See blog: http://blog.csdn.net/szchtx/article/details/12000867


1, can only be built on the heap
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 () {delete this   ;}  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 ()      {          return   New  A ();      }      void  destory ()      {          Delete this   ;      }  };  

2, can only be built on the stack
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:      void * operator  new (size_t  t) {}    void  operator  Delete (void * ptr) {} public   :      A () {}      ~a () {}  

Reference: http://blog.csdn.net/szchtx/article/details/12000867


C + + Knowledge essentials 6--Define classes that generate objects only on heaps/stacks

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.