[localhost:~]$ cat * > /dev/ragfield

Wednesday, March 18, 2009

Using stack based object constructors as function parameters

In C++, if the type of a function parameter is a bare class or a const reference to a class then it is not necessary to pre-create an object to pass into that function. You can use one of the class' constructors in place. For example:

class Graphics;
class Point;
...
void drawPoint(Graphics& g, const Point& p);
...
// The first argument is a non-const reference,
//   so the object must already exist
// The second argument is const reference,
//   so it can be created on the spot
drawPoint(g, Point(0, 0));

The constructor for the stack based object is called first, then the function is called, then the destructor for the stack based object is called last.

This is potentially very useful when combined with auto_ptr (or similar classes):

void foo(class Bar* b);
...
// A new "Bar" object is created, passed into
//   the foo() function, then destroyed
//   automatically after foo() is called.
foo(std::auto_ptr<Bar>(new Bar(...)));

No comments: