Is there an easy way to build a generic type in C ++ by default, without a dispenser instance?

Context: Writing a container containing type T and char * p to the memory area. Suppose the pointer is already properly aligned for type T - the alignment problem is not part of the question. How do I build an element in this memory area by default?

((*T)(p))->T();

works for classes, but not with some built-in types.

((*T)(p)) = 0; // or simply memset

for integer types, pointers. Do these two cover everything, alliances, and what not? Is there any best practice for this or some kind of standard library function? std :: allocator :: construct can do this, that is, for example, std :: vector uses, but this is not a static method, so I need an instance of it. Is there some kind of standalone or static function that can do this?

- EDIT -

Yes, the answer is obvious, and today I was dumb - posting a new BTW, now I'm trying to destroy an element ...

+4
source share
2 answers

“Posting new” is a term to look for. This is a standard operator newoverload library that does not actually allocate memory, but simply returns any pointer that you pass to it.

+3
source

Include the header <new>and use its new distribution function as follows:

::new (p) T()

Qualification ::avoids the choice of class allocation function.

Paranesia (p)is a list of arguments for the highlight function.

.

, void*, operator new .


, ((*T)(p))->T();, . , . .

+3

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


All Articles