为什么我不能将unique_ptr与恐惧一起使用?

Why can't I use unique_ptr with fread?

本文关键字:一起 恐惧 ptr 不能 unique 为什么      更新时间:2023-10-16

如果运行下面的代码,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*

您甚至可以定义一个工厂函数来进一步减少冗长的内容。