Tuesday, September 14, 2010

realloc()

realloc() provides all of the functionality of malloc() and free().

Reference: Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu. Addison-Wesley, 2001, p. 143.

Monday, September 13, 2010

Throwing Exceptions

The following statements compile:
        throw 99;
        throw "Hello";
You can throw any object that can be copied.

Sunday, September 12, 2010

Calling delete on a pointer to const

You can call delete on a pointer to const.

Reference: Modern C++ Design by Andrei Alexandrescu. Addison-Wesley, 2001, p. 182.

Saturday, September 11, 2010

Declaration in if Statement

The following code compiles.

if (int i = 1) {}

This is sometimes used to allocate a resource that is used within the scope of the if statement.

Reference: Modern C++ Design by Andrei Alexandrescu. Addison-Wesley, 2001, p. 238.

Here is some example code:
// File: decl_in_if.cpp
#include 
using namespace std;

int main() {
    if (int i = 0)
    {
        i = 11;
        cout << "Test 1 failed" << endl;
    }
    else
    {
        i = 23;
        cout << "Test 1 passed" << endl;
    }
    if (int j = 1)
    {
        j = 29;
        cout << "Test 2 passed" << endl;
    }
    else
    {
        j = 31;
        cout << "Test 2 failed" << endl;
    }
    return 0;
}
/* The above program prints out the following:
 *
 * Test 1 passed
 * Test 2 passed
 *
 */

Friday, September 10, 2010

Volatile

If you share a variable with multiple threads, you should specify that variable as volatile.

Reference: Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu. Addison-Wesley, 2001. p. 308.

Thursday, September 9, 2010

Repeated Enum Values

You can repeat values in an enum. For example:
enum RGB
{
   StartValue,
   Red       = StartValue,
   Green     , 
   StopValue ,
   Blue      = StopValue,
   RgbCount
};

Wednesday, September 8, 2010

const_cast<>() and the volatile type qualifier

You can use const_cast<>() to remove the volatile qualifier.

Reference: The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis. Addison-Wesley, 1999, p. 20.

I tried this on a couple of compilers.

It worked on the IBM AIX compiler, but it did not work on the Sun compiler.

It only worked for references, pointers and pointers to data members.

See also: volatile - Multithreaded Programmer's Best Friend by Andrei Alexandrescu.