我从朋友那里得到了这个问题
#include <string>
#include <vector>
#include <iostream>
void riddle(std::string input)
{
auto strings = std::vector<std::string>{};
strings.push_back(input);
auto raw = strings[0].c_str();
strings.emplace_back("dummy");
std::cout << raw << "\n";
}
int main()
{
riddle("Hello world of!"); // Why does this print garbage?
//riddle("Always look at the bright side of life!"); // And why doesn't this?
std::cin.get();
}
我的第一个观察是,当传入的单词数超过 3 个单词riddle()
时,该函数不会产生垃圾。input
我仍在试图了解为什么它在第一种情况下失败,而不是在第二种情况下。不管怎样,我觉得分享这个很有趣。