2016-05-13 52 views
0

我有一個結構箱和指向框對象,像這樣的一個載體,是否可以將自我的地址推向結構構造上的向量?

struct Box { 
    int number; 
    Box() { 
     /* Push address of self to the vector here */ 
     /* All I need is a way to access the address of self */ 
    }; 
}; 

std::vector<Box*> Boxes; 

我想使對象的創建(對於GUI元素)更容易推對象的地址爲矢量創建時。這樣我可以在創建後編輯對象的成員,而不必手動推送到矢量。

是否可以在對象構造函數中訪問self的地址?

+0

要小心。除非完全構造對象,否則不得使用此指針調用函數。如果函數是虛擬的,那麼這樣做就是UB(並且您不希望在將來版本的代碼中假定函數將保持非虛擬)。 –

回答

2

Boxes.push_back(this);是你所需要的。另外請記住在析構函數中刪除它,以免空閒後使用。

std::vector<Box*> Boxes; 

struct Box { 
    int number; 
    Box() { 
     Boxes.push_back(this); 
    }; 
    ~Box() { 
     Boxes.erase(std::remove(Boxes.begin(), Boxes.end(), this), Boxes.end()); 
    } 
}; 

在線演示:http://coliru.stacked-crooked.com/a/b0db13cfdff4a70b