从函数返回一个字符串 [英] returning a string from a function

查看:186
本文介绍了从函数返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个跨平台的函数(win32& linux),并返回datetime的字符串表示形式[hh:mm:ss dd-mm-yyyy]。

I wanted to write a function that'll be cross platform (win32 & linux), and return a string representation of the datetime [hh:mm:ss dd-mm-yyyy].

知道我只想使用返回的字符串作为临时流如下所示:

Knowing that I just want to use the returned string as a temporary in a stream fashion as below:

std::cout << DateTime() << std::endl;

我考虑用以下原型写一个函数

I considered writing a function with the following prototype

const char* DateTime();

如果返回字符数组,必须在完成后将其删除。但我只想要一个临时的,我不想担心取消分配字符串。

If you return a character array, you must delete it once you're done. But I just want a temporary, I don't want to have to worry about de-allocating the string.

所以我写了一个函数,只返回一个std :: string:

So I've written a function that just returns an std::string:

#include <ctime>
#include <string>
#include <sstream>

std::string DateTime()
{
    using namespace std;

    stringstream ss;
    string sValue;
    time_t t = time(0);
    struct tm * now = localtime(&t);

    ss << now->tm_hour << ":";
    ss << now->tm_min << ":";
    ss << now->tm_sec << " ";
    ss << now->tm_mday + 1 << " ";
    ss << now->tm_mon + 1 << " ";
    ss << now->tm_year + 1900;

    sValue = ss.str();

    return sValue;
}


$ b $ p我意识到我在DateTime中返回一个堆栈变量的副本。这是没有效率的,因为我们在DateTime堆栈上创建字符串,填充它,然后返回一个副本并销毁堆栈上的副本。

I realize that I'm returning a copy of the stack variable in DateTime. This is inefficient in that we create the string on the DateTime stack, populate it, then return a copy and destroy the copy on the stack.

有c ++ 11移动语义革命做了什么来解决这种低效率 - 我可以改进这个吗?

Has the c++11 move-semantics revolution done anything to resolve this inefficiency - can I improve upon this?

推荐答案

+11代码。在C ++ 98/03中,由于编译器优化,您的代码可能会 效率很高,但这些优化不能保证。在C ++ 11中,这些相同的优化可能仍然使您的返回免费,但是如果没有,您的字符串将被移动,而不是复制。

lapin, your code is fine C++11 code. In C++98/03 your code will probably be efficient due to compiler optimizations, but those optimizations aren't guaranteed. In C++11, those same optimizations will probably still make your return free, but just in case they don't, your string will be moved instead of copied.

所以返回值无罪! : - )

So return by value guilt-free! :-)

次要:

最好的做法是在首次使用时声明您的值,而不是在块的顶部:

It is best practice to declare your values at the point of first use, instead of at the top of a block:

string sValue = ss.str();
return sValue;

或者甚至:

return ss.str();

但这只是一个小小的。您的代码效果很好

But this is just a minor nit. Your code is fine and efficient.

这篇关于从函数返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