为什么以下代码触发断言?这段代码最初工作,并且在某些时候开始触发一个断言,因为shared_ptr超出了范围.
#include <iostream>
#include <memory>
#include "GLFW/glfw3.h"
int main()
{
if (!glfwInit()){
std::cout << "Failed to initialize GLFW." << std::endl;
return -1;
}
auto window = std::shared_ptr<GLFWwindow>(glfwCreateWindow(1024, 768, "Test", NULL, NULL));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我只使用了最少量的代码来重现这一点,也许我误解了shared_ptr的使用.我也尝试了它的语法:
std::shared_ptr<GLFWwindow> window(glfwCreateWindow(1024, 768, "Test", NULL, NULL));
Run Code Online (Sandbox Code Playgroud)
我在调试器(VS2013)的输出窗口中得到的确切错误消息如下:
Debug Assertion Failed!
Program: C:\Users\...\xxxx.exe
File: f:\dd\vctools\crt\crtw32\misc\dbgdel.cpp
Line: 52
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
Run Code Online (Sandbox Code Playgroud)
从我研究的内容来看,它似乎试图将shared_ptr两次释放 - 这种情况如何,我该如何防止这种情况?这可能是值得一提的是从交换的类型GLFWwindow,以struct test { int i; };不再触发断言.这是否意味着GLFWwindow在内部删除指针?如果是这样,为什么代码在某一点工作但现在不工作?