Return std::strftime 的值

Return value of std::strftime

我想我在某处读到,如果我将 nullptr 传递给 std::strftime,该函数将 return 所需的缓冲区大小。事实上,下面的代码在我试过的许多 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 是正确的:

来自 The GNU C Library 的文档:

If s is a null pointer, strftime does not actually write anything, but instead returns the number of characters it would have written.