Search code examples
c++memory-managementshared-ptrraii

Using shared pointers for run time array allocations


I have a C++ program where I need to allocate memory for a log (char*).

I read about std::shared_ptr and how they will handle deletion of memory once scope is left.

Will the code below automatically free the log buffer after the scope is left?

std::shared_ptr< char * > pLog = 
    std::shared_ptr< char * > ( new char[logLength+1] );

I know it might be somewhat simple, but I'm not quite sure how to confirm if it works.


Solution

  • You may consider to use std::unique_ptr instead. It will handle deletion of memory once scope is left, but in a more simpler way. Shared pointer creates and maintains a special descriptor object. You don't need that for a simple local buffer.

    auto buff = std::make_unique<char[]>(buffSize);