gpt4 book ai didi

基于 C++ 范围的 for 循环给出 SIGABRT,而普通循环工作正常

转载 作者:行者123 更新时间:2023-11-27 23:57:39 26 4
gpt4 key购买 nike

这段代码工作正常:

for (int i = 0; i < grid.size(); i++)
painter.drawRect(grid[i].rect);

此代码无效:

for (Square square : grid)
painter.drawRect(square.rect);

运行时打印失败:

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc The program has unexpectedly finished.

这是调用堆栈:

1  raise
0x7ffff53cf91f
2 abort
0x7ffff53d151a
3 __gnu_cxx::__verbose_terminate_handler()
0x7ffff5f3f52d
4 ??
0x7ffff5f3d2d6
5 std::terminate()
0x7ffff5f3d321
6 __cxa_throw
0x7ffff5f3d539
7 operator new(unsigned long)
0x7ffff5f3dafc
8 __gnu_cxx::new_allocator<Square>::allocate
new_allocator.h 104 0x408548
9 std::allocator_traits<std::allocator<Square>>::allocate
alloc_traits.h 416 0x408308
10 std::_Vector_base<Square, std::allocator<Square>>::_M_allocate
stl_vector.h 170 0x407f54
11 std::_Vector_base<Square, std::allocator<Square>>::_M_create_storage
stl_vector.h 185 0x407b99
12 std::_Vector_base<Square, std::allocator<Square>>::_Vector_base stl_vector.h 136 0x4078f3
13 std::vector<Square>::vector
stl_vector.h 322 0x4075c3
14 Square::Square
square.h 19 0x407406
15 Canvas::Canvas
canvas.cpp 23 0x406752
16 MainWindow::MainWindow
mainwindow.cpp 10 0x4044b6
main.cpp 7 0x404310

问题发生在canvas.cpp

请阐明可能导致此问题的原因。

最佳答案

您尝试的两个循环根本不等价。第一个使用grid[i]vector[]运算符返回一个reference到元素 vector ,而不是它的拷贝。第二个版本使用 based-range for: 但是你写它的方式,for(Square square : grid,你要求它为每个元素制作一个 copy 并放置它在变量 square 中。

您的 Square 对象似乎是一个沉重的对象,或者其复制构造函数存在一些问题,导致 bad_alloc。但是,由于第一个版本运行良好,要执行相同的操作,您需要使 range-based-for 在引用上工作,而不是每个元素的拷贝:

for (Square& square : grid)  // <-- return a reference on each element.
painter.drawRect(square.rect);

甚至最好返回一个const ref,只要它足以对元素执行所需的操作:

for (const Square& square : grid) // <-- return a const ref whenever it is enough and the subsequent action does not modify the object
painter.drawRect(square.rect);

关于基于 C++ 范围的 for 循环给出 SIGABRT,而普通循环工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com