将char *赋予std :: string进行管理(最终释放内存) [英] Giving char* to std::string for management (to eventually free memory)

查看:37
本文介绍了将char *赋予std :: string进行管理(最终释放内存)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to use a library function that allocates a bit of memory for a generated string and returns a char*, with the expectation that the caller eventually free the memory with free().

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

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

Is it possible to construct a std::string from this pointer, passing ownership of the memory to the string object so it will be freed when the string is destructed? I know I could implement my own wrapper that would give this RAII behavior, but I'm guessing this wheel has already been invented once.

推荐答案

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

No, you cannot use string for such a thing. string always owns its buffer, and will allocate and deallocate its own. You can't transfer ownership into a string. I don't even know if there's a proposal for such a thing.

有一个 容器,您可以通过该容器将所有权转移到其中: unique_ptr :

There is a container that you can transfer ownership into though: unique_ptr:

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

std::unique_ptr<char, free_deleter> foo_str = foo();

这篇关于将char *赋予std :: string进行管理(最终释放内存)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