std::strftime的返回值

Return value of std::strftime

本文关键字:返回值 strftime std      更新时间:2023-10-16

我想我在某处读到,如果我传递一个nullptr给std::strftime,该函数将返回所需的缓冲区大小。事实上,下面的代码在我尝试过的许多linux系统上都能很好地工作(虽然不是用VS编译时):

#include <iostream>
#include <ctime>
#include <string>
int main()
{
    std::time_t time{};
    std::tm const * ltime = std::localtime(&time);
    const char * formatString = "%Y-%b-%d";
    //allocate buffer of appropriate size
    auto requiredSize = 1 + std::strftime(nullptr, 50, formatString, ltime);
    std::cout << "Required buffer size:" << requiredSize << "n";
    //Format time to string
    std::string buff(requiredSize, ' ');
    std::strftime(&buff[0], requiredSize, formatString, ltime);
    std::cout << buff << std::endl;
}

然而,我无法找到我的原始源代码或任何其他文档来指定此行为。所以我的问题是:

  • 在哪些系统/编译器/标准库实现(如果有的话)这是一个保证的行为?
  • 哪里可以找到相应的文档?

编辑:我添加了C标签,因为我在等效的C代码中看到了相同的结果,至少在gcc/g++(或者更确切地说是glibc/libstdc++) std::strftime可能只是C函数strftime的别名。

据我所知,正如其他人在评论中所写的,上面的代码很可能是根据ISO C或c++标准未定义的行为,就我自己的实验而言,在VS2015编译时会崩溃。

然而,就glibc而言,@rici是正确的:

来自GNU C库的文档:

如果s是空指针,strftime实际上不写任何东西,而是返回它应该写的字符数。