クロス プラットフォーム (win32 & linux) になる関数を作成し、日時 [hh:mm:ss dd-mm-yyyy] の文字列表現を返したいと思いました。
以下のように、返された文字列をストリーム形式で一時的に使用したいだけであることを知っています。
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 の移動セマンティクス革命は、この非効率性を解決するために何かをしましたか? これを改善できますか?