如果你运行下面的代码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 = %d\n", 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 = %d\n", fread(p, 1, sizeof buf, f));
fclose(f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
auto buf2 = make_unique<char>(1024 * 32);
Run Code Online (Sandbox Code Playgroud)
分配一个char并初始化它(1024 * 32) mod 256(假设8位字符).要分配char包含这些元素的s 数组,请使用
auto buf2 = unique_ptr<char[]>(new char[1024 * 32]);
//or
auto buf2 = make_unique<char[]>(1024 * 32);
Run Code Online (Sandbox Code Playgroud)
进行更改后,您的程序应该按预期运行.
你也可以unique_ptr用来管理它FILE.
定义删除器和别名
auto fcloser = [](FILE *f) { ::fclose(f); };
using unique_file = std::unique_ptr<FILE, decltype(fcloser)>;
Run Code Online (Sandbox Code Playgroud)
然后用它作为
unique_file f(fopen("tmpfile", "wb"), fcloser); // use f.get() to access FILE*
Run Code Online (Sandbox Code Playgroud)
您甚至可以定义工厂功能以减少详细程度.