c++ - std::strftime 的返回值

标签 c++ c glibc

我想我在某处读到,如果我将 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 是正确的:

来自 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.

关于c++ - std::strftime 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131893/

相关文章:

c++ - 使用 boost::serialization 序列化 TAO/CORBA 对象

c - 尝试掌握 C 字节码...GNU/gcc 是否/可以像 Clang/LLVM 一样生成 C 字节码?

select - 增加 FD_SETSIZE

c - *** 检测到 glibc *** realloc() : invalid old size

不能在输出流上使用 fclose,输入流没问题

c++ - SDL_Net 套接字创建时出错

c++ - C++17 中的 constexpr 容器是什么?

c++ - 如何从十六进制值缓冲区渲染矩形 SDL2 纹理?

c - printf 未知精确类型的整数

创建随机大小 [1...500] KB 的文件