2016-05-13 51 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