简体   繁体   English

Stringstream到Vector <char> 抛出std :: bad_alloc

[英]Stringstream to Vector<char> throws std::bad_alloc

I was tinkering with Boost Property Tree a bit, and I came across this example. 我稍微修改了Boost属性树,然后遇到了这个示例。 I needed to convert the final result to vector, so I just added one more line after 我需要将最终结果转换为矢量,所以我只在之后添加了一行

write_json(ss, root);

like this: 像这样:

std::vector<char> testVec(std::begin(ss.str()), std::end(ss.str()));

I have also tried this instead: 我也尝试过这样:

std::string someString = ss.str()
char* someArray = (char*)someString.c_str();
std::vector<char> someVec(someArray, someArray+sizeof(someArray));

In both the cases, I am getting this error: 在两种情况下,我都会收到此错误:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc

Any hints what I am doing wrong? 有什么提示我做错了吗? It is not a problem of property tree, I gather. 我搜集到,这不是财产树的问题。 It is a problem of string to vector conversion. 这是字符串到向量转换的问题。 I guess this makes sense, because vectors are only supposed to be one dimensional, but I have no clue how to convert that string to vector and get it back again. 我猜这是有道理的,因为矢量只应该是一维的,但是我不知道如何将字符串转换为矢量并将其重新取回。

This fails: 这将失败:

std::vector<char> testVec(std::begin(ss.str()), std::end(ss.str())); 

because the std::begin() and std::end() are not associated with same std::string instance. 因为std::begin()std::end()没有与同一个std::string实例关联。 The ss.str() returns a new std::string instance each time, it does not return a std::string& to some internal member. ss.str()每次都会返回一个新的std::string实例,但不会向某个内部成员返回std::string&

This is incorrect: 这是不正确的:

std::vector<char> someVec(someArray, someArray+sizeof(someArray)); 

because sizeof(someArray) is sizeof(char*) . 因为sizeof(someArray)sizeof(char*) If there is less than sizeof(char*) elements in someArray an attempt will be made to read memory that should not. 如果someArray的元素少于sizeof(char*) ,将尝试读取不应该的内存。

A possible solution: 可能的解决方案:

std::string someString = ss.str();
std::vector<char> someVec(someString.begin(), someString.end());

sizeof() isn't giving you the length of the array, because c strings don't know their length (null-terminated). sizeof()不能给你数组的长度,因为c字符串不知道它们的长度(以null结尾)。 It's just providing the size of the memory location for the pointer at the beginning of the array, which is why you can reference past the end of the string using operator[] if you're not careful. 它只是在数组的开头提供指针的内存位置大小,这就是为什么如果您不小心,可以使用operator []来引用字符串末尾的原因。

Another solution is to overload sizeof to iterate through the string until it hits the null terminator, but that seems like something you could do with built in things without going through the extra work. 另一个解决方案是重载size​​of以遍历字符串,直到到达空终止符为止,但这似乎可以用内置的东西来完成,而无需执行额外的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM