std ::矢量引用将在.insert()上复制
std::vector references being copied on .insert()
我正在尝试此代码,但是不断发生的事情是,当我插入向量时,引用不会更改。例如,在第一个插入矢量中,所有11个元素都将平均更改,包括temp_word。这是预期的行为吗?
std::cout << "Searching for the top 10 scrabble scores" << std::endl;
Word temp_word;
std::vector<std::pair<Word&, unsigned>> word_scores;
for(unsigned x = 0; x < 10; ++x)
word_scores.push_back({temp_word, 0});
for(Word& word : dict.words()){
auto score = word.CalculateScrabbleScore();
for(unsigned x = 0; x < 10; ++x){
if(word_scores[x].second <= score){
// Insert into the list of scores
word_scores.insert(word_scores.begin() + x, {word , score});
// Remove what was pushed off the list
word_scores.erase(word_scores.begin() + 10);
break;
}
}
}
当std::pair
包含参考类型的成员时,其复制构造函数与其分配运算符之间存在非常明显的区别。考虑:
int n = 42;
std::pair<int&, int> p1{n, 0};
std::pair<int&, int> p2(p1);
assert(&p1.first == &p2.first);
p1.first
和p2.first
现在参考n
。比较和对比:
int n = 42;
std::pair<int&, int> p1{n, 0};
int m = 84;
std::pair<int&, int> p2{m, 0};
p2 = p1;
assert(m == n);
p1.first
仍然是指n
,p2.first
仍然是指m
,但现在m
的值与n
相同。
初始化时的引用是绑定的,之后不能反弹。分配给引用实际分配给基础对象。
vector::insert
可以合法地使用复制构造函数,分配运算符或两个组合的任何组合来移动元素。在您的示例中发生的事情是vector::insert
首先将元素移开(可能是通过分配,但这并不重要),然后分配给"空"点。但是这个位置并不是真正的空位 - 它仍然具有其原始元素。正是在此任务中,temp_word
被修改,就像我之前的示例中p2 = p1;
修改m
一样。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 复制列表初始化的隐式转换的等级是多少
- 当从函数参数中的临时值调用复制构造函数时
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 复制几乎为空的数组的最快方法
- Insert函数不适用于2 if语句C++
- 以下示例中如何避免代码复制?C++/库达
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- std::map insert && hyperload 导致复制
- std ::矢量引用将在.insert()上复制
- 为什么std::vector::insert需要复制赋值
- Std::set::insert:使用用户定义类复制
- fill-insert()-复制构造函数和复制赋值noexcept状态
- 为什么map.insert()方法调用复制构造函数两次?