簡體   English   中英

銷毀shared_ptr時,堆損壞

[英]Heap corruption when shared_ptr is destroyed

考慮以下示例代碼:

Uncopyable.h

class Uncopyable {
protected:
    Uncopyable() {}
    ~Uncopyable() {}

private:
    Uncopyable(const Uncopyable&);
        Uncopyable& operator=(const Uncopyable&);
};

Base.h

class Base : private Uncopyable
{
public:
    Base(int a);

    virtual ~Base();

private:
    int mValBase;
};

Base.cpp

Base::Base(int a)
    : mValBase(a)
{
}

Base::~Base()
{
}

Derived.h

class Derived : public Base
{
public:
    Derived(int a, int b);

    ~Derived();

private:
    int mValDerived;
};

Derived.cpp

Derived::Derived(int a, int b)
    : Base(a),
      mValDerived(b)
{
}

Derived::~Derived()
{
}

當我插入以下代碼塊時(此處未顯示所有代碼)

{
    std::shared_ptr<Derived> derived = std::shared_ptr<Derived>(new Derived(1, 2));
}

在退出代碼塊並銷毀derived的shared_ptr時,我得到了堆損壞(“ CRT檢測到應用程序在堆緩沖區結束后寫入了內存”)。 但是,如果在Derived的構造函數中刪除了mValDerived的初始化,則mValDerived導致堆損壞。 另外,如果將上述類和代碼插入一個非常短的控制台應用程序中,則不會導致堆損壞。

誰能幫助我了解問題所在以及如何解決? 我很茫然。

我正在使用VS2012。

我沒有發現任何代碼錯誤。 如果它在簡短的控制台程序中起作用,則錯誤可能出在您程序的其他部分。 您將必須系統地檢查程序的其他部分,直到錯誤消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM