tags:

views:

268

answers:

3

Is this allowed?

Object::Object()
{
    new (this) Object(0, NULL);
}
+9  A: 

Using new(this) will re-construct member variables. This can result in undefined behavior, since they're not destructed first. The usual pattern is to use a helper function instead:

class Object {
private:
  void init(int, char *);
public:
  Object();
  Object(int, char *);
};

Object::Object() {
  init(0, NULL);
}

Object::Object(int x, char *y) {
  init(x, y);
}

void Object::init(int x, char *y) {
  /* ... */
}
bdonlan
So, is using placement new on `this`, in and of itself, undefined behavior, or is it only *potentially* undefined behavior depending on what members the class has? If the class only has POD-type members, would it be safe to do that?
Rob Kennedy
Assuming there are the other pitfalls (virtual functions etc) are avoided too, potential. The behavior of ctors and dtors is quite well specified. If all members are PODs, neither the initial ctor nor the placement new will do anything.
MSalters
+2  A: 

I believe you want delegate constructors, like Java for example, which are not here yet. When C++0x comes you could do it like this :

Object::Object() : Object(0, NULL)
{

}
AraK
Did you mean C++0x? Despite not being ready until 201x, its name remains C++0x. If you really meant C++1x, then this is an especially unhelpful answer.
Rob Kennedy
I used to call it C++0x but it isn't anymore :(
AraK
Yes it is. x is a hex digit
Martin York
Oh! I'll edit my answer thanks Martin ;)
AraK
The syntax is wrong anyway - C++0x constructor delegation would be Object::Object() : Object(0, NULL) { }
bdonlan
@bdonlan Sorry, I corrected it.
AraK
@AraK There should not be a semicolon in that syntax. The correct syntax should look very much like member variable initialization.
Shmoopty
I feel stupid! This is maybe the fifth mistake. Thanks!
AraK
A: 

If Object is a POD type you could initialize it in this way:

class Object
{
  int x;
  int y;
  // ...
public:
  Object() { memset( this, 0, sizeof Object ); }
};
Kirill V. Lyadvinsky
We haven't seen the implementation of the two-argument constructor, so we don't know whether all-bits-zero is really the desired representation. In particular, we don't know whether the null pointer on this system is all-bits-zero.
Rob Kennedy
this seems a bit dodgy... then one day somebody comes along and decides to inherit from Object
Anders K.
Something like `boost::noninheritable` could be used to make sure that noone will inherit from `Object`.
Kirill V. Lyadvinsky