That's not how you write code in C++.
First, as properly mentioned in the comments, do not use malloc
ever. Use new
if you need dynamic memory allocation. Otherwise you would have non-constructed objects, like you have already been told.
Second, do not use new
when you do not have to. If you need dynamic memory allocation, most probably you want to manage this memory with a smart pointer, like std::unique_ptr
. To construct a unique_ptr<T>
, use std::make_unique<T>()
function. Using make_unique
will make you program leak-free and exception safe at zero cost. Using make_unique()
will prevent some tricky situations with leaking due to exceptions and save you a couple of keystrokes when writing the code. At zero cost, of course. See GotW #89 Solution: Smart Pointers.
Third, most likely you don't even need dynamic memory allocation here. This is not Java, we love to allocate things on the stack. Remember that std::vector
itself does dynamic memory allocation to store its buffer. And due to move semantics it can move this storage effective at runtime. There is no much sense to allocate vector
itself in dynamic memory. See Why should C++ programmers minimize use of 'new'?
Do a search on each emphasized item for details.