簡體   English   中英

在C ++中復制包含基類指針的QMap導致堆棧損壞

[英]Stack corruption with copying a QMap containing a base class pointer in C++

我有以下設置:

class A {
  public:
  A();
  virtual ~A();
  A(const A&other) {*this = other;}
  A& operator=(const A&) {/*assigne reference members, create new of pointer members*/}

  /* some other stuff */
}

class B : public A {
  public:
  B();
  virtual ~B();
  B(const B&other) {*this = other;}
  B& operator=(const B&rhs) { A::operator=(rhs); /*assigne reference members, create new of pointer members*/}

  /* some other stuff */
}

class C : public A {
  public:
  C();
  virtual ~C();
  C(const C&other) {*this = other;}
  C& operator=(const C&) { A::operator=(rhs); /*assigne reference members, create new of pointer members*/}

  /* some other stuff */
}


class D {
  public:
  D();
  virtual ~D();
  D(const D&other) {*this = other;}
  D& operator=(const D&rhs) {
    /* iterate through map and create new instances of B or C */
    m_list = rhs.m_list;
  }

  QMap<QUuid, A*> GetMap() {return m_map;}
  QList<QUuid> GetList {return m_list;}

  private:
  QMap<QUuid, A*> m_map;
  QList<QUuid> m_list;

  /* some other stuff */
}

and into the map get a reference from which creates a deep copy of the QMap through 's copy constructor. 現在,我將一些放入映射中,從獲得引用, 通過的副本構造函數創建QMap的深層副本。 如果我嘗試獲取QMap的大小,則可以正常工作,但列表已損壞。 gets corrupted when the assignment operator of the QMap calls std::swap. 借助於調試器,我發現當QMap的賦值運算符調用std :: swap時, 中的QList會損壞。 我完全不清楚我的記憶在那里發生了什么。

這與派生和使用基類指針有關嗎? 如果我將QMap更改為std :: map,我的程序也會崩潰,但在另一點出現另一個問題。

感謝您的任何建議和提示。

現在,我將一些B和C放入映射中,以獲取D的引用,該引用通過D的副本構造函數創建QMap的深層副本。

復制了地圖,但是您有兩個指向相同對象的地圖,那么問題是誰擁有這些對象。

最好不要使用原始指針,而是使用shared_ptr來存儲實例

QMap<QUuid, std::shared_ptr<A>> m_map;

還要注意,您的方法GetMap()返回的是地圖的副本,而不是實際的地圖,因此在調用時,您還有一個映射到同一對象的地圖。

暫無
暫無

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

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