Malloc on a struct containing a std::vector

后端 未结 5 438
甜味超标
甜味超标 2021-01-14 18:30

Here is the situation :

I use a malloc to allocate memory for a struct. The struct contains various items such as pointers, string variables and vectors.

The

5条回答
  •  不要未来只要你来
    2021-01-14 18:53

    Your code causes undefined behaviour, because your wMyStructure does not point to an object, so you may not use the accessor operator -> on it.

    An object only commences its life after its constructor has completed. Since you don't call any constructor, you do not have an object.

    (If your struct were a POD, i.e. just consisting of primitive types and PODs, then this would be OK, because PODs have trivial constructors, which do nothing.)

    The concrete problem you're facing is that the string and vector members of your struct didn't get to call their constructors, so those members don't exists, and hence the entire object doesn't.

    If you want to decouple memory management from object construction, you can use placement syntax:

    // get some memory
    char arena[HUGE_VAL];
    void * morespace = malloc(HUGE_VAL);
    
    // construct some objects
    MyClass   * px = new (arena + 2000) MyClass;  // default constructor
    YourClass * py = new (morespace + 5000) YourClass(1, -.5, 'x');  // non-default constructor
    

    (You have to destroy those objects manually, px->~MyClass(); etc., when you're done with them.)

提交回复
热议问题