C ++代码可能的问题

时间:2014-10-31 11:47:30

标签: c++

下面的代码中是否有任何错误?

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>


int main()
{
  std::vector<std::string> myVector;

  myVector.push_back("one");
  myVector.push_back("two");
  myVector.push_back("three");
  myVector.push_back("four");
  myVector.push_back("five");

  std::sort(myVector.begin(),myVector.end(),std::less_equal<std::string>());
  std::string& str = myVector.back();

  std::cout << str << std::endl;

  std::vector<std::string>::const_iterator it = myVector.begin();

  myVector.push_back("six");
  myVector.push_back("seven");

  std::cout << *it << std::endl;

  return 0; 
}

我只能通过将向量的最后一个元素的地址分配给str来表示,这意味着如果删除该元素,则str为空,这可能导致不期望的行为,甚至是运行时问题。

1 个答案:

答案 0 :(得分:2)

是的,问题在于这一行:

std::cout << *it << std::endl;

在几个push_back之后出现。由于vector可以调整大小,因此可能在保存迭代器和添加更多元素之间,容器必须分配更多内存。如果它必须,那么你的迭代器将指向一个不再属于vector的元素。它可能看起来不太明显,但你有[潜在]悬挂指针。

同样如下:

std::string& str = myVector.back();

push_back之后,该引用可能会失效。