想想一个返回必须为freed的东西的C函数,例如POSIX strdup().我想在C++ 11中使用该函数并避免任何泄漏,这是正确的方法吗?
#include <memory>
#include <iostream>
#include <string.h>
int main() {
char const* t { "Hi stackoverflow!" };
std::unique_ptr<char, void(*)(void*)>
t_copy { strdup(t), std::free };
std::cout << t_copy.get() << " <- this is the copy!" <<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
假设它有意义,可以使用与非指针相似的模式吗?例如,POSIX的函数open返回int?