将char *提供给std :: string进行管理(最终释放内存)

Ste*_*eve 0 c++ c++11

我必须使用一个库函数,该函数为生成的字符串分配一点内存并返回a char*,期望调用者最终使用释放内存free()

// Example declaration of the library function:
char* foo();
// ...
// Example usage:
auto foo_str = foo();
// ...
free(foo_str);
Run Code Online (Sandbox Code Playgroud)

是否可以std::string从此指针构造一个,将内存的所有权传递给字符串对象,以便在销毁字符串时将其释放?我知道我可以实现这种RAII行为的我自己的包装器,但是我猜想这个轮子已经被发明了一次。

Bar*_*rry 5

不,您不能使用string这种东西。string始终拥有其缓冲区,并将分配和释放自己的缓冲区。您无法所有权转让string。我什至不知道是否有这样的建议。

这里一个容器,可以将所有权转移到虽然:unique_ptr

struct free_deleter {
    void operator()(void* p) {
        free(p);
    }
};

std::unique_ptr<char, free_deleter> foo_str = foo();
Run Code Online (Sandbox Code Playgroud)