C++ references

Assigning reference return value to a variable

When assigning a reference return value to a variable, a copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

References r("foo");
std::string n = r.getName();

This code makes a copy of the name member variable from the References class and puts the copy into the variable n.

Assigning reference return value to a reference variable

When assigning a reference return value to a reference variable, no copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

References r("foo");
const std::string& n = r.getName();

This code does not make a copy of the name member variable. Instead, the reference variable is now a reference directly to the member variable inside the class.

Passing a reference return value to a method that takes a reference

When you pass the return value from a method that returns a reference directly into a method that takes a reference, no copy is made. Here is an example:

class References {
private:
    std::string name;

public:
    References(const std::string& name) : name(name) {
    };

    virtual ~References() {
    };

    const std::string& getName() const {
        return name;
    };
};

void print(const std::string& s) {
    ...;
}

References r("foo");
print(r.getName());

This passes the reference returned directly into the method as a reference. Therefore, no copy is made.

Using a reference method in a comparison operator

This is the same as the method invocation example above because all operators take references.

Inferred typing

I know that .Net 4 is going to have some pretty cool features around dynamic typing and C++0x is also adding some auto typing features. I was thinking about all of this today and realized that what I really use most of the time is an inferred type. Essentially it would infer a new type based on the method’s contents.

Let’s say we have this:

public void callSomeMethod(Object obj) {
  obj.methodCall();
}

In static languages this fails because Object doesn’t contain the method methodCall. However, what if we told the compiler to create a new interface based on the content of the method? This code would then look like this:

public void callSomeMethod(autotype obj) {
  obj.methodCall();
}

The autotype keyword would cause the compiler to actually create this code:

public interface MethodCallInterface {
  void methodCall();
}

public void callSomeMethod(MethodCallInterface obj) {
  obj.methodCall();
}

This would now compile. Next, a caller to this method could pass in any object whose type the compiler could add this interface to. If you called it like this:

public class MyClass {
  public void methodCall() {
    System.out.println("Here I am");
  }
}

// Some other code somewhere
MyClass mc = new MyClass();
callSomeMethod(mc);

The compiler could take the interface it created for this method call and then see if the type passed in could implement that interface. If MyClass has already been compiled, it could do one of two things:

  • If MyClass is accesible as part of the current compilation unit, it could update the compiled Class to implement the interface
  • If it isn’t part of the current compilation unit and isn’t final, it could create a proxy for the call that implements the interface and delegates the call

Not sure yet how #2 really works or if it even makes sense to do it that way, but it seems to be the only way to make it work if the Class is in a JAR or DLL or something like that.

The only issue would be reflection. How could you reflection on the method and then pass an Object to it so that it would not completely blow chunks at runtime? Perhaps the reflective method invocation could determine if the object being passed could be proxied to the dynamic interface and then create a proxy on the fly.

Anyways, just pondering type systems in general today….

C++ sorting with the STL

Since I’m doing a lot of C++ these days and working a lot with the STL, I want to jot down some things I’ve had to painfully recall about sorting:

  1. The std::sort function really only works with vector
  2. If you want to sort a set of pointers, you’ll need to create a comparator function or object and use it as a type parameter (uglier than hell)
  3. If you want to sort a list, you MUST call the sort method on the list

#2 looks like this and really sucks to look at:

set<string*,StringPointerComparator> myset;

And if you want to pass that thing around, you have to either pass it like that (nasty) or typedef it. Since I hate all typedefs, macrodefs, etc, I generally pass that nasty full type around.

Getting the current system time in milliseconds with C++

After doing quite a bit of C++ recently, I thought I would post my method for getting the current system time in milliseconds in C++ for both Mac OS X and Windows. The Mac version might translate to other Unix platforms, but you’ll have to check the docs or man pages.

Mac OS X

#include <sys/time.h>
timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);

This actually returns a struct that has microsecond precision.

Windows

#include "windows.h"
SYSTEMTIME time;
GetSystemTime(&time);
WORD millis = (time.wSeconds * 1000) + time.wMilliseconds;

This code gives the milliseconds within the last minute. If you want milliseconds since epoch or some other fixed point in time it will require a bit more math on the SYSTEMTIME struct.

Writing a marker interface in C++

Just figured this out and it caused me about 3 hours of pain, so I figured I’d post it in case I need to do it again.

class Base {
public:
  virtual ~Base() {};
};

class Derived : public Base {
private:
  set someSet;
public:
  virtual ~Derived() {};
  set getSomeSet() { return someSet; };
};

