Calling a constructor class from a new GNU statement - use an invalid class

The closest topic to my question is here . I am trying to compile the following code with gcc:

#include <malloc.h>

class A
{
public:
  A(){};  
  ~A(){};
};//class A

int main()
{
  A* obj = (A*) malloc( sizeof(A) );
  if(obj==0) return 1 ;
  obj->A::A(); /*error: invalid use of 'class A' */
  obj->A::~A();
  free(obj);
  return 0;  
};//

From the command line, I compile the code with:

$ g ++ -o main main.cpp  
main.cpp: In function 'int main ()':  
main.cpp: 22: error: invalid use of 'class A'

Could you point me in the right direction?

+3
source share
4 answers

You cannot call the constructor for an object; a constructor can only be called when an object is created, so by definition, an object cannot yet exist.

new. malloc. void *, A; , A.

.

void* mem = malloc( sizeof(A) );

A* obj = new (mem) A();
obj->~A();

free(mem);
+6

.

void* ptr = malloc(sizeof(A));
A* obj = new(ptr) A;
+8

++ malloc . :

A* obj = new A();

new .

, , :

delete a;

delete .

+2

Since you are using C ++, a return to is mallocnot required. You can write it in terms of operatornew

int main() {
  if(A* obj = new (std::nothrow) A()) {
    delete obj;
    return 0;
  }
  return 1;
}

The minor version newreturns a null pointer if the distribution fails and throws an exception.

+2
source

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


All Articles