There is a structure:

struct A{ char * buf; A(int size){ buf = new char[size]; } }; 

I want to create an array of objects A with the specified size.

 A * a = new A[10](10); // 10 объектов, должны конструироваться через A(int size) 

but it does not work.

    4 answers 4

    If there is not a very fundamental need to rely on raw new , then you can use std::vector and one of its constructors:

     std::vector<A> v(10, A(10)); 

    True in this case, the object is created by the specified constructor once, and then copying is already done. That is, you need to write a suitable copying constructor.

      I strongly suspect that UB, but you can try something like this: https://ideone.com/PlWjPh

       struct A { char *buf; A(int size) : buf(new char[size]) {} ~A() { delete [] buf; } }; template <typename T, int val> struct with_arg : T { with_arg() : T(val) {} }; int main() { A *a = new with_arg <A, 10> [10]; delete [] a; return 0; } 

      Discussion of the presence of UB in this code:

      • Of course UB! At a minimum, the destructor must be virtual. - αλεχολυτ
      • @alexolut, there is potentially 2 UB - destructor and wrong array type. But the heir class adds nothing, so it may turn out to be normal. - Qwertiy
      • about the wrong type of array did not understand. And for UB it doesn't matter if there is something new added to it or not, if the objects of the derived class are deleted via a pointer to the base class, then without a virtual destructor in the base class there will be UB. - αλεχολυτ
       #include <new> int main() { struct A{ ~A() { delete [] buf; buf = nullptr; } A( int size ) { buf = new char[ size ]; } char * buf; }; //выделяем A* ptr = (A*)(::operator new[](sizeof(A) * 10)); for(auto i=0; i<10; ++i) { new(ptr + i) A(10); } //освобождаем for(auto i=0; i<10; ++i) (ptr + i)->~A(); ::operator delete[](ptr, sizeof(A)*10); return 0; } 
      • This is a perversion ... - VTT
      • no exception handling. - Abyx
      • Well this is not a reference code of some kind ... just showed the author what he wants - xperious
       //еще вариант int main() { //___ A* aptr = static_cast<A*>(operator new [](sizeof(A) * 10)); //___ } //и еще template <size_t i> struct A{ char * buf; A(){ buf = new char[i + 1]; } }; int main() { A* p = new A<10>[10]; p[0].buf[0] = 't'; //_ _ _ }