0

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.

user1291510
  • 265
  • 5
  • 14
  • 1
    Possible duplicate of [shared\_ptr to an array : should it be used?](http://stackoverflow.com/questions/13061979/shared-ptr-to-an-array-should-it-be-used) – Mad Physicist Dec 12 '15 at 20:06
  • `std::shared_ptr` is difficult to use with dynamic arrays; `std::shared_ptr` by default models a single `T` object, not an array. (You would need to pass a suitable array deleter; e.g. [see the example here](http://en.cppreference.com/w/cpp/memory/default_delete).) `std::experimental::shared_ptr` supports array types `T[]` (like `std::unique_ptr`) and has a more convenient way of requesting the correct deleter. – Kerrek SB Dec 12 '15 at 20:13

1 Answers1

1

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);
Minor Threat
  • 2,025
  • 1
  • 18
  • 32