【发布时间】:2017-01-03 01:27:18
【问题描述】:
这段代码运行良好:
for (int i = 0; i < grid.size(); i++)
painter.drawRect(grid[i].rect);
此代码不起作用:
for (Square square : grid)
painter.drawRect(square.rect);
运行时打印失败:
在抛出 'std::bad_alloc' 的实例后调用终止 what(): std::bad_alloc 程序意外结束。
这是调用堆栈:
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
请说明可能导致此问题的原因。
【问题讨论】:
-
基于范围的循环会复制每个元素,而基于索引的循环不会。看来
Square的复制成本很高。设为for (Square& square : grid) {...}(注意与号)。 -
你是对的!谢谢。