0

This code passes in VS2010, but give run time error as Segmentation fault with g++ compiler.

I know we should not use delete for an object which is instantiated by placement new.

Please explain how it is working in VS2010.

If I use delete xp or xp->~X() (can delete one object only), the program runs successfully on both platforms.

Please provide a solution to delete an array of objects.

class X {
 int i;
 public:
  X()
  {
   cout << "this = " << this << endl;
  }
  ~X()
  {
   cout << "X::~X(): " << this << endl;
  }
  void* operator new(size_t, void* loc)
  {
   return loc;
  }
};
int main()
{
 int *l =  new int[10];
 cout << "l = " << l << endl;
 X* xp = new (l) X[2]; // X at location l
 delete[] xp;// passes in VS2010, but gives segmenatation fault with g++
}
JAL
  • 41,701
  • 23
  • 172
  • 300
Santhosh Kumar
  • 167
  • 2
  • 12

1 Answers1

0

You should call destructor for all X objects manually and then delete the original buffer

int main() {
    int *l =  new int[10]; // allocate buffer
    X* xp = new (l) X[2]; // placement new
    for (size_t idx = 0; idx < 2; ++idx) {
        xp[idx]->~X(); // call destructors
    }
    delete[] l; // deallocate buffer
}
  • yeah thanx.. but one more problem. assume xp is member of `class Y.`` xp = new X[n]` where `n` value is dynamic. i instantiated xp in function of `Class Y`. in the destructor of `Classy Y` i have to delete xp. how can i do it? – Santhosh Kumar Feb 15 '16 at 08:10
  • You want to store underlying buffer outside `class Y`? Why? You may store n and delete xp by calling destructors of the first n objects. It won't deallocate the underlying buffer. I may recommend you to look at [std::aligned_storage](http://en.cppreference.com/w/cpp/types/aligned_storage) which is a simple example of using placement new. – Sergey Krivohatskiy Feb 15 '16 at 09:58
  • what do you mean underlying buffer in this context? i got the answer that i have to keep a private member of `class Y` to store the value of n, so that i can call destructor of X using index. We have use `xp[idx].~X()` – Santhosh Kumar Feb 15 '16 at 16:04
  • By underlying buffer I meant `l` from your example – Sergey Krivohatskiy Feb 15 '16 at 19:52