1

Let's say I have a struct containing a list of std::vector objects that are all empty. Then the struct is part of a larger contiguous, dynamically allocated memory region and all of that is zeroed with memset (which is not something I can change). Now I'd like to re-construct the vector objects just not to have an undefined behavior later on when I use them (the vectors do seem to function fine even without explicitly reconstructing them, but I'm not sure if that is a behavior I can rely on).

typedef struct {
    // many other members
    std::vector<someClass> listOfVectors[10];
    // many other members
} mystruct;
Evg
  • 25,259
  • 5
  • 41
  • 83
Reza
  • 11
  • 3
  • Don't use memset to initialize, use brace initialization of your struct. `typedef struct` is "C" style by the way. `mystruct x{};` initializes memory of struct x to all 0 – Pepijn Kramer Oct 01 '22 at 04:39
  • 4
    It's [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) to `memset` on a type that is not trivially copyable (see [docs](https://en.cppreference.com/w/cpp/string/byte/memset)), and `std::vector` is not trivially copyable. The code you've been given has a severe fault. The only thing to do in this case is to have your struct contain a `std::vector*` and let that get memset to zero (i.e. null pointer). I don't often recommend using raw pointers, but it can be necessary when dealing with C-style APIs like this. – Silvio Mayolo Oct 01 '22 at 05:22
  • @SilvioMayolo Couldn't have said it better :) – Pepijn Kramer Oct 01 '22 at 05:29
  • Sounds like you are using some sort of custom memory pool. You are probably looking for ["placement new"](https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new). – Sedenion Oct 01 '22 at 06:27
  • If you destruct the vectors before the memset then use implace new afterwards then i guess it'll work? Maybe with a Boolean member to indicate whether the vectors are currently constructed if there's a chance that the memset can be done without you then reconstructing? – Alan Birtles Oct 01 '22 at 06:38

0 Answers0