如果我的代码通常像这样:
char* log = new char[logLength];
glGetProgramInfoLog(..., ..., log)
//Print Log
delete [] log;
Run Code Online (Sandbox Code Playgroud)
如何使用C++ 11智能指针实现相同的结果?谁知道在我有机会删除那段记忆之前会发生什么.
所以我想我需要向下转换为C风格的指针?
如果您的代码在您的代码段中看起来真的那样,shared_ptr对于这种情况来说有点过分,因为看起来您不需要分配内存的共享所有权.unique_ptr对数组有一个部分专门化,非常适合这种用例.delete[]当它超出范围时,它将调用托管指针.
{
std::unique_ptr<char[]> log( new char[logLength] );
glGetProgramInfoLog(..., ..., log.get());
//Print Log
} // allocated memory is released since log went out of scope
Run Code Online (Sandbox Code Playgroud)