简体   繁体   中英

c++ object instantiation using sizeof, malloc and cast

In Java I can instantiate an object using the 'Class' method 'newInstance' which for my particular system I find very helpful indeed. I am now trying to achieve something similar in C++.

It has not been obvious to me how this might be achieved but after some reflection .... (do you get it ... huh?) I think that it might be possible by creating a ClassDescription class which has an attribute holding the 'sizeof' the class instance and a method newInstance which mallocs this amount of memory and returns it as a void *. The calling code will then need to cast this appropriately.

Does the C++ language suitably define whether this is valid?

By the way .. I recognise that I could create a registry holding Factories for the classes which is a backup plan. For answers to this question I would value focusing on the specific question of whether what I have discussed will work.

Best Regards

* Additional Context * The reason for this requirement is to allow a generic library to instantiate classes which the library user is aware of but not the library itself. The library will have some meta data to use to achieve this and so could be told the sizeof the class. It is 'neater' from the user perspective not to have to add a factory object to the the meta data.

This would be valid in some instances. The requirement is that the type must be a "plain old data type" (POD) ( see also this answer ). If it has anything more complicated (eg virtual member functions, members which have virtual member functions, base classes must also be POD etc.) then it will not work and is undefined behaviour.

You can check if a type meets these requirements by doing:

#include <type_traits> 

static_assert(std::is_pod<A>::value, "A must be a POD type.");

In general though it probably indicates that you're doing it wrong. C++ isn't Java and there's probably a much better way to solve the underlying real problem.

What you're missing in the malloc and cast method is the construction of the object. Using new both allocates memory and constructs it. This includes building v-tables, calling the constructor and so on. Type casting malloc allocated memory is not valid.

Note that malloc ing a memory block of the right size gives you just raw memory. You need to construct an object of the desired class in this memory block. This can be achieved using placement new .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM