Working with C++0x/C++11: nullptr and nullptr_t

One my pet peeves with C/C++ are null pointers – specifically not having a good way of specifying a special pointer value that means “invalid pointer”. C (and C++) have a preprocessor macro NULL, which in C expands to either (void*)0 or 0. C++ is different has NULL defined to 0. Zero is a fine representation of an invalid pointer value, but it has nothing inherently invalid it, it can still be used as an address. What nullptr as a keyword brings to the table is the ability to unambiguously inform the compiler and the running code that this pointer isn’t valid.

But another interesting thing is that nullptr is a keyword, and not a type. It’s a what, a keyword? If this doesn’t seem like a great thing, look at it this way; If you have a bool, and want to check its value it will be either true of false. true and false are keywords. And now we have a keyword for “invalid pointer”. Get it now? If a pointer value is nullptr it’s null and pointing at something invalid. It’s also strongly typed so that will aid in disambiguating from non-null pointers in addition to other types. What’s nullptr’s type? It’s of type nullptr_t. Looking back to our bool example, the keywords “true” and “false” are of type bool, and the keyword “nullptr” is of type nullptr_t. This also allows you to use it (for example) in a function definition to catch those instances when a nullptr instead of something else a pointer could be converted to is passed in.

So if you have various function prototypes…

void Foo(long a) { cout << "Foo(long)" << endl; }
void Foo(int a) { cout << "Foo(int)" << endl; }
void Foo(char *a) { cout << "Foo(char*)" << endl; }
void Foo(void* a) { cout << "Foo(void*)" << endl; }
void Foo(nullptr_t a) { cout << "Foo(nullptr_t)" << endl; }

Foo((void*)0); // Foo(void*)
Foo(0); // Foo(int)
Foo(5.5f); // Foo(float) if it’s defined else Foo(int)
//    but usually you’ll get a conversion warning
Foo(NULL); // Foo(int) or Foo(long) on some machines – depends on how NULL is defined
Foo(nullptr); // Foo(nullptr_t) if it’s defined, else Foo(char*)

In some instances you’ll get a compiler warning about an ambiguous overloaded call. nullptr isn’t yet in all C++ compilers, but it will be soon. nullptr’s are a great addition to C++ that made pointer handling much easier.

Posted in C++0X/C++11, Code | Leave a comment

Working with C++0x/C++11: static_assert and decltype

I have been writing a lot of code the last few months, and I’ve had a chance to play with some of the new C++0x features. It’s really the first time in many years that there’s been a significant improvement to the language. I thought I’d take a few blog entries and work through some of the new features, because unless you’ve already had experience with some of them in other languages you might not fully understand the power that is behind some of the features.

The first one I’m going to talk about is called static assertions. I assume you are familiar with the assert macro in debug mode. There’s also the #error preprocessor command. Static assertions on the other hand are compile time tests. They give you the ability to essentially make compile time assertions in your code. One nice feature is that it works with templated expressions as well. If the conditional can be evaluated at compile time then the compiler will immediately evaluate the conditional For a template assertion, the test is performed when a template is instantiated, just like the assert macro, if the condition evaluates to true, nothing is done. If however the condition is false then the compiler will raise an error and post the error message that is part of the static assert. For example;

static_assert ( 1+1 == 3 , "one plus one does not equal three");

For example, you might have code compiles for both 32-bit and 64-bit and you might need to make assertions;

static_assert(8 == sizeof(void*),  "Not valid for 32-bit code");
static_assert(4 == sizeof(void*),  "64-bit code generation has not been tested");

Or, as I recently have been doing, you’re writing out binary files that have to run on a variety of operating systems and architectures, and you don’t want any nasty surprises when you start running on different systems.

static_assert(4 == sizeof(int) ,   "ints aren’t 32 bits in size");

A recent post in AltDevBlogADay by Michael Tedder <Trivial Constructors and Destructors in C++> talked about creating POD data (Plain old data – i.e. data that has no virtual function tables, exceptions, etc. that is, data that is just that – data and no dangling functionality hanging off it) If you are creating an allocator for POD objects, it’s possible to check for this at compile time.


#include <type_traits> 

template <class TYPE >
class Allocator{
    static_assert(std::is_pod>TYPE&rt;::value, "Template argument must be a POD");
};

class pod
{
};

class not_pod
{
virtual ~not_pod(){} ; //  the offending non-POD part
};
...
Allocator<int>  v1; // works
Allocator<pod> v2; // works
Allocator<not_pod>  v3; // static asserts
...

It just takes some creativity to figure out how to assert that what you want, and then it’s in your code forever, tested every time you compile. As you can see, I am a firm believer in letting computers do as much of the work as possible. In this case, it’s possible to let the compiler check my assertions for me. With the rapidly changing pace of both target architecture and operating system that we have today in the games industry an ounce of prevention is worth a whole lot more than a pound of cure.

Posted in C++0X/C++11, Code | Leave a comment

Otto Berkes – the last Xbox founder – leaves Microsoft

Way back when I was writing my OpenGL Book, I had the good fortune to run across some stupendous folks at Microsoft who were forthright and open and very very helpful to me, answering questions, implementation details, and generally reviewing a lot of my work. One of these guys was Otto Berkes. Later the API wars would put him and most of the other OpenGL team onto the DirectX team (which is one reason it suddenly jumped in quality between releases),  and eventually he went on with Seamus Blackley, Kevin Bachus, and Ted Hase to be the core Xbox team. He’s the last one to leave Microsoft, and I wish him all the best.

