为什么我不能将unique_ptr与恐惧一起使用?
Why can't I use unique_ptr with fread?
如果运行下面的代码,fread
将返回0。如果您将p
更改为使用buf
而不是unique_ptr
,它将起作用。为什么?我在MSVC 2013 中运行了这个
#include <iostream>
#include <map>
#include <memory>
using namespace std;
int main(int argc, char *argv[]) {
char buf[1024 * 32];
auto buf2 = make_unique<char>(1024 * 32);
{
memset(buf, 0, sizeof buf);
FILE *f = fopen("tmpfile", "wb");
printf("write = %dn", fwrite(buf, 1, sizeof buf, f));
fclose(f);
}
//char*p = 0 ? buf2.get() : buf;
//char*p = buf;
char*p = buf2.get();
FILE *f = fopen("tmpfile", "r+b");
printf("read = %dn", fread(p, 1, sizeof buf, f));
fclose(f);
return 0;
}
auto buf2 = make_unique<char>(1024 * 32);
分配单个CCD_ 5并将其初始化为CCD_。要分配一个包含这么多元素的char
数组,请使用
auto buf2 = unique_ptr<char[]>(new char[1024 * 32]);
//or
auto buf2 = make_unique<char[]>(1024 * 32);
在进行更改之后,您的程序应该按预期运行。
现场演示
您还可以使用unique_ptr
来管理FILE
。
定义删除程序和别名
auto fcloser = [](FILE *f) { ::fclose(f); };
using unique_file = std::unique_ptr<FILE, decltype(fcloser)>;
然后将其用作
unique_file f(fopen("tmpfile", "wb"), fcloser); // use f.get() to access FILE*
您甚至可以定义一个工厂函数来进一步减少冗长的内容。
相关文章:
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将C++中的库和头与MinGW一起使用
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 为什么我不能将 rand() 与数组的大小一起使用?
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 将fold表达式与std::一起用于两个元组
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 将 std::allocate_shared 与多态资源分配器一起使用
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 将 exprtk 与自定义类的对象一起使用
- 将 std::set 与基于键的比较器一起使用
- 将 C++ 类与 Rcpp 一起使用,从 C 或 R 修改它
- 如何将 Eigen::Ref 与 pybind11 一起使用?
- 如何将AERT_Allocate与 std:vector 一起使用
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 为什么我不能将unique_ptr与恐惧一起使用?