21.5.13

Running with pointers I

(This is the first in an occasional series of explorations of some of the stranger areas of C++ syntax.)

Consider the following code. What does it output? Will it run without crashing?
#include <stdio.h>

struct TypeA {
    TypeA() { printf("::TypeA() {}\n"); }
    ~TypeA() { printf("::~TypeA() {}\n"); }
};

struct TypeB {
    TypeB() { printf("::TypeB() {}\n"); }
    ~TypeB() { printf("::~TypeB() {}\n"); }
};

int main() {
    TypeA *a = new TypeA;
    TypeB *b = new TypeB;

    printf(" %p %p\n", a, b);

    delete a, b;
    delete (a, b); // I really want these deleted.

    return 0;
}
You may be relieved to learn that the program does actually release its resources correctly. But the two delete lines should probably be rewritten and the utterly misleading comment removed. Both a and b are deleted once each, although the appearance of the comma operator in the delete expressions introduces some confusion. In the first delete, delete a is evaluated first, then the expression as a whole evaluates to b. On the next line, the expression (a, b) is evaluated, and then the result of that (b) is deleted.
The output you'll see is something like the following (pointer values may settle in transit; dramatization, do not attempt, etc):
$ ./a.out
::TypeA() {}
::TypeB() {}
 0x10a2010 0x10a2030
::~TypeA() {}
::~TypeB() {}
Slightly alarming is that the code compiles without a peep using GCC's default settings (on Ubuntu 12.04.2):
$ g++ main.cpp
[ compiler says nothing... ]
Although we do get some (slightly cryptic) warnings when compiling with -Wall:
$ g++ main.cpp -Wall
main.cpp: In function ‘int main()’:
main.cpp:19:16: warning: right operand of comma operator has no effect [-Wunused-value]
main.cpp:20:16: warning: left operand of comma operator has no effect [-Wunused-value]
So, uh, -Wunused-value is your friend, I guess... (If you compile this on a different compiler/OS, let me know what results you get.)

No comments :

Post a Comment