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

📄 ec7.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 4 页
字号:
  Directory();  ...};Directory::Directory(){  create a Directory object by invoking member  functions on theFileSystem;}Further suppose this client decides to create a distinguished global Directory object for temporary files: Directory tempDir;                  // directory for temporary                                    // filesNow the problem of initialization order becomes apparent: unless theFileSystem is initialized before tempDir, tempDir's constructor will attempt to use theFileSystem before it's been initialized. But theFileSystem and tempDir were created by different people at different times in different files. How can you be sure that theFileSystem will be created before tempDir?This kind of question arises anytime you have non-local static objects that are defined in different translation units and whose correct behavior is dependent on their being initialized in a particular order. Non-local static objects are objects that are defined at global or namespace scope (e.g., theFileSystem and tempDir), declared static in a class, or defined static at file scope.Regrettably, there is no shorthand term for "non-local static objects," so you should accustom yourself to this somewhat awkward phrase.You do not want the behavior of your software to be dependent on the initialization order of non-local static objects in different translation units, because you have no control over that order. Let me repeat that. You have absolutely no control over the order in which non-local static objects in different translation units are initialized.It is reasonable to wonder why this is the case.It is the case because determining the "proper" order in which to initialize non-local static objects is hard. Very hard. Halting-Problem hard. In its most general form with multiple translation units and non-local static objects generated through implicit template instantiations (which may themselves arise via implicit template instantiations) it's not only impossible to determine the right order of initialization, it's typically not even worth looking for special cases where it is possible to determine the right order.In the field of Chaos Theory, there is a principle known as the "Butterfly Effect." This principle asserts that the tiny atmospheric disturbance caused by the beating of a butterfly's wings in one part of the world can lead to profound changes in weather patterns in places far distant. Somewhat more rigorously, it asserts that for some types of systems, minute perturbations in inputs can lead to radical changes in outputs.The development of software systems can exhibit a Butterfly Effect of its own. Some systems are highly sensitive to the particulars of their requirements, and small changes in requirements can significantly affect the ease with which a system can be implemented. For example, Item 29 describes how changing the specification for an implicit conversion from String-to-char* to String-to-const-char* makes it possible to replace a slow or error-prone function with a fast, safe one.The problem of ensuring that non-local static objects are initialized before use is similarly sensitive to the details of what you want to achieve. If, instead of demanding access to non-local static objects, you're willing to settle for access to objects that act like non-local static objects (except for the initialization headaches), the hard problem vanishes. In its stead is left a problem so easy to solve, it's hardly worth calling a problem any longer.The technique sometimes known as the Singleton pattern is simplicity itself. First, you move each non-local static object into its own function, where you declare it static. Next, you have the function return a reference to the object it contains. Clients call the function instead of referring to the object. In other words, you replace non-local static objects with objects that are static inside functions. (See also Item M26.)The basis of this approach is the observation that although C++ says next to nothing about when a non-local static object is initialized, it specifies quite precisely when a static object inside a function (i.e. a local static object) is initialized: it's when the object's definition is first encountered during a call to that function. So if you replace direct accesses to non-local static objects with calls to functions that return references to local static objects inside them, you're guaranteed that the references you get back from the functions will refer to initialized objects. As a bonus, if you never call a function emulating a non-local static object, you never incur the cost of constructing and destructing the object, something that can't be said for true non-local static objects.Here's the technique applied to both theFileSystem and tempDir: class FileSystem { ... };            // same as beforeFileSystem& theFileSystem()          // this function replaces{                                    // the theFileSystem object  static FileSystem tfs;             // define and initialize                                     // a local static object                                     // (tfs = "the file system")  return tfs;                        // return a reference to it}class Directory { ... };             // same as beforeDirectory::Directory(){  same as before, except references to theFileSystem are  replaced by references to theFileSystem();}Directory& tempDir()                 // this function replaces{                                    // the tempDir object  static Directory td;               // define/initialize local                                     // static object  return td;                         // return reference to it}Clients of this modified system program exactly as they used to, except they now refer to theFileSystem() and tempDir() instead of theFileSystem and tempDir. That is, they refer only to functions returning references to those objects, never to the objects themselves.The reference-returning functions dictated by this scheme are always simple: define and initialize a local static object on line 1, return it on line 2. That's it. Because they're so simple, you may be tempted to declare them inline. Item 33 explains that late-breaking revisions to the C++ language specification make this a perfectly valid implementation strategy, but it also explains why you'll want to confirm your compilers' conformance with this aspect of the standard before putting it to use. If you try it with a compiler not yet in accord with the relevant parts of the standard, you risk getting multiple copies of both the access function and the static object defined within it. That's enough to make a grown programmer cry.Now, there's no magic going on here. For this technique to be effective, it must be possible to come up with a reasonable initialization order for your objects. If you set things up such that object A must be initialized before object B, and you also make A's initialization dependent on B's having already been initialized, you are going to get in trouble, and frankly, you deserve it. If you steer shy of such pathological situations, however, the scheme described in this Item should serve you quite nicely. Back to Item 47: Ensure that non-local static objects are initialized before they're used.Continue to Item 49: Familiarize yourself with the standard library.Item 48: Pay attention to compiler warnings.Many programmers routinely ignore compiler warnings. After all, if the problem were serious, it'd be an error, right? This kind of thinking may be relatively harmless in other languages, but in C++, it's a good bet compiler writers have a better grasp of what's going on than you do. For example, here's an error everybody makes at one time or another: class B {public:  virtual void f() const;};class D: public B {public:  virtual void f();};The idea is for D::f to redefine the virtual function B::f, but there's a mistake: in B, f is a const member function, but in D it's not declared const. One compiler I know says this about that: warning: D::f() hides virtual B::f()Too many inexperienced programmers respond to this message by saying to themselves, "Of course D::f hides B::f that's what it's supposed to do!" Wrong. What this compiler is trying to tell you is that the f declared in B has not been redeclared in D, it's been hidden entirely (see Item 50 for a description of why this is so). Ignoring this compiler warning will almost certainly lead to erroneous program behavior, followed by a lot of debugging to find out about something that this compiler detected in the first place.After you gain experience with the warning messages from a particular compiler, of course, you'll learn to understand what the different messages mean (which is often very different from what they seem to mean, alas). Once you have that experience, there may be a whole range of warnings you'll choose to ignore. That's fine, but it's important to make sure that before you dismiss a warning, you understand exactly what it's trying to tell you.As long as we're on the topic of warnings, recall that warnings are inherently implementation-dependent, so it's not a good idea to get sloppy in your programming, relying on compilers to spot your mistakes for you. The function-hiding code above, for instance, goes through a different (but widely used) compiler with nary a squawk. Compilers are supposed to translate C++ into an executable format, not act as your personal safety net. You want that kind of safety? Program in Ada. Back to Item 48: Pay attention to compiler warnings.Continue to Item 50: Improve your understanding of C++.Item 49: Familiarize yourself with the standard library.C++'s standard library is big. Very big. Incredibly big. How big? Let me put it this way: the specification takes over 300 closely-packed pages in the C++ standard, and that all but excludes the standard C library, which is included in the C++ library "by reference." (That's the term they use, honest.)Bigger isn't always better, of course, but in this case, bigger is better, because a big library contains lots of functionality. The more functionality in the standard library, the more functionality you can lean on as you develop your applications. The C++ library doesn't offer everything (support for concurrency and for graphical user interfaces is notably absent), but it does offer a lot. You can lean almost anything against it.Before summarizing what's in the library, I need to tell you a bit about how it's organized. Because the library has so much in it, there's a reasonable chance you (or someone like you) may choose a class or function name that's the same as a name in the standard library. To shield you from the name conflicts that would result, virtually everything in the standard library is nestled in the namespace std (see Item 28). But that leads to a new problem. Gazillions of lines of existing C++ rely on functionality in the pseudo-standard library that's been in use for years, e.g., functionality declared in the headers <iostream.h>, <complex.h>, <limits.h>, etc. That existing software isn't designed to use namespaces, and it would be a shame if wrapping the standard library by std caused the existing code to break. (Authors of the broken code would likely use somewhat harsher language than "shame" to describe their feelings about having the library rug pulled out from underneath them.)Mindful of the destructive power of rioting bands of incensed programmers, the standardization committee decided to create new header names for the std-wrapped components. The algorithm they chose for generating the new header names is as trivial as the results it produces are jarring: the .h on the existing C++ headers was simply dropped. So <iostream.h> became <iostream>, <complex.h> became <complex>, etc. For C headers, the same algorithm was applied, but a c was prepended to each result. Hence C's <string.h> became <cstring>, <stdio.h> became <cstdio>, etc. For a final twist, the old C++ headers were officially deprecated (i.e., listed as no longer supported), but the old C headers were not (to maintain C compatibility). In practice, compiler vendors have no incentive to disavow their customers' legacy software, so you can expect the old C++ headers to be supported for many years.Practically speaking, then, this is the C++ header situation: Old C++ header names like <iostream.h> are likely to continue to be supported, even though they aren't in the official standard. The contents of such headers are not in namespace std. New C++ header names like <iostream> contain the same basic functionality as the corresponding old headers, but the contents of the headers are in namespace std. (During standardization, the details of some of the library components were modified, so there isn't necessarily an exact match between the entities in an old C++ header and those in a new one.) Standard C headers like <stdio.h> continue to be supported. The contents of such headers are not in std. New C++ headers for the functionality in the C library have names like <cstdio>. They offer the same contents as the corresponding old C headers, but the contents are in std.All this seems a little weird at first, but it's really not that hard to get used to. The biggest challenge is keeping all the string headers straight: <string.h> is the old C header for char*-based string manipulation functions, <string> is the std-wrapped C++ header for the new string classes (see below), and <cstring> is the std-wrapped version of the old C header. If you can master that (and I know you can), the rest of the library is easy.The next thing you need to know about the standard library is that almost everything in it is a template. Consider your old friend iostreams. (If you and iostreams aren't friends, turn to Item 2 to find out why you should cultivate a relationship.) Iostreams help you manipulate streams of characters, but what's a character? Is it a char? A wchar_t? A Unicode character? Some other multi-byte character? There's no obviously right answer, so the library lets you choose. All the stream classes are really class templates, and you specify the character type when you instantiate a stream class. For example, the standard library defines the type of cout to be ostream, but ostream is really a typedef for basic_ostream<char>.Similar considerations apply to most of the other classes in the standard library. string isn't a class, it's a class template: a type parameter defines the type of characters in each string class. complex isn't a class, it's a class template: a type parameter defines the type of the real and imaginary components in each complex class. vector isn't a class, it's a class template. On and on it goes.You can't escape the templates in the standard library, but if you're used to working with only streams and strings of chars, you can mostly ignore them. That's because the library defines typedefs for char instantiations for these components of the library, thus letting you continue to program in terms of the objects cin, cout, cerr, etc., and the types istream, ostream, string, etc., without having to worry about the fact that cin's real type is basic_istream<char> and string's is basic_string<char>.Many components in the standard library are templatized much more than this suggests. Consider again the seemingly straightforward notion of a string. Sure, it can be parameterized based on the type of characters it holds, but different character sets differ in details, e.g., special end-of-file characters, most efficient way of copying arrays of them, etc. Such characteristics are known in the standard as traits, and they are specified for string instantiations by an additional template parameter. In addition, string objects are likely to perform dynamic memory allocation and deallocation, but there are lots of different ways to approach that task (see Item 10). Which is best? You get to choose: the string template takes an Allocator parameter, and objects of type Allocator are used to allocate and deallocate the memory used by string objects.Here's a full-blown declaration for the basic_string template and the string typedef that builds on it; you can find this (or something equivalent to it) in the header <string>: namespace std {  template<class charT,

⌨️ 快捷键说明

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