Successful builds should be silent (warning-free). If they aren't, you'll quickly get into the habit of skimming the output, and you will miss real problems. (See Item 2.)
To get rid of a warning: a) understand it; and then b) rephrase your code to eliminate the warning and make it clearer to both humans and compilers that the code does what you intended.
Do this even when the program seemed to run correctly in the first place. Do this even when you are positive that the warning is benign. Even benign warnings can obscure later warnings pointing to real dangers.
#include
s the original header and selectively turns off the noisy warnings for that scope only, and then
#include
your wrapper throughout the rest of your project. Example (note that the warning control syntax will vary from compiler to compiler):
// File: myproj/my_lambda.h -- wraps Boost's lambda.hpp // Always include this file; don't use lambda.hpp directly. // NOTE: Our build now automatically checks "grep lambda.hpp <srcfile>". // Boost.Lambda produces noisy compiler warnings that we know are innocuous. // When they fix it we'll remove the pragmas below, but this header will still exist. // #pragma warning(push) // disable for this header only #pragma warning(disable:4512) #pragma warning(disable:4180) #include <boost/lambda/lambda.hpp> #pragma warning(pop) // restore original warning level
Example 2: "Unused function parameter." Check to make sure you really didn't mean to use the function parameter (e.g., it might be a placeholder for future expansion, or a required part of a standardized signature that your code has no use for). If it's not needed, simply delete the name of a function parameter:
// ... inside a user-defined allocator that has no use for the hint ... // warning: "unused parameter 'localityHint'" pointer allocate( size_type numObjects, const void *localityHint = 0 ) { return static_cast<pointer>( mallocShared( numObjects * sizeof(T) ) ); } // new version: eliminates warning pointer allocate( size_type numObjects, const void * /* localityHint */ = 0 ) { return static_cast<pointer>( mallocShared( numObjects * sizeof(T) ) ); }
Example 3: "Variable defined but never used." Check to make sure you really didn't mean to reference the variable. (An RAII stack-based object often causes this warning spuriously; see Item 13.) If it's not needed, often you can silence the compiler by inserting an evaluation of the variable itself as an expression (this evaluation won't impact run-time speed):
// warning: "variable 'lock' is defined but never used" void Fun() { Lock lock; // ... } // new version: probably eliminates warning void Fun() { Lock lock; lock; // ... }
Example 4: "Variable may be used without being initialized." Initialize the variable (see Item 19).
Example 5: "Missing return
." Sometimes the compiler asks for a return
statement even though your control flow can never reach the end of the function (e.g., infinite loop, throw
statements, other return
s). This can be a good thing, because sometimes you only think that control can't run off the end. For example, switch
statements that do not have a default
are not resilient to change and should have a default
case that does assert( false )
(see also Items 68 and 90):
// warning: missing "return" int Fun( Color c ) { switch( c ) { case Red: return 2; case Green: return 0; case Blue: case Black: return 1; } } // new version: eliminates warning int Fun( Color c ) { switch( c ) { case Red: return 2; case Green: return 0; case Blue: case Black: return 1; default: assert( !"should never get here!" ); // !"string" evaluates to false return -1; } }
Example 6: "Signed/unsigned mismatch." It is usually not necessary to compare or assign integers with different signedness. Change the types of the variables being compared so that the types agree. In the worst case, insert an explicit cast. (The compiler inserts that cast for you anyway, and warns you about doing it, so you're better off putting it out in the open.)
The C++ Standard says not one word about threads. Nevertheless, C++ is routinely and widely used to write solid multithreaded code. If your application shares data across threads, do so safely:
Note that the above applies regardless of whether the type is some kind of string type, or an STL container like a vector
, or any other type. (We note that some authors have given advice that implies the standard containers are somehow special. They are not; a container is just another object.) In particular, if you want to use standard library components (e.g., string
, containers) in a multithreaded program, consult your standard library implementation's documentation to see whether that is supported, as described earlier.
When authoring your own type that is intended to be usable in a multithreaded program, you must do the same two things: First, you must guarantee that different threads can use different objects of that type without locking (note: a type with modifiable static data typically can't guarantee this). Second, you must document what users need to do in order to safely use the same object in different threads; the fundamental design issue is how to distribute the responsibility of correct execution (race-and deadlock-free) between the class and its client. The main options are:
Push
, Pop
). More generally, note that this option is appropriate only when you know two things: First, you must know up front that objects of the type will nearly always be shared across threads, otherwise you'll end up doing needless locking. Note that most types don't meet this condition; the vast majority of objects even in a heavily multithreaded program are never shared across threads (and this is good; see Item 10).
Second, you must know up front that per-member-function locking is at the right granularity and will be sufficient for most callers. In particular, the type's interface should be designed in favor of coarse-grained, self-sufficient operations. If the caller typically needs to lock several operations, rather than an op- eration, this is inappropriate; individually locked functions can only be assembled into a larger-scale locked unit of work by adding more (external) locking. For example, consider a container type that returns an iterator that could become invalid before you could use it, or provides a member algorithm like find that can return a correct answer that could become the wrong answer before you could use it, or has users who want to write if( c.empty() ) c.push_back(x);
. (See [Sutter02] for additional examples.) In such cases, the caller needs to perform external locking anyway in order to get a lock whose lifetime spans multiple individual member function calls, and so internal locking of each member function is needlessly wasteful.
So, internal locking is tied to the type's public interface: Internal locking becomes appropriate when the type's individual operations are complete in themselves; in other words, the type's level of abstraction is raised and expressed and encapsulated more precisely (e.g., as a producer-consumer queue rather than a plain vector
). Combining primitive operations together to form coarser common operations is the approach needed to ensure meaningful but simple function calls. Where combinations of primitives can be arbitrary and you cannot capture the reasonable set of usage scenarios in one named operation, there are two alternatives: a) use a callback-based model (i.e., have the caller call a single member function, but pass in the task they want performed as a command or function object; see Items 87 to 89); or b) expose locking in the interface in some way.
Particularly if you are authoring a widely-used library, consider making your objects safe to use in a multithreaded program as described above, but without added overhead in a single-threaded program. For example, if you are writing a library containing a type that uses copy-on-write, and must therefore do at least some internal locking, prefer to arrange for the locking to disappear in single-threaded builds of your library (#ifdef
s and no-op implementations are common strategies).
When acquiring multiple locks, avoid deadlock situations by arranging for all code that acquires the same locks to acquire them in the same order. (Releasing the locks can be done in any order.) One solution is to acquire locks in increasing order by memory address; addresses provide a handy, unique, application-wide ordering.
Given that inheritance is nearly the strongest relationship we can express in C++, second only to friendship, it's only really appropriate when there is no equivalent weaker alternative. If you can express a class relationship using composition alone, you should prefer that.
In this context, "composition" means simply embedding a member variable of a type within another type. This way, you can hold and use the object in ways that al- low you control over the strength of the coupling.
Composition has important advantages over inheritance:
Of course, these are not arguments against inheritance per se. Inheritance affords a great deal of power, including substitutability and/or the ability to override virtual functions (see Items 36 through 39, and Exceptions below). But don't pay for what you don't need; unless you need inheritance's power, don't endure its drawbacks.
Even if you don't need to provide a substitutability relationship to all callers, you do need nonpublic inheritance if you need any of the following, in rough order from most common (the first two points) to exceedingly rare (the rest):
[Alexandrescu02a] A. Alexandrescu. "Multithreading and the C++ Type System" (InformIT website, February 2002).
[Alexandrescu04] A. Alexandrescu. "Lock-Free Data Structures" (>cite>C/C++ Users Journal, 22(10), October 2004).
[Butenhof97] D. Butenhof. Programming with POSIX Threads (Addison- Wesley, 1997).
[Cargill92] T. Cargill. C++ Programming Style (Addison-Wesley, 1992).
[Cline99] M. Cline, G. Lomow, and M. Girou. C++ FAQs (2nd Edition) (Addison-Wesley, 1999).
[Dewhurst03] S. Dewhurst. C++ Gotchas (Addison-Wesley, 2003).
[Henney00] K. Henney. "C++ Patterns: Executing Around Sequences" (EuroPLoP 2000 proceedings).
[Henney01] K. Henney. "C++ Patterns: Reference Accounting" (EuroPLoP 2001 proceedings).
[Lakos96] J. Lakos. Large-Scale C++ Software Design (Addison-Wesley, 1996).
[McConnell93] S. McConnell. Code Complete (Microsoft Press, 1993).
[Meyers97] S. Meyers. Effective C++ (2nd Edition) (Addison-Wesley, 1997).
[Meyers04] S. Meyers and A. Alexandrescu. "C++ and the Perils of Double- Checked Locking, Part 1" and "�Part 2" (Dr. Dobb's Journal, 29(7,8), July and August 2004).
[Schmidt01] D. Schmidt, M. Stal, H. Rohnert, F. Buschmann. Pattern- Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects (Wiley, 2001).
[Stroustrup94] B. Stroustrup. The Design and Evolution of C++ (Addison- Wesley, 1994).
[Stroustrup00] B. Stroustrup. The C++ Programming Language (Special 3rd Edition) (Addison-Wesley, 2000).
[Sutter00] H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
[Sutter02] H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
[Sutter04c] H. Sutter. "'Just Enough' Thread Safety" (C/C++ Users Journal, 22(9), September 2004).
Have an opinion? Readers have already posted 1 comment about this article. Why not add yours?
Andrei Alexandrescu is the author of the award-winning book Modern C++ Design (Addison-Wesley, 2001) and is a columnist for C/C++ Uses Journal.
-
Artima provides consulting and training services to help you make the most of Scala, reactive
and functional programming, enterprise systems, big data, and testing.