我希望编写一个跨平台的函数(win32和linux),返回日期时间的字符串表示形式[hh:mm:ss dd-mm-yyyy]。我只是想将返回的字符串作为流式传输中的临时变量使用,如下所示:
我考虑编写一个具有以下原型的函数。
如果你返回一个字符数组,你必须在使用完后删除它。但是我只想要一个临时的字符串,我不想担心释放它。
所以我写了一个函数,它只返回一个std::string:
std::cout << DateTime() << std::endl;
我考虑编写一个具有以下原型的函数。
const char* DateTime();
如果你返回一个字符数组,你必须在使用完后删除它。但是我只想要一个临时的字符串,我不想担心释放它。
所以我写了一个函数,它只返回一个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;
}
我意识到在DateTime中返回堆栈变量的副本。这是效率低下的,因为我们在DateTime堆栈上创建字符串,填充它,然后返回一个副本并销毁堆栈上的副本。
c++11的移动语义革命是否对解决此效率问题有所帮助 - 我能否改进这个问题?
-1
,因为tm_mday
是基于 1 的。 - Alexey Frunze