gpt4 book ai didi

c++ - 为循环内创建的对象调用哪个 C++ vector push_back

转载 作者:行者123 更新时间:2023-11-30 03:34:50 25 4
gpt4 key购买 nike

这是一个非常基本的问题,但我似乎无法理解这里发生的事情的逻辑。考虑代码片段:

class Board{
private:
vector< vector<Cell> > allCells;
int bheight;
int bwidth;
public:
Board(int width = 10, int height = 10){
bheight = height; bwidth = width;
allCells.resize(width);
#loop for creating cell objects
for(int i = 0; i < width; i++){
allCells[i].reserve(height);
for(int j = 0; j < height; j++){
Cell aCell(i,j,0); #an object created inside a loop
allCells[i].push_back(aCell); #push it into a vector
}

}
}

这段代码工作正常,即在退出构造函数后, vector ( vector 的)allCells 中的所有对象仍然存储适当的信息。我的问题是这是如何实现的?根据定义,vector.push_back 只有两种变体:

void push_back (const value_type& val);
void push_back (value_type&& val);

它不能调用第二个变体,因为临时 aCell 对象是左值对象。如果它调用第一个变体,则它会推送临时对象aCell,该对象在循环终止时被销毁。

感谢任何对此背后发生的事情的解释。

编辑:由于 Sam Varshavchik 和 songyuanyao 指出的错误,代码已修复

最佳答案

If it calls the first variant, then it push the temporary object aCell, which is destroyed when the loop terminates.

是的,第一个版本被调用,因为 aCell 是一个左值。这很好,因为 push_back ed 元素是从参数复制初始化的;它独立于局部变量 aCell

Appends the given element value to the end of the container.

1) The new element is initialized as a copy of value.

顺便说一句:当在 for 循环中使用 allCells[i] 时,您的代码有未定义的行为,因为 allCells 那时仍然是空的,它没有元素。备注reserve不会更改大小,但会更改 vector 的容量,但是 resize

Board(int width = 10, int height = 10){
bheight = height; bwidth = width;
allCells.reserve(width); // it should be allCells.resize(width) !!
#loop for creating cell objects
for(int i = 0; i < width; i++){
allCells[i].reserve(height);
for(int j = 0; j < height; j++){
Cell aCell(i,j,0); #an object created inside a loop
allCells[i].push_back(aCell); #push it into a vector
}
}
}

关于c++ - 为循环内创建的对象调用哪个 C++ vector push_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732703/

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