c++ - 将 double 转换为字符串函数 - 内存问题?

标签 c++ double stdstring memory-efficient

我发现自己不得不 std::cout 各种 double 变量。 我做了一个简单的函数来将 double 转换为 std::string,然后我可以将其与 std::cout 等一起使用。

// Convert a double to a string.
std::string dtos(double x) {
    std::stringstream s;
    s << x;
    return s.str();
}

该函数似乎工作正常,但我的问题是:这种方法是否有任何(坏的)内存影响,即。我是在分配不必要的内存,还是留下任何“悬空”的东西?

谢谢大家 皮特

最佳答案

不,你的代码没问题,阅读代码注释:

std::string dtos(double x) {
    std::stringstream s;  // Allocates memory on stack
    s << x;
    return s.str();       // returns a s.str() as a string by value
                          // Frees allocated memory of s
} 

此外,您可以将double 直接传递给cout

关于c++ - 将 double 转换为字符串函数 - 内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16117528/

相关文章:

c++ - 我应该将有内存泄漏的库转换为 C++11 的智能指针吗?

c++ - 如何知道 Gtk::ComboBoxText 是否弹出

c++ - 如何在处理传统 C 字符串的 C 风格函数中有效地使用 std::string?

c++ - 搜索不同于 "X"的第一个字符的字符串

c++ - 奇怪的 winAPI 行为

C++ 用户输入 float 而不是整数

Java : How to count the number of decimals contained in a double value that represent money?

c++ - GNU C++ 中程序的奇怪行为,使用 float

android - 致命异常 : java. lang.NumberFormatException

c++ - 如何将字符串添加到 vector (并随后显示它)?