⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mi26.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML LANG="EN">
<HEAD>
<TITLE>More Effective C++ | Item 26: Limiting the number of objects of a class</TITLE>
<LINK REL=STYLESHEET HREF=../INTRO/ECMEC.CSS>

<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/COOKIE.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">var imagemax = 0; setCurrentMax(0);</SCRIPT>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/DINGBATS.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">
var dingbase = "MI26_DIR.HTM";
var dingtext = "Item M26, P";
if (self == top) {
 top.location.replace(dingbase + this.location.hash);
}
</SCRIPT>

</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" ONLOAD="setResize()">
<!-- SectionName="M26: Limiting the number of objects of a class" -->
<A NAME="5350"></A>
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./MI25_FR.HTM" TARGET="_top">Item 25: Virtualizing constructors and non-member functions</A> &nbsp;&nbsp;<BR>&nbsp;&nbsp;Continue to <A HREF="./MI27_FR.HTM" TARGET="_top">Item 27: Requiring or prohibiting heap-based objects</A></FONT></DIV>

<A NAME="p130"></A>
<P><A NAME="dingp1"></A><font ID="mititle">Item 26: &nbsp;Limiting the number of objects of a class.</font><SCRIPT>create_link(1);</SCRIPT>
</P>

<A NAME="72175"></A>

<P><A NAME="dingp2"></A><A NAME="23500"></A>
Okay, you're crazy about objects, but sometimes you'd like to bound your insanity. For example, you've got only one printer in your system, so you'd like to somehow limit the number of printer objects to one. Or you've got only 16 file descriptors you can hand out, so you've got to make sure there are never more than that many file descriptor objects in existence. How can you do such things? How can you limit the number of <NOBR>objects?<SCRIPT>create_link(2);</SCRIPT>
</NOBR></P>

<P><A NAME="dingp3"></A><A NAME="20311"></A>
If this were a proof by mathematical induction, we might start with n&nbsp;=&nbsp;1, then build from there. Fortunately, this is neither a proof nor an induction. Moreover, it turns out to be instructive to begin with n = 0, so we'll start there instead. How do you prevent objects from being instantiated at <NOBR>all?<SCRIPT>create_link(3);</SCRIPT>
</NOBR></P>

<P><A NAME="dingp4"></A><font ID="mhtitle">Allowing Zero or One Objects</font><SCRIPT>create_link(4);</SCRIPT>
</P>

<P><A NAME="dingp5"></A><A NAME="20337"></A>
Each time an object is instantiated, we know one thing for sure: a constructor will be called. That being the case, the easiest way to prevent objects of a particular class from being created is to declare the constructors of that class <NOBR>private:<SCRIPT>create_link(5);</SCRIPT>
</NOBR></P>

