Archive for category Programming

Smart Pointers in C++

There are a number of “smart pointer” implementations in C++. Each one has a different set of features and it seems hard to pick one that satisfies scenarios.

auto_ptr: Available as part of the standard C++ library (#include ). Has the several useful features and shortcomings:

  1. Pointer initializes itself to 0 if not explicitly initialized
  2. Pointer automatically deletes itself when it goes out of scope
  3. Only one auto_ptr can point to an object at a given time (so no question of reference counting). If you do x=y auto_ptr x will now point to what was pointed to by y. But y will now point to NULL!!
  4. Does not work for arrays because it deletes its pointer with delete and not delete []
  5. Does not work with STL. Warning: May appear to work but reportedly results in subtle devastating bugs
  6. It is not thread safe

Feature 3 limits its usefulness IMHO. This article – Using auto_ptr Effectively – summarizes auto_ptr features.

shared_ptr: This pointer from  the BOOST C++ library uses reference counting. So a shared_ptr that is assigned to another will point at the same object in memory and will increment a reference count to that object. When either of the pointers is deleted the object reference count is decremented. If the object reference count is zero the object is truely deleted from memory.

  1. Reference counted
  2. Does NOT do copy on write. If shared_ptr x is assigned to y and later *x (or *y) is changed then the memory location pointed to is changed (just like a regular pointer)
  3. Cycling references may lead to memory leaks – this is a problem with reference counting itself and not this specific implementation
  4. Thread safety – some operations seem atomic. See BOOST docs.
  5. Cannot hold a pointer to an array (see shared_array)
  6. Pointer automatically deletes itself (or reduces reference count) when it goes out of scope

This may be already added to C++ standard library in the near future (already in?).

Const in C++

Const declaration:

const int* x; //constant data (*x); non-constant pointer
int const *x; //same as above
int * const x; //constant pointer; non-constant data
const int * const x; //const data; const pointer

Const member functions:
Function values can be declared const. Helps specifically in operator overloading.

const Foo operator*(const Foo& lhs, const Foo& rhs);

Foo a,b,c; 

a = b*c; //legal
(a*b) = c; //This will work if return value is not const

It is not useful to assign any value to the product of two variables but it can happen accidentally. Example, using = instead of ==

if(a*b = c) {
}

Const member functions in a class cannot modify the contents of the class. They make it possible to work with const objects. Member functions differing only in their “constness” can be overloaded.

class Foo {
public:
    const int& value() const;
       int& value();

private:
    int x;
};

main() {
    Foo x(1);
    cout<<x.value(); //Non-const function is called

    const Foo y(2);
    cout<<y.value(); //const function is called
}

Bitwise Constness:
C++ gives only bitwise constness. This means const member functions cannot modify pointers in a class. But they can modify the data the pointer points to.

Mutable:
Mutable type modifier allows variables to be modified even by const functions.

Class Foo {
public:
    void test() const; //can modify x but nor y
private:
    mutable int x;
    int y;
};

Tags: , ,

Misc C++ links

C++ file I/O quick notes.

Gcc and uninitialized variables

Gcc will not produce any warnings about uninitialized variables if the optimization level is not 1 or greater. The following code has an obvious uninitialized variable problem.

test.c

int foo() {
    int x;
    return x;
}

But gcc (3.4 and 4.2.1) produces no warning or error when you use this command line:

gcc -Wall -Werror -O0 test.c
gcc -Wall -Werror  test.c (this defaults to -O0)

I have tested the above on Linux as well as Mac OS X.
The -Wall flag is supposed to automatically include the -Wuninitialized flag. But if the optimization level is 0 then the check for uinitialized variables is not done.

gcc -Wall -Werror -Wuninitialized test.c

If included explicitly like above:

$ gcc -Wall -Werror -Wuninitialized test.c
cc1: warnings being treated as errors
cc1: warning: -Wuninitialized is not supported without -O

For gcc to check for uninitialized variables you need to throw at least -O1 optimization.

From the gcc man page:

-Wuninitialized
Warn if an automatic variable is used without first being
initialized or if a variable may be clobbered by a “setjmp” call.

These warnings are possible only in optimizing compilation, because
they require data flow information that is computed only when
optimizing. If you do not specify -O, you will not get these
warnings. Instead, GCC will issue a warning about -Wuninitialized
requiring -O.

However, uninitialized checking does not seem to work correctly. This code compiles on Mac OS X (Snow Leopard):

#include <stdlib.h>
#include <iostream>

int main() {

    int l_retVal;
    unsigned int x = 1;
    unsigned int y = random() % 10;
    if(y == x) {
        l_retVal = 2;
        std::cout<<"HERE \n";
    }
    return l_retVal;
}

$ g++ -Wall -Werror -Wuninitialized -O test.cpp
$

CPU, Graphics, Stream computing, and OpenCL

  • NVIDIA GPU Gems1 book online
  • NVIDIA GPU Gems2 book (discusses GPU architecture) online

OpenCL Links

Command line parsing in C++ – Tclap

TCLAP library

Precision in games

Why not to use double precision to represent objects in 3D – TomF’s Tech Blog

How debuggers work

Interesting post on how debuggers work.

Other interesting articles:

  1. Abusing mach on Mac OS X: Discusses how to replace some ptrace functionality using Mach functions
  2. mach_star and mach_inject (still being developed?): Opensource code to dynamically load your code into a running process. Port for Intel machines. Also see this link.

Game Physics

Ok not quite game physics but a very good article on modeling collisions in a game. The author talks about modeling both “hard” collision – like a billiards ball hitting another – and soft collisions (sumo wrestlers).

Article at MacResearch: The Physics of Sumos (A Flirtation with iPhone Game Development)

How to pick an open source license

A list of articles comparing licenses

  1. From ZDNet blogs: Part 1 and Part 2
  2. Milking The GNU: Picking an open source license w/o becoming brain dead
  3. Choosing an Open Source License
  4. An impassioned plea to pick a license.
  5. And finally the WTFPL.