为什么我不能使用删除器创建此unique_ptr
Why can I not create this unique_ptr with deleter?
我正在使用 SDL,遇到了一个我无法解决的问题。我想将纹理(指向结构的指针)保留在std::map
中,其中我使用std::string
作为键,std::unique_ptr<texture, void(*)(texture*)>
作为值。我必须在std::unique_ptr
中使用删除器,因为纹理必须通过某个功能释放。纹理也是由另一个函数创建的。我将代码简化为如下所示:
#include <map>
#include <memory>
int* new_int(){ return new int; }
void delete_int(int* p){ delete p; }
typedef std::unique_ptr<int, void(*)(int*)> int_ptr;
int main()
{
std::map<int, int_ptr> the_map;
the_map[1] = int_ptr(new_int(), delete_int);
return 0;
}
当我尝试在Visual Studio 2012中编译此代码时,我收到以下错误:
error C2338: unique_ptr constructed with null deleter pointer.
我觉得这很奇怪,因为我提供了delete_int
作为删除器指针。欢迎任何帮助,不同的方法也是如此。提前感谢!
这是因为使用 map::operator[]
要求值类型是默认可构造的,而本例中的unique_ptr
则不是。存储的指向 unique_ptr
对象的指针可能为空,但如果删除器是指针,则可能不为 0。你可以检查一下
the_map[1];
甚至只是
int_ptr p;
这将为您提供完全相同的错误。
解决方案是使用std::map::emplace
:
the_map.emplace(1, int_ptr(new_int(), delete_int));
如果由于未在您的环境中实现而无法做到这一点,则可以使用 std::map::insert
the_map.insert(std::make_pair(1, int_ptr(new_int(), delete_int)));
或更冗长但效率更高
the_map.insert(std::map<int, int_ptr>::value_type(1, int_ptr(new_int(), delete_int)));
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 为什么 std::unique 不调用 std::sort?
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