Memory safety is non-negotiable in C++. If you ever find yourself needing to return an array, here are some alternative ways to do it safely! 1. As a good rule of thumb, it's best to avoid using arrays wherever possible. Instead, use std::vector. 2. If for some reason, you absolutely have to use an aray, allocate the array with std::unique_ptr(). 3. If that array needs to be passed around after it returns, use std::shared_ptr() #codingtips #interview #softwareengineering #cpp #memorysafety
why? In my day we didn't have these std:: things we just managed memory the way t was intended to be managed. malloc, calloc,, memset. Understand your memory management.
It is not just arrays. One shall never return an ownership as a raw pointer. Also avoid explicit ‘operator new’ use. Instead consider make_unique and make_shared. std::make_shared does not support the arrays until C++20, so consider boost::make_shared if you’re on C++17. Just keep in mind, if you use weak_ptr, the array memory allocated by std/boost::make_shared (I mean raw memory, not objects allocated in the memory) won't be released until all shared and weak references are destroyed.
would auto_ptr not simplify the memory management even better? and for passing it around i would use a mix of unique_ptr and weak_ptr as in Rust to track ownership if this is really needed...but in my C++ code usually auto_ptr is my weapon of choice
it’s good to see something “tech” on this forum… way to much “high five crap” here. 👏👏👏
std::vector is the only reasonable option here. If you know the size at compile time, use std::array instead You don't ever need a raw array with the above constructs, because both provide data() methods and store stuff in a single contiguous memory block.
Here is very good talk provided by the Mateusz Pusz regarding the use of pointers. https://youtu.be/qrifyjQW9gA
Simple, use std::array instead and .data() where you need raw array. Your solution is over complicated.
Oh I miss C++ and the smart pointers. I wonder if it has changed much since I stopped using it around 6 years ago
This is great advice... unless you are dealing with performance-critical code, embedded systems, or interfacing with C-Style APIs...i.e. OpenGL or Vulkan. std::unique_ptr<int[]> is appropriate for managing ownership of a dynamically allocated array in low-level code or when interfacing with APIs that require raw pointers, but it’s not a general-purpose solution for returning arrays. Using std::shared_ptr<int[]> for arrays introduces unnecessary overhead due to shared ownership semantics (reference counting). Shared ownership is rarely appropriate for arrays unless multiple objects genuinely need to share and manage the same array’s lifetime, which is uncommon for return values. This advice is "incomplete" at best and dangerously misinformed at worst.