使用std :: vector <const char =“”* =“”>错误的赋值效果?</const>

时间:2014-05-19 07:35:10

标签: c++ string c++11 char

错误代码如下:

#include <vector>
#include <string>
#include <iostream>
void foo(const std::vector<double> & in) {
  std::vector<const char *> v(5);
  size_t indx = 0; 
  for(auto & tmp : in) {
    auto temp = std::to_string(tmp);
    v[indx] = temp.c_str();
    std::cout << "right: "<< v[indx] << std::endl;
    indx += 1; 
  }
  std::cout << "wrong: " << v[0] << std::endl;
  std::cout << "wrong: " << v[1] << std::endl;
  std::cout << "wrong: " << v[2] << std::endl;
  std::cout << "wrong: " << v[3] << std::endl;
  std::cout << "wrong: " << v[4] << std::endl;
}

int main(int argc, char *argv[])
{
  std::vector<double> tmp = {0.01, 0.02, 0.03, 0.04, 0.05};
  foo(tmp);
  return 0; 
}

我编译了代码,在for-loop中,打印是正确的,但在外面打印错误,这里有什么问题?

2 个答案:

答案 0 :(得分:1)

错误是std::to_string(tmp)创建了一个临时对象,在分号后立即销毁。所以c_str()指针变为无效。

为什么不使用std::vector<std::string>存储字符串?

std::vector<std::string> v(5);
size_t indx = 0; 
for(auto & tmp : in) {
  v[indx] = std::to_string(tmp);
  std::cout << "right: "<< v[indx] << std::endl;
  indx += 1; 
}

答案 1 :(得分:1)

std::string::c_str()没有给你指向永远存在的字符数组;它为你提供指向直到std::to_string(tmp)死亡的字符数组的指针,这是直接的。

之后尝试访问那些不存在的字符数组是未定义的。

使用std::vector<std::string>取得巨大成功。