所以我有一个名为 array
的类(class)我想将其作为格式化字符串返回,如下所示:[first, second, third, ..., last]
.现在我写了试图这样做的方法:
std::string& array::to_string()
{
char buffer[1];
std::string s("[");
for (auto &x: *this)
{
if (&x == this->end()) s += _itoa_s(x, buffer, 10) + "]";
else s += _itoa_s(x, buffer, 10) + ",";
}
return s;
}
是的,我已经包含了 <string>
.现在,在我程序的另一部分,我使用 std::cout << myArray.to_string() << '\n'
.我得到的错误(在执行期间)只是 Visual Studio 把我扔到 stdlib.h
标题并显示它的这一部分:
__DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_1(
_Success_(return == 0)
errno_t, _itoa_s,
_In_ int, _Value,
char, _Buffer,
_In_ int, _Radix
)
我做错了什么?
最佳答案
字符串 s
是函数 to_string
的本地字符串,它的析构函数作为 to_string
返回运行,因此返回并使用对已经销毁的字符串会产生未定义的行为。改为按值返回它:
std::string array::to_string() const
{
// a more robust, C++-style implementation...
std::ostringstream oss;
size_t n = 0;
for (const auto& x: *this)
oss << (n++ ? ',' : '[') << x;
oss << ']';
return oss.str();
}
关于c++ - cout 一个返回的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42583630/