std ::矢量引用将在.insert()上复制

std::vector references being copied on .insert()

本文关键字:复制 insert 引用 std      更新时间:2023-10-16

我正在尝试此代码,但是不断发生的事情是,当我插入向量时,引用不会更改。例如,在第一个插入矢量中,所有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.firstp2.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仍然是指np2.first仍然是指m,但现在m的值与n相同。

初始化时的引用是绑定的,之后不能反弹。分配给引用实际分配给基础对象。

vector::insert可以合法地使用复制构造函数,分配运算符或两个组合的任何组合来移动元素。在您的示例中发生的事情是vector::insert首先将元素移开(可能是通过分配,但这并不重要),然后分配给"空"点。但是这个位置并不是真正的空位 - 它仍然具有其原始元素。正是在此任务中,temp_word被修改,就像我之前的示例中p2 = p1;修改m一样。