Thursday, May 14, 2009
Friday, May 08, 2009
C++: new Foo vs. new Foo()
Hi folks. It's been a while since I last posted anything. My family and I moved from the valley to Seattle. We love it up here but we've been very busy.
Anyway, on to something somewhat interesting...
Question: In C++, what's the difference between the following
- new Foo;
- new Foo();
Give up (I almost did)? They're both valid and they both return a pointer to a newly constructed Foo on the heap. They only produce different results when Foo is a POD type. In a nutshell, a POD (Plain Ol' Data) type is a class/struct that only contains data members that are scalar types (int, unsigned char, float, bool, etc.) or other POD types. Basically, a POD object looks like an old C-style struct. For example:
(sorry about the lack of indentation—blogger ate it)
// POD
class Foo {
public:
int a;
};
// NOT a pod
class Bar {
public:
int a;
string name; // not a POD type
};
The difference between new Foo and new Foo() is that former will be uninitialized and the latter will be default initialized (to zero) when Foo is a POD type. So, when not using the form with the parens, the member "a" can contain garbage, but with the parens "a" will always be initialized to 0. Let's see:
$ cat pod.cc
#include
struct Foo {
int a;
};
int main() {
Foo* foo = new Foo;
foo->a = 7;
delete foo;
Foo* new_foo = new Foo;
printf("new_foo->a = %d\n", new_foo->a);
delete new_foo;
return 0;
}
$ g++ -o pod pod.cc
$ ./pod
new_foo->a = 7
But if we simply add empty parens to our new Foo, we'll get different behavior (again, this is only because Foo is a POD type).
$ cat pod.cc
#include
struct Foo {
int a;
};
int main() {
Foo* foo = new Foo();
foo->a = 7;
delete foo;
Foo* new_foo = new Foo();
printf("new_foo->a = %d\n", new_foo->a);
delete new_foo;
return 0;
}
$ g++ -o pod pod.cc
$ ./pod
new_foo->a = 0
And that's about it. The two forms are nearly identical. They behave the same except when used on a POD type, in which case the form with parens initializes the members to zero.
Perhaps not that useful, but somewhat interesting.
Posted by
Greg Miller
at
9:01 PM
0
comments
Labels: c++
Subscribe to:
Posts (Atom)

