"More effective C + +" clause 26 limiting the number of class objects

Source: Internet
Author: User

Problem:

How can I limit the number of class objects? Like 1, 10 and so on.

Method (1):

If you define a class's constructor as private, you cannot instantiate the class. But how do you create 1 objects out of it? There are 2 types of methods:

1. Declare a friend function, then the constructor can be called in the friend function, and the static limit is used to create the object, then only one object is guaranteed. A similar definition is as follows:

1 classPrinter2 {3  Public:4Friend printer&theprinter ();5 Private:6 Printer ();7Printer (Constprinter&RHS);8 };9printer&theprinter ()Ten { One     StaticPrinter p; A     returnp; -}

2. The same effect can be achieved by defining a static member function instead of the friend function above, that is, the call is troublesome and requires the class name to call the function, but this is also possible, but it can be resolved by defining the class in a namespace (namespace). The namespace can then be invoked directly using the function name (see how to define namespaces). Namespaces can also be used to prevent name collisions, and the benefit of declaring an object in a function is that the object is created only when the function is called. Note: Try not to create static objects in inline functions, possibly producing multiple replicas.

1 classPrinter2 {3  Public:4     Staticprinter& Theprinter ();//Watch this .5 Private:6 Printer ();7Printer (Constprinter&RHS);8 };9printer&theprinter ()Ten { One     StaticPrinter p; A     returnp; -}

Method (2): Define a counter in the class that limits the number of instance objects by counter, and throws an exception once the number of limits is created. (Consider inheritance, and the derived class object is also counted by T.)

"More effective C + +" clause 26 limiting the number of class objects

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.