Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Of Many Things


"Well," I sighed to nobody in particular, "Bahb's been at it again."

"What this time?" Wendy's voice floated over the cubicle wall.

"Well, there's a few things. Fortunately, a couple of them are minor. One of them, though...C'mon over and I'll show you his latest abominations," I said in my best Guru imitation. As Wendy came over, I slid aside to let her view the code:

class T
{
  int id_;
public:
  void printValue(FILE * stream);
  void test(int testValue) const;
  // 'tors, etc.
  static const int invalidID_=-1;
};
// Note: FILE passed in via a C API
// wrapper
void T::printValue(FILE * stream)
{
  char buff[20];
  itoa( id_, buff, 10 );
  string value = string( buff );
  fputs( "\"ID=\"", stream );
  fputs( value.c_str(), stream );
}

"First, the string here is completely unnecessary. I think Bob was just trying to score brownie points with Pete," I said, referring to our somewhat clueless manager, "for using the STL."

"Indeed, my apprentice." I don't know what startled me more, the Guru's sudden voice, or the fact that she did not snap closed the tome she customarily carried. "A string is quite overmuch in this situation. The buffer could have been passed directly to the fputs function. Standard strings shine the best when manipulating strings — concatenating them, extracting subsets of them, and so on."

"I don't get why he's even using fputs here," Wendy jumped in. "The whole function can be replaced with a single statement." She took over the keyboard:

void T::printValue(FILE * stream)
{
  fprintf( stream, 
         "\"ID=%d\"", id_ );
}

"Very good, child," the Guru said. "Let us assume for the moment, though, that there is a valid reason for using fputs — an optimization, perhaps, that has been properly profiled." Wendy and I rolled our eyes at each other. The likelihood of Bob properly profiling the program was...well, let's just say I'd bet more money on the lottery than on Bob. A lot more. "What next, apprentice?"

"Ah," I said, "the next one's a little worse." I scrolled to the next function:

void T::test( int testID ) const
{
  if ( id_ > 0 || testID > 0 )
  // do something
}

"Here, he's comparing the IDs against a literal zero. He's overlooked a couple of things. First, the constant indicating an invalid ID is -1. Zero is a valid ID. If an ID of 0 is passed in, the test will fail. Second, he's assuming that the ID will never wrap into negative values. The test will fail for half the valid ID range."

"A most unlikely occurrence, given the problem domain," the Guru answered, "but still worth noting."

"There's another problem, too," Wendy added. "He seems to have forgotten that zero is a magic number."

"Magic number?" I had visions of Bob surrounded by numerology charts and calculations.

"You know," Wendy gave me a withering glare, "a number hard-coded into the program instead of using a const int."

"How would you correct this?" the Guru interrupted.

"Well, by testing for inequality, not greater than," I said as I modified the function:

void T::test( int testID ) const
{
  if ( id_ != invalidID_ || 
       testID != invalidID_ )
  // do something
}

"What else did you find, apprentice?"

"Well, this one's really serious," I said. "I think he's taking advantage of a compiler bug here." I opened another file:

struct U
{
  int & i_;
  u();
};
void f( const U & u )
{
  u.i_ = 43;
}

"He's modifying a member inside a function where the object is const. He should be at least using a const_cast, or something like that." I looked up at the Guru, who was smiling enigmatically. Suddenly, I wasn't so sure.

"What makes you think it's a compiler bug, apprentice?" The Guru stared at me.

"Uh, well, it's gotta be wrong, because it's modifying a member of a constant object."

"Have you checked the Holy Standard, apprentice?" I quickly turned to my keyboard and looked up the appropriate section in the Standard. "Well, I'll be..." I trailed off as I read aloud:

"'Each nonstatic, nonmutable, nonreference data member of a const-qualified class object is const-qualified...'[1] What the hay — why would that be?"

"Well, my child, remember that a reference is somewhat equivalent to a constant pointer to an object — not to be confused with a pointer to a constant object," [2] she said as she began writing on my whiteboard:

struct T
{
  int * const i1_;
  int & i2_;
  int * i3_;
};

"The first two int members are roughly equivalent, for the purposes of this discussion. When working with a nonconstant T object, we can modify the value pointed to by i1_, but we cannot change which integer i1_ points to. Similarly, we can modify the integer referred to by i2_, but we cannot change which integer it refers to."

void f( T & t )
{
  *t.i1_ = 4; // OK
  t.i1_ = NULL; // Error
  t.i2_ = 5; // OK
  t.i3_ = new int; // OK
  *t.i3_ = 43; // OK
}

"When working with a constant T object, the member i3_ behaves as if you had declared the class thusly,"

(const) struct T
{
  int * const i1_;
  int & i2_;
  int * const i3_; // NOTE change
};

"The member i1_ is already const-qualified, so it changes not. And, since i2_ is effectively the same as i1_, that means we are still free to modify the integer being referred to. The only change is that now we may not reseat i3_,"

void f1( T & t )
{
  *t.i1_ = 4; // Still OK
  t.i1_ = NULL; // Still error
  t.i2_ = 5; // Still OK
  t.i3_ = new int; // Error now
  *t.i3_ = 43; // Still OK
}

"Huh," I huh-ed. "So...would it be fair to say that, because the object being referred to is not a member of the class, the constness of the class doesn't affect it?"

"That would be a simpler, although less comprehensive answer — consider the case where the pointer or reference points to a member of the class itself. The same rules still apply,"

struct U
{
  int i_;
  int & iref_;
  U() : iref_( i_ ) {}
};
void f( const U & u )
{
  u.iref_ = 43; // changes u.i_
}

"In this situation, you must be careful not to pass in an object that was originally declared const, as that would lead to the dark path of undefined behavior,"

extern const U u;
void g()
{
  f( u ); // this is Very Bad
}

"Looks like Bob's got one up on you, pardner," Wendy punched me in the arm as the Guru silently glided away.

"Yeah, well, he's still going overboard with his use of strings, and he blew the 'zero is a magic number' rule, so I'm still ahead of him," I grinned.

References

[1] ISO/IEC 14882:1998(E), (C++ Standard) clause 3.9.3.

[2] Thanks to Bryan Ross for providing the pointer analogy to help explain this.

Authors' note: This column dealt with three separate, unrelated items, none of which was large enough to deserve an article in its own right. We hope the distinction between the three topics was clear.


Herb Sutter (http://www.gotw.ca/) is convener of the ISO C++ Standards committee, author of Exceptional C++ and More Exceptional C++, and C++ program manager for Microsoft.

Jim Hyslop is a senior software designer with over 10 years of programming experience in C and C++. Jim works at Leitch Technology International Inc. where he deals with a variety of applications ranging from embedded apps to Windows programs. He can be reached at [email protected].



Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.