Yes, it is. C++
allows user-defined types that run code when they are destroyed. That means automatic variables can be used to manage allocated memory.
See (for example) std::unique_ptr for a smart pointer that cleans up memory automatically when it goes out of scope.
Furthermore std::unique_ptr adds no overhead to using a raw pointer as it is purely syntactic sugar, the compiler's optimizer strips everything away generating almost identical code to hand crafted manual allocation.
Furthermore, it is not just memory that can be automatically cleaned up you can use std::unique_ptr
to close your files for you!
struct FILE_closer{void operator()(std::FILE* fp) const { if(fp) std::fclose(fp); }};
using unique_FILE = std::unique_ptr<FILE, FILE_closer>;
void func()
{
// this will close when it goes out of scope
unique_FILE fp(std::fopen("filename.txt", "w"));
std::fprintf(fp.get(), "hello %s", "world");
// no need to close fp here!
}
Character string that automatically clean up themselves!
struct malloc_deleter{void operator()(void* p) const { std::free(p); }};
using char_uptr = std::unique_ptr<char, malloc_deleter>;
void func()
{
char_uptr s((char*) malloc(128));
std::sprintf(s.get(), "Hello World Number %d\n", 5);
std::printf(s.get());
// no need to call free(s) here!!!
}