Archive for the ‘C++’ Category

Iostreams Re-Examined

Sunday, April 7th, 2013

One area in C++ I had never really spent a lot of time with until early last year is the iostreams library. I *thought* I understood it pretty well. At a superficial level, it made perfect sense: replace printf/scanf with an abstract interface for serialization that objects could implement for themselves.

As a developer whose post-stdio-era coding usually targeted things like graph databases instead of text files, I didn’t have all that many occasions to use iostreams. But as I became more involved in exchanging small conceptual programs with other developers, I realized that they are the “lingua franca” of standard C++. Using them began to teach me that there were many things about them I didn’t know…and that they could be very useful, as well as very tricky.

For instance, do you know the difference between these two lines?

std::cout << std::endl;
std::cout << ‘\n’;

I didn’t! That’s just for starters, so I gave a presentation on the topic to my Austin C/C++ Group in October 2011. In it, I represent some of my new understandings:

Slideshow iconView the presentation

At first, I delayed on publishing it to the Web for fear that it may not be 100% right. But then it languished in a private Google Docs presentation for a year and a half. I found it today, and if I’m worried about its inaccuracy it’s sure not going to get any better by leaving it there. And it might help someone, as I know there are a large number of people on the Internet who are even more less than 100% right. :-P

So here it is, and corrections are of course welcome–just leave a comment!

(Note: Learning the details about this would not have happened without the help of the active C++ community on SO. That’s where I spent most of my recreational programming time—instead of writing blog entries—in 2011. Both asking and answering questions offers insights. While some people seem to have a bit of what amounts to an “online game addiction”, it’s a case where their affliction can benefit you and the common good. :P)

The Essential Noisy Debug Hook for Qt

Tuesday, October 2nd, 2012

If you’re using Qt, you might find that it can often be rather quiet about important and common programming errors. For instance: by default, it considers the inability to connect a signal and a slot—due perhaps to a typographic error—to be a warning worth only quietly pushing into your debug output window. It’s easy to miss, especially if you (or libraries you call) have a lot of monitoring information turned on!

I’m the sort who immediately bumps up every warning level in the compiler to turn them into errors. In a similar vein, I’ve found it useful to throw the following code into the main.cpp of any Qt GUI app I am writing. (Thanks to commenter kkoehne for feedback!)

#ifdef QT_DEBUG
 
#include <QMessageBox>
#include <QThread>
#include <iostream>
 
// By default, fairly big problems like QObject::connect not working due to not being able
// to find a signal or slot goes to the debug output.  There can be a lot of spew which
// makes that easy to miss.  While perhaps the release build would want to try and
// keep going, it helps debugging to get told this ASAP.
//
// Would be nice to chain to the default Qt platform error handler
// However, this is not feasible as there is no "default error handler" function
// The default error handling is merely what runs in qt_message_output
// 	http://qt.gitorious.org/qt/qt/blobs/4.5/src/corelib/global/qglobal.cpp#line2004
//
void noisyFailureMsgHandler(QtMsgType type, const char * msgAsCstring) {
    QString msg (msgAsCstring);
    std::cerr << msgAsCstring;
    std::cerr.flush();
 
    // Why on earth didn't Qt want to make failed signal/slot connections qWarning?
    if ((type == QtDebugMsg)
            && msg.contains("::connect")) {
        type = QtWarningMsg;
    }
 
    // this is another one that doesn't make sense as just a debug message.  pretty serious
    // sign of a problem
    // http://www.developer.nokia.com/Community/Wiki/QPainter::begin:Paint_device_returned_engine_%3D%3D_0_(Known_Issue)
    if ((type == QtDebugMsg)
            && msg.contains("QPainter::begin")
            && msg.contains("Paint device returned engine")) {
        type = QtWarningMsg;
    }
 
    // This qWarning about "Cowardly refusing to send clipboard message to hung application..."
    // is something that can easily happen if you are debugging and the application is paused.
    // As it is so common, not worth popping up a dialog.
    if ((type == QtWarningMsg)
            && QString(msg).contains("QClipboard::event")
            && QString(msg).contains("Cowardly refusing")) {
        type = QtDebugMsg;
    }
 
    // only the GUI thread should display message boxes.  If you are
    // writing a multithreaded application and the error happens on
    // a non-GUI thread, you'll have to queue the message to the GUI
    QCoreApplication * instance = QCoreApplication::instance();
    const bool isGuiThread = 
        instance && (QThread::currentThread() == instance->thread());
 
    if (isGuiThread) {
        QMessageBox messageBox;
        switch (type) {
        case QtDebugMsg:
            return;
        case QtWarningMsg:
            messageBox.setIcon(QMessageBox::Warning);
            messageBox.setInformativeText(msg);
            messageBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
            break;
        case QtCriticalMsg:
            messageBox.setIcon(QMessageBox::Critical);
            messageBox.setInformativeText(msg);
            messageBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
            break;
        case QtFatalMsg:
            messageBox.setIcon(QMessageBox::Critical);
            messageBox.setInformativeText(msg);
            messageBox.setStandardButtons(QMessageBox::Cancel);
            break;
        }
 
        int ret = messageBox.exec();
        if (ret == QMessageBox::Cancel)
            abort();
    } else {
        if (type != QtDebugMsg)
            abort(); // be NOISY unless overridden!        
    }
}
#endif

