[ Team LiB ] Previous Section Next Section

Gotcha #10: Ignorance of Idiom

It is an old observation that the best writers sometimes disregard the rules of rhetoric. When they do so, however, the reader will usually find in the sentence some compensating merit, attained at the cost of the violation. Unless he is certain of doing as well, he will probably do best to follow the rules. (Strunk and White, The Elements of Style)[1]

[1] The author of this quote is actually William Strunk, since it appeared in the original volume before the book's resurrection by White in 1959.

This often-quoted advice from the classic guide to clarity in English prose often finds its way into texts on programming style as well. I approve of the quote and the chastening sentiment behind it. However, I find it unsatisfying because, taken out of context, it doesn't indicate why it's generally profitable to follow the rules of rhetoric and how those rules come about. I've always preferred White's cowpath simile to Strunk's Olympian dictum:

The living language is like a cowpath: it is the creation of the cows themselves, who, having created it, follow it or depart from it according to their whims or their needs. From daily use, the path undergoes change. A cow is under no obligation to stay in the narrow path she helped make, following the contour of the land, but she often profits by staying with it and she would be handicapped if she didn't know where it was and where it led to. (E. B. White, Writings from The New Yorker)

Programming languages are not as complex as natural languages, and our goal of writing clear code is not as difficult to achieve as that of writing clear sentences. A programming language like C++, however, is sufficiently complex that effective programming in the language depends upon a body of standard usage and idiom. The design of the C++ language is not proscriptive, in that it allows much flexibility in how it may be used, but idiomatic usage of language features allows efficient and clear communication of a design. Ignorance or willful disregard of idiom is an invitation to misunderstanding and misuse.

Much of the advice found in this book involves being aware of and employing idioms in C++ coding and design. Many of the gotchas listed here could be described simply as departing from a particular C++ idiom. The accompanying solution to the problem could often be described simply as following the appropriate idiom. There's a reason for this: the body of idiom in C++ coding and design has been built up and continuously refined by the community of C++ programmers as a whole. Approaches that don't work or that are out of date fall out of favor and are discarded. Idioms that survive are those that evolve to suit the environment of their use. Being aware of—and employing—C++ coding and design idioms is one of the surest ways of producing clear, effective, and maintainable C++ code and designs.

As competent professional programmers, we should be aware, always, that our code and designs exist within a context of idiom. If we are aware of coding and design idioms, we can choose to stay within their narrow path or make an educated decision to depart from them according to our needs. However, we can most often profit by staying within them, and we would be handicapped indeed if we were ignorant of them.

I don't mean to inadvertently give the impression that our C++ programming idioms are in some way a straitjacket that controls every aspect of the design process. Far from it. Properly used, idiom can simplify the process of design and communication of a design, leaving the designer free to expend creativity where it's needed. Sometimes even the most sensible and common programming idiom is inappropriate to the context of a design, and the designer is forced to depart from the standard approach.

One of the most common and useful C++ idioms is the copy operation idiom. Every abstract data type in C++ should make a decision about its copy assignment operator and copy constructor. Either the compiler should be allowed to write them, the programmer should write them, or they should be disallowed (see Gotcha #49).

If the programmer writes these operations, we know exactly how they should be written. However, the "standard" way of writing these operations has evolved over the years. This is one of the advantages of idiom over dictate; idiom evolves to suit the current context of use.



class X { 


 public:


   X( const X & );


   X &operator =( const X & );


   // . . .


};


While the C++ language permits a lot of leeway in the definitions of copy operations, it's almost invariably a good idea to declare these operations as they are above: both operations take a reference to a constant, and the copy assignment is nonvirtual and returns a reference to a non-const. Clearly, neither of these operations will change its operand. It wouldn't make sense.



X a; 


X b( a ); // a won't change


a = b; // b won't change


Except sometimes. The standard C++ auto_ptr template has some unusual requirements. It's a resource handle charged with cleaning up heap-allocated storage when the storage is no longer needed:



void f() { 


   auto_ptr<Blob> blob( new Blob );


   // . . .


   // automatic deletion of allocated Blob


}


Fine, but what happens when the student interns are set loose on this code?



void g( auto_ptr<Blob> arg ) { 


   // . . .


   // automatic deletion of allocated Blob


}


void f() {


   auto_ptr<Blob> blob( new Blob );


   g( blob );


   // another deletion of allocated Blob!!!


}


One approach might be to disallow copy operations for auto_ptr, but that would severely limit their use and would make impossible a number of useful auto_ptr idioms. Another approach might be to add a reference count to the auto_ptr, but that would increase the expense of employing a resource handle. The approach taken by the standard auto_ptr is to depart from the copy operation idiom intentionally:



template <class T> 


class auto_ptr {


   public:


   auto_ptr( auto_ptr & );


   auto_ptr &operator =( auto_ptr & );


   // . . .


 private:


   T *object_;


};


(The standard auto_ptr also implements template member functions corresponding to these nontemplate copy operations, but the observations for those are similar. See also Gotcha #88.) Here the right side of each operation is non-const! When one auto_ptr is initialized by or assigned to by another, the source of the initialization or assignment gives up ownership of the heap-allocated object to which it refers by setting its internal object pointer to null.

As is often the case when departing from idiom, some confusion initially arose about how to use auto_ptr properly. However, this departure from an existing idiom has allowed the development of a number of productive new idioms centered on object ownership issues, and the use of auto_ptrs as "sources" and "sinks" of data looks to be a profitable new design area. In effect, an educated departure from an existing, successful idiom has resulted in a family of new idioms.

    [ Team LiB ] Previous Section Next Section