c++ - RAII 字符缓冲区

标签 c++ raii

为了安全地使用 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/

相关文章:

c++ - 如何清理失败的构造函数

c++ - longjmp 和 RAII

java - java.util.concurrent.locks.Lock 的 AutoCloseable 包装器有任何风险吗?

c++ - 在代码的其他部分使用带有 lock_gard 的同一个互斥体而不使用它是否安全

C++ unordered_map 与 uint8_t

C++ 声明其大小值来自 const 数组的数组

c++ - 如何在 C++ 中挂起一个程序,然后将其挂起 "unhang"

c++ - 返回标准流的编译器错误 C2448

c++ - 单元测试资源管理类中的私有(private)方法 (C++)

c++ - OpenGL 闪烁屏幕