cout 一个返回的字符串
cout a returned string
所以我的 class 叫做 array
,我想 return 它作为一个格式化的字符串,像这样:[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
header 并显示它的这一部分:
__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
returns 运行,因此返回并使用对已析构的引用字符串创建 未定义的行为 。 Return 它 按值 代替:
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();
}
您正在return引用本地对象。因此,您尝试使用已从堆栈中释放的对象。从函数签名中删除 &
到 return 它的值。
您正在 return 引用 std::string 范围内的 array::to_string()
方法。
当方法退出时,局部 s
变量超出范围,因此它被销毁,导致“dangling reference”被 returned。
您应该 return 字符串值:
std::string array::to_string()
或将其作为参考参数传递:
void array::to_string(std::string& result)
所以我的 class 叫做 array
,我想 return 它作为一个格式化的字符串,像这样:[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
header 并显示它的这一部分:
__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
returns 运行,因此返回并使用对已析构的引用字符串创建 未定义的行为 。 Return 它 按值 代替:
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();
}
您正在return引用本地对象。因此,您尝试使用已从堆栈中释放的对象。从函数签名中删除 &
到 return 它的值。
您正在 return 引用 std::string 范围内的 array::to_string()
方法。
当方法退出时,局部 s
变量超出范围,因此它被销毁,导致“dangling reference”被 returned。
您应该 return 字符串值:
std::string array::to_string()
或将其作为参考参数传递:
void array::to_string(std::string& result)