You might find this necessary if you have some code like this:

class Base {
};

class Derived : public Base {
private:
  set someSet;
public:
  set getSomeSet() { return someSet; };
}

void main() {
  map objects;
  Base base;
  if (objects.find("foo") != objects.end()) {
    base = objects.find("foo")->second; // This is actually a Derived
  }
}

void useBase(Base& base) {
  Derived* derived = (Derived*) &base;
  set someSet = derived->getSomeSet();
  ...
}

This code will toss strange errors such as EXC_BAD_ACCESS and other kernel alarms. I’m not certain way this happens, but I think it is because Derived in the second example isn’t actually an instance of Base since the compiler doesn’t understand that Base is polymorphic. If you try to apply a dynamic_cast operator rather than the pointer cast (as used in example #2) the compiler will complain. What is probably happening is that at runtime the memory for the Derived is not correct because it was cast to a Base, and the kernel freaks out when you attempt to access something in Derived.

Another classic example of C++’s power causing major issues at runtime. These types of problems are not only tricky to figure out, but really only make sense to the kernel and compiler and aren’t obvious from a OO perspective.

Most modern OO languages would have absolutely no issues with the above code, and all dynamic OO languages wouldn’t even need the casts at all and would duck type the invocations via dynamic method invocation.

Visual Studio sucks, NetBeans is coming along, IJ is slipping

I’ve been working on a decent sized C++ project recently and since the application will be used on a Windows server, I wanted to stay close to that platform. I fired up the latest Visual Studio 2008 version hot off the presses with my MSDN subscription and boy is that thing a piece of junk. It is like working in the stone ages. I mean writing C++ is bad enough and then I have to battle with the worse IDE imaginable?

I think not.

So, I grabbed Eclipse and NetBeans and fired both up. Eclipse, is a beast and I wanted to avoid it at all costs if possible. I’ve never liked Eclipse, no matter the version, and they haven’t improved the issues enough for me to really use it for Java development. However, I found the Eclipse C++ integration decent, but still pretty rough. The Eclipse interface is so clunky that it makes it hard to be productive.

Next I grabbed the latest NetBeans (6.5) and fired it up. I have to say that it started pretty darn fast for a Java IDE. It also has a really decent layout and configuration system. The C++ support, although experimental for on the fly error highlighting, is impressive. After tweaking my colors and battling through keymappings I’m actually productive. NetBeans lacks a number of editor features that are required these days, including multiple clipboards, duplicate lines (has this but no keyboard shortcut), join lines, etc. Besides this problems, I like it.

On the flip side, IntelliJ is still great. 8.0 is just out and it adds a number of new great features and more language support. However, I think that IJ is probably getting close to needing a good chunk rewritten. The configuration system is becoming clunky, the projects difficult to manage, and most aspects of the IDE are beginning to fail.

The speed is horrible, the memory consumption off the charts and the productivity increases that we all used IntelliJ for are is slowly being integrated into the other IDEs. I think IJ is still the best, but their margin is slowing being reduced. If the folks over at JetBrains want to stay competitive they are gonna need more speed, more productivity, more simplicity and more power. These things are all hard to get at the same time, but I’m confident that they will find at way.

For now, I’m gonna give NetBeans the full shake-down, log a ton of bugs and wait for 7.0 to see how many they fix. I’d say my list is pretty short at this point and I could envision a full switch to NetBeans with 5-10 enhancements if IntelliJ continues its slow decline.

Only time will tell.

Setting up GoogleTest in VS 2008

I’m not a huge C++ developer nor a VS wizard, so I thought I would write down how I got GoogleTest setup in a C++ project I’m using VS 2008 for.

  1. Download it
  2. Add it as an existing project to your solution by right clicking on the “Solution ‘your-project'” part of the Solution Explorer
  3. Compile it (if you want)
  4. Right click your project and open the Properties
  5. Click on ‘Common Properties -> Frameworks and References’
  6. Add a Reference to the GoogleTest project
  7. Click on ‘Configuration Properties-> C++’
  8. Under the ‘Additional Include Directories’ add the a new directory that points to the include directory inside the GoogleTest distribution
  9. Click on ‘Configuration Properties -> C++ -> Code Generation’ and change all of the projects to ‘Multi-threaded Debug (/MTd)’

Another thing I realized is that it is probably best to create a separate project for the tests within your solution. I created a Win32 Console Application project in my solution and followed the above steps for that project. I also then needed to add a reference to the project I am testing within my test-project. (Slightly annoying, cumbersome and verbose).