簡體   English   中英

std :: map :: const_iterator泄漏非const引用值?

[英]std::map::const_iterator leaks non-const reference to value?

我觀察到std :: map :: const_iterator泄漏了對value_type的非const引用:

#include <map>
#include <stdio.h>

int main (int argc, char *argv[])
{
  std::map<int,int> foo = {{1,1},{4,2}};
  const auto &m = foo;
  const auto &it = foo.find(1);
  printf("%d %d\n", it->first, it->second);
  int &i = it->second;
  i = 3;
  auto &one = foo.at(1);
  printf("%d %d\n", 1, one);
  return 0;
}

輸出

$ g++ test.cc && ./a.out 
1 1
1 3

這是預期的嗎? 為什么? 編寫std :: map的const-protection的唯一方法是將它包裝在另一個類中嗎?

這一行:

const auto &it = foo.find(1);

創建const referencestd::map<int,int>::iterator命名it ,這樣就可以不修改it本身或它的迭代器指的是,但可以修改它指向(如迭代器)的數據。 它類似於常量指針與指向const數據的指針。 使用m來獲取帶有自動推導類型的std::map<int,int>::const_iterator (它不必是const引用)或者給它顯式類型:

std::map<int,int>::const_iterator it = foo.find(1);

那么你不能通過迭代器修改數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM