从函数返回一个字符串

fis*_*ood 3 c++ string return-value move-semantics c++11

我想编写一个跨平台(win32和linux)的函数,并返回日期时间的字符串表示[hh:mm:ss dd-mm-yyyy].

知道我只是想以流方式将返回的字符串用作临时字符,如下所示:

std::cout << DateTime() << std::endl;
Run Code Online (Sandbox Code Playgroud)

我考虑使用以下原型编写函数

const char* DateTime();
Run Code Online (Sandbox Code Playgroud)

如果返回字符数组,则必须在完成后将其删除.但我只想暂时,我不想担心取消分配字符串.

所以我编写了一个只返回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;
}
Run Code Online (Sandbox Code Playgroud)

我意识到我正在返回DateTime中的堆栈变量的副本.这是低效的,因为我们在DateTime堆栈上创建字符串,填充它,然后返回副本并销毁堆栈上的副本.

c ++ 11移动 - 语义革命是否已经做了任何事情来解决这种低效问题 - 我可以改进吗?

How*_*ant 6

lapin,你的代码是很好的C++ 11代码.在C++ 98/03中,由于编译器优化,您的代码可能会高效,但不保证这些优化.在C++ 11中,那些相同的优化可能仍然可以使你的返回空闲,但是如果他们不这样做,你的字符串将被移动而不是被复制.

所以按价值回报无罪!:-)

次要的:

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

string sValue = ss.str();
return sValue;
Run Code Online (Sandbox Code Playgroud)

或者甚至是:

return ss.str();
Run Code Online (Sandbox Code Playgroud)

但这只是一个小小的问题.您的代码很好,效率很高.


Nev*_*vin 5

另一种方法是使用流插入器使其成为函数对象,如下所示:

struct DateTime()
{
    friend std::ostream& operator<<(std::ostream& os, DateTime)
    {
        time_t t = time(0);
        struct tm * now = localtime(&t);

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

        return os;
    }

    // Could be converted to a static method,
    //  since DateTime has no internal state
    std::string str() const
    {
        // the following 3 lines can be replaced by
        //  return boost::lexical_cast<std::string>(*this);
        std::ostringstream ss;
        ss << *this;
        return ss.str();
    }

    operator std::string() const
    { return str(); }
};
Run Code Online (Sandbox Code Playgroud)