堆/栈 - 进入 QGraphicsItemGroup 的变量范围
如果我有一个 QGraphicsItem,我想将其放入 QGraphicsItemGroup 中,在循环中..就像这样:
for(int i =0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
QPixmap p(imwidth, imheight);
p.fill(Qt::gray);
QGraphicsPixmapItem *ipi = new QGraphicsPixmapItem(p);
group->addToGroup(ipi);
}
}
该项目是否有必要位于堆上,或者我可以将其设为堆栈变量并期望它在中仍然可见在 for 循环之外声明的组?
If I have a QGraphicsItem that I want to put in a QGraphicsItemGroup, in a loop..like so:
for(int i =0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
QPixmap p(imwidth, imheight);
p.fill(Qt::gray);
QGraphicsPixmapItem *ipi = new QGraphicsPixmapItem(p);
group->addToGroup(ipi);
}
}
is it necessary for that item to be on the heap, or can I make it a stack variable and expect it to still be visible in the group, which is declared outside of this for loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
addToGroup
方法需要一个指针,因此你无法通过传递任何其他东西来逃避惩罚。它不会复制传入的对象,只是存储该指针。如果你给它一个指向堆栈分配对象的指针,它迟早会在尝试访问堆栈内存时爆炸,该内存(可能)从那时起就被覆盖了,即使它(奇迹般地)没有被覆盖,那些对象无论如何都会被摧毁 - 所以它们在任何情况下都是无效的。
The
addToGroup
method takes a pointer, so you can't get away with passing it anything else. It doesn't copy the objects passed in, just stores that pointer.If you give it a pointer to stack-allocated objects, it will blow up sooner or later trying to access stack memory which will (probably) have been overwritten since then, and even if it (miraculously) hasn't been overwritten, those objects will have been destroyed anyway - so they'll be invalid in any case.
如果您将 QGraphicsPixmapItem 声明为堆栈变量,它将在循环的每次迭代时被破坏。因此,使用其地址作为 QGraphicsItemGroup::addToGroup 方法的指针很可能会导致程序稍后出现分段错误。
If you declare your QGraphicsPixmapItem as a stack variable, it will be destructed at each iteration of the loop. Therefore, using its address as a pointer for the QGraphicsItemGroup::addToGroup method will most likely lead to a segmentation fault later in the program.