If I have code that would normally function like this:
char* log = new char[logLength];
glGetProgramInfoLog(..., ..., log)
//Print Log
delete [] log;
How could I achieve the same result with a C++11 Smart Pointer? Who knows what could happen before I have a chance to delete that memory.
So I guess I need to downcast to a C style pointer?
If your code really looks like that in your snippet, shared_ptr
is a bit of an overkill for the situation, because it looks like you do not need shared ownership of the allocated memory. unique_ptr
has a partial specialization for arrays that is a perfect fit for such use cases. It'll call delete[]
on the managed pointer when it goes out of scope.
{
std::unique_ptr<char[]> log( new char[logLength] );
glGetProgramInfoLog(..., ..., log.get());
//Print Log
} // allocated memory is released since log went out of scope
std::shared_ptr
has a method get
which you can use to get a C style pointer to the variable. If that pointer is to a std::string
, you need to further call the c_str()
function to get a pointer to C style string.
edit: I notice the function is writing to the string as opposed to reading. You would need to resize the std::string first, and even after that, the pointer returned by c_str isnt meant for writing. std::shared_ptr should work though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With