簡體   English   中英

智能指針或“更好”的析構函數

[英]Smart pointers, or “better” destructor

哪種類型的智能指針(共享的,作用域的)最適合此類數據結構...

結構1:

//Class with cross-references to points p1, p2
class PointTopo
{
private:
    double x, y;
    PointTopo * p1;
    PointTopo * p2;

public:
    PointTopo(double xx, double yy): x(xx), y(yy) {this-> p1 = NULL; this->p2 = NULL;}
    ...

};

結構2:

//Class  with cross references: topological model for Delaunay triangulation
class Edge
{
   private:
      Point * start; //Only 2D point without topo information
      Edge *next;
      Edge *previous;
      Edge *twin;
...
};

我想使用向量存儲Edges和PointTopo:

class PointsTopoList
{
   private:
      std::vector <PointTopo *> points;
   public:

      inline void push_back ( PointTopo *p ) { points.push_back ( p );}
      ~PointsTopoList() {clear();}
      void clear()
        {
           for ( TNodes2DList::iterator i_points= points.begin(); i_points!= points.end(); ++i_points)
            {
            if ( *i_points!= NULL )
            {
                delete *i_points;
                *i_points= NULL;
            }

             points.clear();
        }

}

但是析構函數存在一些問題,因此我想知道是否使用引用計數。

int main()
{
   PointTopo *p1 = new PointTopo(0,0);
   PointTopo *p2 = new PointTopo(10,10);
   PointTopo *p3 = new PointTopo(20,20);
   PointTopo *p4 = new PointTopo(30,30);

   PointsTopoList tl1;
   tl1.push_back(p1);
   tl1.push_back(p2);
   tl1.push_back(p3);
   tl1.push_back(p4);

   PointsTopoList tl2;
   tl2.push_back(p1);  //P1 is stored in tl1 and tl2
   tl2.push_back(p2);  //P2 is stored in tl1 and tl2
}

點p1,p2將存儲在兩個列表tl1,tl2中。 tl2的析構函數導致異常,點p1和p2已使用tl1析構函數刪除。

這個例子不是合成的。 想象一下,nl2代表nl1的子集,例如nl1的凸包...

我認為,沒有引用計數就無法解決此問題...所以我嘗試使用一些智能指針...

非常感謝您的幫助...

tl2的析構函數導致異常,點p1和p2已使用tl1析構函數刪除。

您試圖兩次delete對象p1 (和p2 )。 這調用了UB-做一件壞事。 嘗試在std::tr1命名空間(請參閱編譯器文檔以獲取更多詳細信息)或Boost中都可用的shared_ptr (引用計數的智能指針)。

另一件事是復制對象(而不是復制指針)。 PointTopo需要復制PointTopo對象。

(就我個人而言,我傾向於對EdgePointTopo成員單獨使用unique_ptr 。)

shared_ptr<>會引用計數和管理指向同一對象的多個指針,並在銷毀指向該對象的最后一個指針時刪除該對象。

scoped_ptr<>使指針的行為類似於堆棧變量,一旦指針超出范圍,它將刪除指向的對象。 這不是您在此處尋找的行為。

在您的用例中, shared_ptr<>提供的引用計數就是您想要的。

您需要的是boost :: shared_ptr

暫無
暫無

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

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