Posted in DirectX, Ex-Microsoft, OpenGL, PC Graphics | Leave a comment

Blog – take 2

So, a few months after updating my website to be more of a blog format ( since that’s what it was anyway), I managed to enter setting in WordPress confuse it utterly and leave it unusable. Much to my surprise, my web provider does not backup content, just e-mail, at my subscription level. Fortunately, I was able to recover most of the content, and I finally sat down, re-created my blog format in WordPress, and am re-posting all of the content from before the unfortunate event. What a pain in the ass. I hope you guys enjoy it!

Posted in Miscellaneous | Leave a comment

Double Your Program Speed with One Easy Change

My friend Stan Melax has written a number of articles on optimization using SSE instructions. He’s also talked about some simple things you can do to make your program run faster. I’d like to reiterate one of these because it’s just so simple to do and it’s such a big payoff. It turns out that the Microsoft C++ compiler falls back to using x87 instructions unless you tell it differently. What you want is to enable SSE instructions in your code. You might be wondering how this will limit your program. Both Intel and AMD’s processors have supported SSE3 instruction since 2004/2005 respectively. So as long as you are targeting a PC made in the last six years there should be no problem in enabling SSE3.

The problem is that the default setting-enable x87 instructions-hearkens back to the day of math coprocessors. In other words, back when a math coprocessor was a separate chip that you could install on your motherboard. The coprocessor was integrated back in the ’486 days, so this bit of legacy isn’t really necessary anymore. You want to make two changes to the default settings to make your calculations faster.

If you doubt this is important the just look at the flak Nvidia caught for its PhysX software implementation. An investigation by David Kanter at Real World Technologies found that Nvidia’s PhysX software implementation for use by CPUs still uses x87 code (plus David says the software implementation seems to only use one thread on multithreaded systems, whereas the hardware version is multithreaded).

Go to the properties dialog. Select C++, then Code Generation. You want to make two changes; set Enable Enhanced Instruction Set, and select Enable Streaming SIMD 2 Extensions. This will enable the SSE instructions. Next you want to select Floating-Point Model, and set it to Fast. This tells the compiler that you want to use 32-bit floats, not doubles;
Here’s a graphic of what it looks like;

Your mileage may vary, but if you do any amount of math in your program this simple modification will greatly speed up your program. If you are wondering about older machines and SSE compatibility, I don’t actually know what will happen if you run this on a PC that doesn’t have the required SSE capabilities – I assume it’ll seg fault and blue screen. While checking CPU capabilities is too big a topic to cover here (perhaps in another post), you can look up the CPUID instruction if you want to puzzle it out. For me, I’d assume that if it’s running WinXP or better, then the SSE instructions will be OK.

I’ll post a link to Stan’s article when it’s up.

 

Posted in C++0X/C++11, Code | Leave a comment

Microsoft Developer Network Article on Threading – Part 2 – Scalable Multithreaded Programming with Tasks

The second of my series of articles on threading is up on Microsoft Systems Developer Network Magazine:

Scalable Multithreaded Programming with Tasks

This article is about using tasks to break up a lengthy job into a series of smaller ones – called “tasks” – which can be individually run on a thread. Of course, there are some restrictions on how you can do this and not have the threads step on each other. In some cases it’s impossible to take a serial task and create collection of independent (or nearly so) smaller tasks. But frequently you can have a task make an assumption out the global state and if you’re right most of the time, it’s a win at the expense of occasionally repeating or redoing some work because your tasks didn’t have the exactly correct information.

Posted in Code, Published Articles | Leave a comment

Microsoft Developer Network Article on Threading – Part 1 – Scalable Multithreaded Programming with Thread Pools

The first of a series of articles on threading is up on Microsoft Systems Developer Network Magazine:

Scalable Multithreaded Programming with Thread Pools

This article is a gentle introduction on how to get better CPU performance with little effort.  If your application is fairly CPU intensive, it’s usually fairly easy to make it multiprocessor friendly by using a little preprocessor magic to instruct the compiler that an operation can be run on multiple threads. Discusses C# and C++ multithreaded programming.

Posted in Code, Published Articles | Leave a comment

Kevin Bachus joins Bebo

Social networking site Bebo (Blog Early, Blog Often.) has hired Kevin Bachus as their “Chief Product Officer”.  Bebo is similar (but smaller) than other social networking sites, like Facebook and MySpace.

The most interesting thing about Bebo is that it was acquired by AOL on March 13, 2008 for $850 million.  In June, 2010 AOL announced it was planning to sell  Bebo to Criterion Capital Partners for (less than an eventually revealed)  10M$US.  AOL’s sale was supposedly due to the falling numbers of unique users. Bebo users were moving to the social giants Facebook and Twitter, and AOL said that Bebo couldn’t compete with other Social Networking sites at its current state. “They couldn’t commit to taking on the massive task to keep Bebo in the social network ‘race’ “.

Update May, 2011 – Bebo creator Michael Birch, said of Bebo (after he made about $600 million from selling Bebo to AOL) “I think the main reason it didn’t work was just that Facebook was beating it, and people would leave Bebo to join Facebook,”. What’s Birch up to now? – “little social network. I wouldn’t say it’s a competitor to Facebook,” he quickly added. “I don’t think it makes sense to try and be what they are. I do think it makes sense to be what they’re not.”

Posted in Ex-Microsoft | Leave a comment