Using Malloc and std::Strings in C Structures
You have encountered a common issue when attempting to use a structure containing std::strings with dynamic memory allocation using malloc(). This issue stems from the complexities of object construction and memory management in C .
The Problem with Malloc
Malloc allocates raw memory, creating an uninitialized block of space. However, using malloc for objects with non-trivial constructors, like std::string, is problematic as it does not invoke the constructor to properly initialize the object.
Using New Instead of Malloc
The solution is to use the C operator new instead of malloc. New creates a new object and invokes its constructor, ensuring proper initialization. In your case, you can use:
example *ex = new example;
Using Placement New for Raw Memory
If you specifically need to use malloc, you can allocate raw memory with malloc and then use placement new to construct the object in that memory:
void *ex_raw = malloc(sizeof(example)); example *ex = new(ex_raw) example;
However, using new directly is the preferred method in this scenario.
The above is the detailed content of Why Can\'t I Use Malloc with std::strings in C Structures?. For more information, please follow other related articles on the PHP Chinese website!