How to obtain the pointer of a C ++ instance

Source: Internet
Author: User
Sometimes, write c ++ CodeAn instance is initialized, that is, an object is created using the class definition.
For some reason, you need to use this instance in some other places. Of course, you cannot redefine an object. At this time, we can only find a way to obtain the pointer of the previous object. What should I do when pointers cannot be passed parameters? You can use static data members to define an object using the following method.
Class testinstance {public: testinstance (void );~ Testinstance (void );
Public: static testinstance * instance () {If (_ instance = NULL) {_ instance = new testinstance ();} return _ instance;} static void release () {If (_ instance! = NULL) {Delete _ instance; _ instance = NULL;} PRIVATE: static testinstance * _ instance;} testinstance * testinstance: _ instance = NULL;

We use static testinstance * _ instance as the static data member to point to the object itself. This design requires class initialization using the following methods:
Testinstance _ testinstance = testinstance: instance ();

In this way, we can store the pointer of the _ testinstance instance to its own data member.
When we need a testinstance instance, we only need to use the following statement to obtain its pointer:
Testinstance * testinstance = testinstance: instance ();

Of course, remember to manually release objects when they are not needed:
Testinstance: release ();

This technique is useful in many cases!

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.