Archive for the ‘C++’ Category

StackOverflow Summaries and Opinions 2011

Wednesday, January 18th, 2012

I’ve not been posting on this WordPress blog very often this past year. That’s despite actually doing more programming-related explorations than I had in a long time. One of the key reasons is because I found more “instant gratification” (and sometimes “instant frustration”) by participating in the online question-and-answer site StackOverflow.

Like Wikipedia, StackOverflow is a collaboratively-edited body of knowledge. Also like Wikipedia, it is curated by (mostly) volunteers who’ve agreed to use the “Creative Commons Attribution-Share Alike 2.5 Generic License” a.k.a. CC-Wiki. But unlike Wikipedia, S.O. is a closed-source system written using proprietary server-side Microsoft technologies. The people running it are a for-profit business, with paid advertisers and venture capital investors. Their profitability enables them to keep $100 bills in jars of their company snack room:

the StackOverflow snack jars

I don’t begrudge them their success. But while the site can be snapshotted and mirrored, it’s certainly not free of lock-in for tracking question history and other integral site features. Due to the aesthetics of the programmer-types running it, quality and improvements have moved ahead quickly…so far. I will remind everyone that seemingly trustworthy and upstanding programmers have sold out sites hosting my content in the past for something “as petty as money”. (Remember LiveJournal when Brad Fitzpatrick ran it, vs. when it was sold and covered with full-pop-up-video advertisements, feature stagnation, and possible KGB oppression by its new Russian owners?)

So I remain a little skeptical. But I did learn a lot by participating, which for me meant reading a lot then answering many more questions than I asked. I’ve been at times awed by the extremely detailed knowledge some people have…and how quickly one can get a thorough and elegant answer. At other times I’ve been amazed at what jerks some of those same incredibly knowledgeable people can be, for no apparent reason. (It’s less surprising when people whose knowledge does not impress me are jerks…that’s status quo for the Internet!)

Because I’ve recently taken on the organizer role of the Austin C/C++ Meetup, I’ve been introducing myself and sharing links to this creaky old WordPress site. So it seems good to share a few of the high-and-low points of what has been my substitute for a programming blog in the latter half of 2011. Sometimes funny, sometimes enlightening, sometimes lame—and sometimes all three! Read on…

(more…)

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…)


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