‘make_unique’ is not a member of ‘std’
错误信息如下:
error: ‘make_unique’ is not a member of ‘std’
test = std::make_unique<TESTCODE>>(res);
在编译C++代码时,如果遇到“‘make_unique’ is not a member of ‘std’”这样的错误,通常是因为你的C++标准库版本较旧,或者没有启用C++14标准及以上版本。std::make_unique 是在C++14中引入的一个功能。如果你使用的是C++11标准,则需要升级到C++14或更高版本。
你可以通过以下几个步骤来解决这个问题:
- 确保启用C++14或更高版本:
在编译时,确保你的编译器使用了C++14或更高版本。例如,如果你使用的是g++,可以在编译命令中添加-std=c++14或-std=c++17选项:
g++ -std=c++14 your_code.cpp -o your_program
或
g++ -std=c++17 your_code.cpp -o your_program
- 检查编译器版本:
确保你的编译器版本支持C++14或更高版本。对于g++,可以使用以下命令查看版本:
g++ --version
如果版本较旧,可以考虑升级你的编译器。
- 手动实现make_unique(如果无法升级编译器):
如果你无法使用C++14或更高版本,可以手动实现一个简单的make_unique。例如:
template
std::unique_ptr make_unique(Args&&... args) {return std::unique_ptr(new T(std::forward(args)...));
}
然后在你的代码中使用这个make_unique函数。如果不能升级为 11 版本之上,可以按照如下方案修改:
result.lock = std::unique_ptr(new Lock(fd, &rwlock));
test = std::unique_ptr(new TESTCODE(res));
解读:
- 这行代码使用 new 来手动创建 TESTCODE 对象,并将其所有权交给 std::unique_ptr。
- 这正是 make_unique 的底层行为,在 C++11 中我们就只能这么写。
注意事项:
- 使用 new 时,请确保没有抛出异常的风险,避免内存泄漏(但这里配合 unique_ptr 使用是安全的)。
- 这种写法等价于 make_unique,只是少了那份简洁。