相关疑难解决方法(0)

std :: unique_ptr用于需要免费的C函数

想想一个返回必须为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

c++ c++11

50
推荐指数
5
解决办法
9886
查看次数

标签 统计

c++ ×1

c++11 ×1