Archive for the ‘C++’ Category

When should one use const_cast<>, anyway?

Saturday, June 12th, 2010

I saw a question on StackOverflow asking about why one would use const_cast. Because I’ve thought about that question lately I glossed over that they were asking specifically about applications of casting away volatile…which I didn’t even know you could use const_cast to do!

So I learned something. But I thought the answer I wrote to why you would use const_cast at all was pretty decent, so I was going to leave it there. But then I decided it was too off topic so I’d move it here.


The most common use of const_cast I’ve seen (with const) is this scenario:

  • You’re calling a library that has something like a printFoo(Foo* fooPointer) function, which clearly requires a non-const Foo.
  • There’s good reason to be “sure” this function doesn’t modify the Foo, but you’re unable to change the prototype or the source to express that knowledge for some reason.
  • Your code has made an effort to only use Foo* in contexts where writability is needed and const Foo* in all other contexts.

…that means that as a stopgap measure, you’ll have to const_cast in order to cross this divide and call the routine.

OTOH, the most legitimate use I know of is in subsystems that own objects in a non-const sense, yet have cases where they hand back const pointers to callers. The subsystem natively has more privileges on those objects, so if a caller passes one of those const pointers back it can “upgrade” the privileges.

Sure, the subsystem could store a useless map from non-const pointers to const ones…but const_cast is more time and space efficient:

const SubsystemObject* Subsystem::getReadOnlyObjectById(int id) {
     SubsystemObject* subsystemObject = getObjectCore(id);
 
#ifdef WORLD_WITHOUT_CONST_CAST
     constMap[subsystemObject] = subsystemObject;
#endif
 
     return subsystemObject;
}
 
void Subsystem::someMethod(const SubsystemObject* constSubsystemObject) {
     SubsystemObject* subsystemObject;
 
#ifdef WORLD_WITHOUT_CONST_CAST
     subsystemObject = constMap[constSubsystemObject];
#else
     subsystemObject = const_cast<SubsystemObject*>(constSubsystemObject);
#endif
 
     doSomethingNeedingNonConstAccess(subsystemObject);
}

Treating Non-Boolean Types as Logic Values

Monday, October 26th, 2009

Historically, I have always disliked the idea of using boolean test operations on types that can take a number of values. This deep-seated aesthetic grudge comes from cases like this:

int x = 0;
if (not x)
   cout << "X is zero" << endl;

I’m simply bothered by this. Perhaps it’s a cognitive thing where I just don’t feel there’s any “truth” to the idea that every non-zero integer is somehow “true” but zero is somehow “false”. It could just as easily be that negative numbers are false and non-negative numbers are true. Or if you ask a mathematical purist, they might suggest that at a more foundational level it is primes that are true and non-primes are false!

My comfort zone is when I’m only testing for “truth” and “falsehood” those things that can only have the values true and false. If I could, I would enforce this. So in the example above I would always write something more like:

int x = 0;
if (x == 0)
   cout << "X is zero" << endl;

That particular example is not very controversial, and I think most programmers would agree with me that’s a better way to test against a literal zero. It’s just better code for capturing the intention.

Yet I have historically considered that a logical extension of “zero is not false” is the premise that “null pointers are not false”. And that belief is contrary to practice:

shared_ptr< foo > fooPointer;
if (not fooPointer)
   cout << "fooPointer is null" << endl;

In fact, look what a mouthful you get if you insist on comparing against null literally:

shared_ptr< foo > fooPointer;
if (fooPointer.get() == nullptr)
   cout << "fooPointer is null" << endl;

In the past I have tried to work around this by creating inline template wrappers like “isNull()” so that I could stick to my guns and avoid flattening pointers into booleans. It doesn’t cost any more in the runtime, so I figured what’s the harm?

template< class T > inline bool isNull(shared_ptr< T > ptr) {
	return !ptr;
}

Yet I’ve decided this is a lost cause and too much of a speed bump in sharing my code with other C++ programmers. They’ve accepted the notion that null pointers are false and non-null pointers are true, and you use boolean logic to test this—not some other operator. It’s not worth it to pick this particular fight.

I’m not happy about it. But I now accept this for pointers only. And I’m going to use “not” instead of “!”… it’s part of the language and a lot more readable.

Smart Pointer Casting Study

Friday, July 10th, 2009

If you’re using public inheritance in C++, the compiler will implicitly “upcast” from a Derived class pointer to a Base class pointer. So I thought a std::auto_ptr to a Derived class would have a similar implicit upcast. It does…but only for assignment and construction!

auto_ptr_cast.cpp

The example shows that if you try to pass an auto_ptr<Derived> to a function that takes an auto_ptr<Base>, it fails to convert due to an ambiguity. You must put an explicit static_cast< auto_ptr<Base> > at the calling site.

This “minor” problem led me down an investigation of the state of auto_ptr and its alternative, unique_ptr. I sought the wisdom of friends and people on the Freenode IRC. Wound up even building a newer version of gcc than came with the latest Kubuntu distribution! Though my findings are not the most exciting subject for a blog, I thought writing them up might help someone.

So I have good news, and bad news…

(more…)

8-Year-Olds Should *Read* My Code

Tuesday, June 16th, 2009

A couple years ago, I read an article that gained popularity on social-bookmarking sites which was entitled “8-year-olds should test my code”. It’s a story about a child named Brian (no relation :P), who crashed UCBLogo only seconds after encountering it for the first time:

Logo Crash Caused By 8-Year-Old

The author is an engineer at Google, and said this:

“I had played with UCBLogo for two weeks and hadn’t made it crash once. Brian brought the whole thing down in three commands. The most telling part is that when I tried to reproduce the defect a week later I couldn’t. I issued rt with a ton of 9s and just couldn’t get it to break. As it turns, it only crashes when you omit the space, which of course I didn’t think of doing. It took me more time to reproduce the defect than it took Brian to discover it.”

We’re offered the conclusion that we need legions of 8-year old testers, since their lack of preconceptions makes them great sources of unanticipated input. I strongly disagree.

For one thing, automated fuzz testing can be made much more genuinely random. But more importantly: 8-year-olds have better things to do than feed random data into programs that were developed using defective methods! It’s much more gratifying if kids are using solid software tools that enable creativity and learning. Even better is if their curiosity about the tool can be satisfied by reading its implementation!

This is not as unattainable as it sounds. I’ll go deeper into this example to make my case…by showing what caused this bug and how far ahead modern techniques are.

(more…)

Modern C++… or Modern Art?

Tuesday, March 31st, 2009

In the preface to his book Modern C++, Andrei Alexandrescu paints a vision of what programming should be like:

“Imagine the following scenario. You come from a design meeting with a couple of printed diagrams, scribbled with your annotations. Okay, the event type passed between these objects is not char anymore; it’s int. You change one line of code. The smart pointers to Widget are too slow; they should go unchecked. You change one line of code. The object factory needs to support the new Gadget class just added by another department. You change one line of code.

You have changed the design. Compile. Link. Done.”

This is a very nice theory. But as C++ programming has remained relevant only among a small (yet important) “fringe” of developers, they have been flexing the standards toward an uncompromising pursuit of this vision. The results are somewhat extreme and not generally easy to work with.

In this article I will talk briefly about the what is happening and what I think of the aesthetics.

(more…)


Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported