为什么这个shared_ptr在超出范围时会抛出一个断言?

aqe*_*qez 2 c++ shared-ptr glfw c++11

为什么以下代码触发断言?这段代码最初工作,并且在某些时候开始触发一个断言,因为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在内部删除指针?如果是这样,为什么代码在某一点工作但现在不工作?

Som*_*ude 6

最有可能的原因glfwCreateWindow是使用分配数据malloc,并使用std::shared_pointer释放内存delete.这是两种不同的内存分配系统,不应混用.

此外,你不能只释放返回的指针glfwCreateWindow,你需要正确关闭窗口,因为你不知道可能已经分配了什么其他数据glfwCreateWindow.您需要一个自定义删除调用glfwDestroyWindow.