On Sat, 16 Jun 2018 10:55:02 +0200
Rosario19 <R...@invalid.invalid> wrote:
> On Fri, 15 Jun 2018 12:50:00 +0100, Chris Vine wrote:
> i not use new() operator only malloc() or malloc like functions
> the new() operator i have is not the new() library provide
No, you have got something completely wrong, although it is difficult to
decipher your remarks to find out what. operator new() either
allocates and returns raw memory, or (when it takes a second void*
argument in connection with a placement new expression) does nothing.
In many implementations, an allocating operator new() comprises no more
than a call to malloc(). You seem to be confusing operator new() with
the new expression, which is something different. operator new()
returns raw uninitialized memory. The new expression constructs an
object in that memory.
> >namely a case where an object is to be constructed in
> >pre-allocated raw memory, such as has been returned by malloc(). The
> >form is this:
> >
> > void* p = malloc(sizeof(T));
> > T* tp = new (p) T;
> this line what would make?
> call new, pass it the pointer to void* p
> call the constructor in the address of p of the compatible T
> constructor?
It constructs an object of type T, via T's constructor, in the memory
pointed to by p, rather than calling allocating operator new() to
obtain a dynamic memory allocation and constructing it there.
> > ... do something with tp ...
> > tp->~T();
> > free(tp);
>
> this above seems to me better free(p)
No, it makes no difference. The value of p and tp is the same, but one
is of type void* and the other of type T*. Since free() takes its
argument by void* it makes zero difference.
> in the start of the class, that use the generic T type
> i could write something as
> "this is ok only if type T allow the existence of one element that has
> in it all memory 0"
> this is equvalent to the "call one constructor on the type when the
> memory exist"
This is unintelligible. Possibly you asked the wrong question and you
are not interested in placement new. Possibly you want to install your
own global operator new() for your program which always hands off to
malloc() (although that is probably what your default global operator
new() already does anyway), or possibly you want to override global
operator new for a particular class. The latter is pretty common for
types that you want to implement their own memory pools. You still use
the new expression to construct objects of such classes, but when the
new expression obtains new memory it calls the class specific version of
operator new() instead of global operator new().
Try getting a decent book on C++.