More Effective C ++ 26

xiaoxiao2021-04-04  278

Terms 26: Restrict the number of objects that can be produced in a Class

Allow zero or an object

Zero, very simple, privatizes the constructor of the object. One, it is also very simple, Singleton mode. I also have blogs to discuss local static objects in front.

Construction status of different objects

There are three states of objects, (1) Objects (2) existing in derived class object (3) as a member object exists in a larger object. We usually do this, usually do this

Class A

{

Private:

A () {}

A (const a &) {}

PUBLIC:

Static a * Makea () {Return New A ();

Static A * Makea (Const A & a) {Return New A (A);

}

In order to avoid resource leakage, such objects can usually be placed in a smart pointer.

Allow objects to endocate

When more than one object, you can make a limit in Makea () if a number of times returns NULL or throws an exception.

Class A

{

Private:

A () {}

A (const a &) {}

~ A () {- NumObjects;

Static size_t numoBjects;

Static const size_t maxObjects;

PUBLIC:

Static a * Makea ()

{

IF (NumObjects> = maxObjects)

Return NULL;

Else

{

NumObjects;

Return new a ();

}

}

Static A * Makea (Const A & A)

{

IF (NumObjects> = maxObjects)

Return NULL;

Else

{

NumObjects;

Return new a (a);

}

}

}

SIZE_T A :: NumObjects = 0;

Const size_t a :: maxObjects = 10;

Base Class used to calculate the number of objects

Consider the following code:

Template

<

Class

Beingcounted

>

Class

Ccounted

{

public

:

Class

Toomanyojects

{};

Static

int

Objectcount

() {

Return

NumberObjects

}

protected

:

Ccounted

() {

init

();

Ccounted

(

Const

Ccounted

&

RHS

) {

init

();

Virtual

~

Ccounted

() {

NumberObjects

}

Private

:

Static

Const

int

MaxObjects

;

Static

int

NumberObjects

;

Void

init

()

{

IF

(

NumberObjects

> =

MaxObjects

)

Throw

Toomanyojects

();

NumberObjects

;

}

}

Template

<

Class

Beingcounted

>

int

Ccounted

<

Beingcounted

> ::

NumberObjects

= 0;

Template

<

Class

Beingcounted

>

Const

int

Ccounted

<

Beingcounted> ::

MaxObjects

= 10;

Class

PRINTER

:

Private

Ccounted

<

PRINTER

>

{

public

:

Static

PRINTER

*

Makeprinter

() {

Return

New

PRINTER

}

Static

PRINTER

*

Makeprinter

(

Const

PRINTER

&

RHS

) {

Return

New

PRINTER

(

RHS

}

Virtual

~

PRINTER

() {}

Using

Ccounted

<

PRINTER

> ::

Objectcount

;

Private

:

PRINTER

() {}

PRINTER

(

Const

PRINTER

&) {}

}

The following code, I tested in VC6, there is no problem. On the original basis, in the destructure, the decrease in the number of objects was added. This is based on future object reference counts.

转载请注明原文地址:https://www.9cbs.com/read-131926.html

New Post(0)