为了安全地使用 C++,我想封装几个 C 函数。有一个 C 函数,它接受指向数组的原始指针及其大小,比如 -
void function(char* bufferToFill, size_t bufsize)
现在,我无法找到可以公开要传递给此类函数的原始指针的 C++ 对象。我想避免使用 new[] 并记住在每次抛出异常时删除它。
std::string 显然不能暴露它的 char*,std::vector 类似,我唯一想到的是 std::unique_ptr 但感觉有点奇怪(因为它通常用于拥有一个对象,而不是数组?)
解决此类问题的正确 C++ 方法是什么? 提前致谢
最佳答案
the only thing that comes to my mind is std::unique_ptr but it feels kinda odd (because its usually used to own an object, not array?)
这里又是一个误解。
数组是一个对象,the language specifically allows for std::unique_ptr
of arrays :
std::unique_ptr<int[]> p(new int[10]);
关于c++ - RAII 字符缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936908/