Then in the main() function, after the QApplication is initialized…I’ll say:

#ifdef QT_DEBUG
    // Because our "noisy" message handler uses the GUI subsystem for message
    // boxes, we can't install it until after the QApplication is constructed.  But it
    // is good to be the very next thing to run, to start catching warnings ASAP.
    {
        QtMsgHandler oldMsgHandler (qInstallMsgHandler(noisyFailureMsgHandler));
        Q_UNUSED(oldMsgHandler); // squash "didn't use" compiler warning
    }
#endif

By re-prioritizing the default error levels to something more reasonable and being “noisier” when a serious problem is happening during debugging, it has been a huge time saver. Try it and let me know what you think!

Bjarne Stroustrup on the Uniqueness of unique_ptr

Sunday, September 30th, 2012

I helped organize a talk from Dr. Bjarne Stroustrup in Austin on September 19, 2012. It was a presentation he’s apparently given in some form or another elsewhere, but I had not seen the slides before.

Much of it wasn’t new material for me. I am already familiar with the tenets of “Modern C++”, but he introduced them lucidly for people unfamiliar with concepts like shared_pointer or unique_ptr. I’d also seen his article about type-safety in SI units from IEEE Spectrum.

(Note: What did surprise me was a graph of an experiment he did with the performance of vector vs. list. It also challenged many people’s assumptions about at what size a list would crossover to being faster. The task would seem to benefit substantially from being able to do arbitrary insertions quickly. But it looks like the three most important things in performance are starting to mirror the three most important things in real-estate: Locality, Locality, Locality! :-P)

We didn’t record the talk. It would have been some effort to arrange with the venue, and he told us in advance it would be similar to talks he’s given elsewhere that were online. Yet I should have had the prescience to record the Q&A!

In any case, I did manage to ask him about an issue that had been on my mind for a while:

Do you personally feel that it’s good practice to use unique_ptr as a way of following the “hot potato” of deletion responsibility on an object, while extracting the raw pointer and passing it into other code? Or should unique_ptr live up to its name and always be truly “unique”…the only handle to the pointed-to-object in the system?

In the past, I’ve not really been able to get a consistent view from people on this. So I figured there wasn’t a much better person to ask for an authoritative answer!

He had more moments of pause in answering this than the other questions. He prefaced by saying that he didn’t really think there was enough experience with the issue to really establish what “good” and “bad” practice was going to be in the matter. But he said he could offer his “current opinion”.

That opinion was that it was fine IF the holder of the unique_ptr could guarantee that all of the routines that were passed the extracted pointers were finished before the unique_ptr was moved to be under the control of someone else.

So that’s “from the horse’s mouth” as of September 19, 2012. Off the top of my head, I do remember a couple of other questions…

(more…)

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);
}

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