【问题标题】:C++ access violation when calling instance method调用实例方法时的 C++ 访问冲突
【发布时间】:2012-04-08 21:47:10
【问题描述】:

我正在创建一个看起来像这样的 DirectX 11 辅助类:

#import "DXClass.h" // I have declared the constructor and the other methods here
// All of the DirectX libraries are imported in the header as well 

DXClass::DXClass()
{

    // Pointers created, etc.
}

DXClass:~DXClass()
{
    // Other DirectX objects released   

    // With an if (bbSRView) {}, the exception still occurs, so bbSRView is not NULL
    // bbSRView is a ID3D11ShaderResourceView*
    // When the other violation does not occur, one does here:
    bbSRView->Release();
    bbSRView = NULL;

    // More releases

void DXClass::Initialize()
{
    SetupDisplay();

    // Other initialization that works fine
}

void DXClass::SetupDisplay()
{
    // This is where the debugger shows the access violation.
    // factory is declared as DXGIFactory*
    HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void **)&factory);

    // Loop through adapters and outputs, etc.
}

这个类是这样初始化的:dxClass = new DXClass(); Initialize() 函数在创建dxClass 的类的另一个方法中被调用。

当应用程序运行时,我在setupDisplay() 函数的开头遇到了访问冲突。但是,如果我将setupDisplay() 中的代码放入Initialize(),删除对setupDisplay() 的调用,则不会发生访问冲突。另外,如果我从setupDisplay() 中删除代码,使其成为一个空函数,然后在Initialize() 中调用它,则不会发生访问冲突。

似乎没有指针为 NULL,如果按上述方式更改,应用程序将正常启动。但是,另一方面,应用程序在退出时会收到另一个访问冲突。调试器指向ID3D11ShaderResourceView* 上的Release() 调用,我已经在我的代码sn-p 中指出了这一点。这个指针似乎也有效。

我也检查了类似的问题,但该类的 this 指针似乎是有效的,并且我没有创建任何可能溢出的缓冲区。也没有任何东西可以提前删除/释放对象。

我不知道是什么导致了错误。 :/

谢谢:D

编辑: 这是一个孤立的测试,具有相同的错误: 我的主要功能是:

INT APIENTRY wWinMain(HINSTANCE, HINSTANCE, LPWSTR, INT)
{
    App *app = new App();
    app->Run();
    app->Release();
 }

在我的App 类中,我删除了所有窗口功能和任何其他变量,使其看起来像这样:

App::App()
{
    dxClass = new DXClass();
}

App::~App()
{
    delete dxClass;
}

void App::Run()
{
    dxClass->Initialize();

    while (true) {} // Never reaches here
}

访问冲突仍然发生在同一个地方。此外,如果我将工厂实例变量替换为:

IDXGIFactory *f;
HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void **)&f);

这在其他应用程序中对我有用。

【问题讨论】:

  • 我怀疑错误出在您显示的代码中,而是出在您使用该代码的其他地方。制作一个最小的、独立的测试用例并发布那个而不是片段。
  • 我认为这里没有足够的信息来说明发生了什么。顺便说一句,你应该使用 CComPtr,它会让你的生活更轻松:msdn.microsoft.com/en-us/library/ezzw7k98(v=vs.80).aspx
  • 最有可能导致问题的变量factory 不知从何而来。没有代码显示它。

标签: c++ function methods directx access-violation


【解决方案1】:

调用 Release() 时的访问冲突通常意味着对象已经从其他地方收到了它的最终 Release()(并且它已经销毁了自己)。一种可能的解决方案是将指针传递到 DXClass 时使用 AddRef()

【讨论】:

  • 我同意这听起来像是一个经典的use-after-free 场景。
  • 谢谢 - 我想通了。我在CreateDXGIFactory() 下面几行,当适配器从未初始化或设置为 NULL 时,我正在执行逻辑非 (!adapter)。 :S 我认为这个错误也间接导致了Release() 错误,因为现在一切正常。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多