Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a shared_ptr to OpenGL?

Tags:

c++

c++11

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?

like image 701
Josh Elias Avatar asked Dec 10 '12 03:12

Josh Elias


2 Answers

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
like image 85
Praetorian Avatar answered Oct 26 '22 22:10

Praetorian


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.

like image 21
Karthik T Avatar answered Oct 27 '22 00:10

Karthik T