New and malloc behavior in C and C ++

In C it is considered bad form to give the result of a call malloc

. However, it seems that the result of the call malloc

in C ++ to be a typecast, although both malloc

and new

have the return type void*

, and the challenges new

are not typecast. Is there a reason why, in C ++, the void pointer returned new

is automatically promoted until the void pointer returned malloc

is not?

+3


source to share


2 answers


You are confusing operator new

with the operator new

. operator new

just allocates raw memory and returns void*

, whereas it new T

also calls the constructor after allocation and returns T*

.



Also, you must specify the result malloc

in C ++, because unlike C, C ++ does not allow implicit conversions from void*

to other pointer types. Note that it is void*

used very rarely in C ++.

+14


source


In C ++, memory locations are indeed expressed through void pointers. But memory is not the same as objects. An object needs memory in order to live, but an object is different from the memory in which it resides.

You need to create an object in memory. If you do this, the new

-operator "converts" between memory and objects:



#include <cstdlib>

void * pm = std::malloc(sizeof(int));       // C-style
void * qm = ::operator new(sizeof(int));    // C++-style

int * po = ::new (pm) int(10);              // void pointer goes in...
int * qo = ::new (qm) int(20);              // ...object pointer comes out.

// (... class-type objects would need to be destroyed...)

std::free(pm);
::operator delete(qm);

      

+4


source







All Articles