<A NAME="20355"></A>
<UL><PRE>class CantBeInstantiated {
private:
  CantBeInstantiated();
  CantBeInstantiated(const CantBeInstantiated&amp;);
<A NAME="7575"></A>
...
<A NAME="20357"></A>
;
</PRE>
</UL>

<P><A NAME="dingp6"></A><A NAME="20368"></A>
Having thus removed everybody's right to create objects, we can selectively loosen the restriction. If, for example, we want to create a class for printers, but we also want to abide by the constraint that there is only one printer available to us, we can encapsulate the printer object inside a function so that everybody has access to the printer, but only a single printer object is <NOBR>created:<SCRIPT>create_link(6);</SCRIPT>
</NOBR></P>

<A NAME="20406"></A>
<UL><PRE>
class PrintJob;                              // forward declaration
                                             // see <A HREF="../EC/EI34_FR.HTM#6793" TARGET="_top">Item E34</A>
<A NAME="71865"></A>
class Printer {
public:
  void submitJob(const PrintJob&amp; job);
  void reset();
  void performSelfTest();
<A NAME="7576"></A>
...
<A NAME="75556"></A>
friend Printer&amp; thePrinter();
<A NAME="71872"></A>
<A NAME="p131"></A>private:
  Printer();
  Printer(const Printer&amp; rhs);
<A NAME="7577"></A>
  ...
<A NAME="75555"></A>
};
<A NAME="20417"></A>
Printer&amp; thePrinter()
{
  static Printer p;                          // the single printer object
  return p;
}
</PRE>
</UL>

<P><A NAME="dingp7"></A><A NAME="20437"></A>
There are three separate components to this design. First, the constructors of the <CODE>Printer</CODE> class are private. That suppresses object creation. Second, the global function <CODE>thePrinter</CODE> is declared a friend of the class. That lets <CODE>thePrinter</CODE> escape the restriction imposed by the private constructors. Finally, <CODE>thePrinter</CODE> contains a <i>static</i> <CODE>Printer</CODE> object. That means only a single object will be <NOBR>created.<SCRIPT>create_link(7);</SCRIPT>
</NOBR></P>

<P><A NAME="dingp8"></A><A NAME="20466"></A>
Client code refers to <CODE>thePrinter</CODE> whenever it wishes to interact with the system's lone printer. By returning a reference to a <CODE>Printer</CODE> object, <CODE>thePrinter</CODE> can be used in any context where a <CODE>Printer</CODE> object itself could <NOBR>be:<SCRIPT>create_link(8);</SCRIPT>
</NOBR></P>

<A NAME="20487"></A>
<UL><PRE>class PrintJob {
public:
  PrintJob(const string&amp; whatToPrint);
  ...
<A NAME="20492"></A>
};
<A NAME="20493"></A>
string buffer;
<A NAME="20497"></A>
...                                          // put stuff in buffer
<A NAME="37714"></A>
thePrinter().reset();
thePrinter().submitJob(buffer);
</PRE>
</UL>

<P><A NAME="dingp9"></A><A NAME="20914"></A>
It's possible, of course, that <CODE>thePrinter</CODE> strikes you as a needless addition to the global namespace. "Yes," you may say, "as a global function it looks more like a global variable, but global variables are gauche, and I'd prefer to localize all printer-related functionality inside the <CODE>Printer</CODE> class." Well, far be it from me to argue with someone who uses words like gauche. <CODE>thePrinter</CODE> can just as easily be made a static member function of <CODE>Printer</CODE>, and that puts it right where you want it. It also eliminates the need for a <CODE>friend</CODE> declaration, which many regard as tacky in its own right. Using a static member function, <CODE>Printer</CODE> looks like <NOBR>this:<SCRIPT>create_link(9);</SCRIPT>
</NOBR></P>

<A NAME="20915"></A>
<UL><PRE><A NAME="p132"></A>class Printer {
public:
  static Printer&amp; thePrinter();
  ...
<A NAME="57600"></A>
private:
  Printer();
  Printer(const Printer&amp; rhs);
  ...
<A NAME="75581"></A>
};
<A NAME="20919"></A>
Printer&amp; Printer::thePrinter()
{
  static Printer p;
  return p;
}
</PRE>
</UL>

<P><A NAME="dingp10"></A><A NAME="20920"></A>
Clients must now be a bit wordier when they refer to the <NOBR>printer:<SCRIPT>create_link(10);</SCRIPT>
</NOBR></P>

<A NAME="23806"></A>
<UL><PRE>Printer::thePrinter().reset();
Printer::thePrinter().submitJob(buffer);
</PRE>
</UL>

<P><A NAME="dingp11"></A><A NAME="23814"></A>
Another approach is to move <CODE>Printer</CODE> and <CODE>thePrinter</CODE> out of the global scope and into a <I>namespace</I> (see <A HREF="../EC/EI28_FR.HTM#6429" TARGET="_top">Item E28</A>). Namespaces are a recent addition to C++. Anything that can be declared at global scope can also be declared in a namespace. This includes classes, structs, functions, variables, objects, typedefs, etc. The fact that something is in a namespace doesn't affect its behavior, but it does prevent name conflicts between entities in different namespaces. By putting the <CODE>Printer</CODE> class and the <CODE>thePrinter</CODE> function into a namespace, we don't have to worry about whether anybody else happened to choose the names <CODE>Printer</CODE> or <CODE>thePrinter</CODE> for themselves; our namespace prevents name <NOBR>conflicts.<SCRIPT>create_link(11);</SCRIPT>
</NOBR></P>

<P><A NAME="dingp12"></A><A NAME="60498"></A>
Syntactically, namespaces look much like classes, but there are no public, protected, or private sections; everything is public. This is how we'd put <CODE>Printer</CODE> and <CODE>thePrinter</CODE> into a namespace called <CODE>PrintingStuff</CODE>:<SCRIPT>create_link(12);</SCRIPT>
</P>

<A NAME="37735"></A>
<UL><PRE>namespace PrintingStuff {
  class Printer {                            // this class is in the
  public:                                    // PrintingStuff namespace
<A NAME="75591"></A>
    void submitJob(const PrintJob&amp; job);
    void reset();
    void performSelfTest();
    ...
<A NAME="75587"></A>
    friend Printer&amp; thePrinter();
<A NAME="71884"></A>
<A NAME="p133"></A>  private:
    Printer();
    Printer(const Printer&amp; rhs);
    ...
<A NAME="75588"></A>
 };
<A NAME="37742"></A>
 Printer&amp; thePrinter()                        // so is this function
 {
    static Printer p;
    return p;
 }
}                                             // this is the end of the
                                              // namespace
</PRE>
</UL>

<P><A NAME="dingp13"></A><A NAME="37736"></A>
Given this namespace, clients can refer to <CODE>thePrinter</CODE> using a fully-qualified name (i.e., one that includes the name of the <NOBR>namespace),<SCRIPT>create_link(13);</SCRIPT>
</NOBR></P>

<A NAME="37768"></A>
<UL><PRE>PrintingStuff::thePrinter().reset();
PrintingStuff::thePrinter().submitJob(buffer);
</PRE>
</UL>

<P><A NAME="dingp14"></A><A NAME="37766"></A>
but they can also employ a <CODE><I>using</I></CODE> <I>declaration</I> to save themselves <NOBR>keystrokes:<SCRIPT>create_link(14);</SCRIPT>
</NOBR></P>

<A NAME="37776"></A>
<UL><PRE>using PrintingStuff::thePrinter;             // import the name
                                             // "thePrinter" from the
                                             // namespace "PrintingStuff"
                                             // into the current scope
</PRE>
</UL><A NAME="37773"></A>
<UL><PRE>thePrinter().reset();                        // now thePrinter can be
thePrinter().submitJob(buffer);              // used as if it were a
                                             // local name
</PRE>
</UL>

<P><A NAME="dingp15"></A><A NAME="20559"></A>
There are two subtleties in the implementation of <CODE>thePrinter</CODE> that are worth exploring. First, it's important that the single <CODE>Printer</CODE> object be static in a <I>function</I> and not in a class. An object that's static in a class is, for all intents and purposes, <I>always</I> constructed (and destructed), even if it's never used. In contrast, an object that's static in a function is created the first time through the function, so if the function is never called, the object is never created. (You do, however, pay for a check each time the function is called to see whether the object needs to be created.) One of the philosophical pillars on which C++ was built is the idea that you shouldn't pay for things you don't use, and defining an object like our printer as a static object in a function is one way of adhering to this philosophy. It's a philosophy you should adhere to whenever you <NOBR>can.<SCRIPT>create_link(15);</SCRIPT>
</NOBR></P>
<P><A NAME="dingp16"></A><A NAME="20617"></A>
There is another drawback to making the printer a class static versus a function static, and that has to do with its time of initialization. We know exactly when a function static is initialized: the first time through the function at the point where the static is defined. The situ<A NAME="p134"></A>ation with a class static (or, for that matter, a global static, should you be so gauche as to use one) is less well defined. C++ offers certain guarantees regarding the order of initialization of statics within a particular translation unit (i.e., a body of source code that yields a single object file), but it says <i>nothing</i> about the initialization order of static objects in different translation units (see <A HREF="../EC/EI47_FR.HTM#8299" TARGET="_top">Item E47</A>). In practice, this turns out to be a source of countless headaches. Function statics, when they can be made to suffice, allow us to avoid these headaches. In our example here, they can, so why <NOBR>suffer?<SCRIPT>create_link(16);</SCRIPT>
</NOBR></P>
<P><A NAME="dingp17"></A><A NAME="40513"></A>
The second subtlety has to do with the interaction of inlining and static objects inside functions. Look again at the code for the non-member version of <CODE>thePrinter</CODE>:<SCRIPT>create_link(17);</SCRIPT>
</P>

<A NAME="40514"></A>
<UL><PRE>Printer&amp; thePrinter()
{
  static Printer p;
  return p;
}
</PRE>
</UL>

<P><A NAME="dingp18"></A><A NAME="40515"></A>
Except for the first time through this function (when <CODE>p</CODE> must be constructed), this is a one-line function &#151; it consists entirely of the statement "<CODE>return</CODE> <CODE>p</CODE>;". If ever there were a good candidate for inlining, this function would certainly seem to be the one. Yet it's not declared <CODE>inline</CODE>. Why <NOBR>not?<SCRIPT>create_link(18);</SCRIPT>
</NOBR></P>
<P><A NAME="dingp19"></A><A NAME="40516"></A>
Consider for a moment why you'd declare an object to be static. It's usually because you want only a single copy of that object, right? Now consider what <CODE>inline</CODE> means. Conceptually, it means compilers should replace each call to the function with a copy of the function body, but for non-member functions, it also means something else. It means the functions in question have <I>internal linkage</I>.<SCRIPT>create_link(19);</SCRIPT>
</P>
<P><A NAME="dingp20"></A><A NAME="60581"></A>
You don't ordinarily need to worry about such linguistic mumbo jumbo, but there is one thing you must remember: functions with internal linkage may be duplicated within a program (i.e., the object code for the program may contain more than one copy of each function with internal linkage), and <I>this duplication includes static objects contained within the functions</I>. The result? If you create an inline non-member function containing a local static object, you may end up with <i>more than one copy</i> of the static object in your program! So don't create inline non-member functions that contain local static data.<a href="#9110"><sup>9</sup></A><SCRIPT>create_link(20);</SCRIPT>
</P>
<P><A NAME="dingp21"></A><A NAME="20908"></A>
But maybe you think this business of creating a function to return a reference to a hidden object is the wrong way to go about limiting the number of objects in the first place. Perhaps you think it's better to simply count the number of objects in existence and throw an excep<A NAME="p135"></A>tion in a constructor if too many objects are requested. In other words, maybe you think we should handle printer creation like <NOBR>this:<SCRIPT>create_link(21);</SCRIPT>
</NOBR></P>

<A NAME="20924"></A>
<UL><PRE>class Printer {
public:
  class TooManyObjects{};                    // exception class for use

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -