DEV Community

Discussion on: First Contact with C++

quantumsheep profile image
Nathanael Demacon • Edited on

C++ also deals with manual memory allocation

C++ standard makes you never deal with memory allocation. You don't even use malloc like C, every memory allocation is made by the new keyword:

char *text = new char[64]; // allocate 64 bytes

But with C++ standard, char * and reallocation can be escaped:

std::string text;

Same with arrays:

// without standard
int *numbers = new int[64]; // allocate 64 integers

// with standard
std::vector<int> numbers;
codemouse92 profile image
Jason C. McDonald • Edited on

You still need to use manual memory allocation to instantiate many custom objects.

However, even if you do need to handle manual memory allocation, smart pointers handle nearly all of the scenarios where you'd need it.

std::shared_ptr<MyFancyObject> fancyObjectPtr = std::make_shared<MyFancyObject>();

Or, thanks to the relatively new auto keyword...

auto fancyObjectPtr = std::make_shared<MyFancyObject>();

std::shared_ptr handles the allocation, deallocation, and lifetime. Alternatively, if you know you're only ever going to have one pointer to the object, you can use std::unique_ptr.

Even still, it's good to know how to use new; every now and then, you still need it.