What is wrong with this use of the new operator?

Is this allowed?

Object::Object()
{
    new (this) Object(0, NULL);
}
+3
source share
3 answers

Using new(this)will be reconstructed member variables. This can lead to undefined behavior, as they are not destroyed in the first place. The usual pattern is to use a helper function:

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) {
  /* ... */
}
+9
source

I believe that you need delegate constructors like Java, which are not there yet. When C ++ 0x arrives, you can do it like this:

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

}
+2
source

If it Objectis a POD , you can initialize it as follows:

class Object
{
  int x;
  int y;
  // ...
public:
  Object() { memset( this, 0, sizeof Object ); }
};
0
source

Source: https://habr.com/ru/post/1714184/


All Articles