std::strftime的返回值
Return value of std::strftime
我想我在某处读到,如果我传递一个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实际上不写任何东西,而是返回它应该写的字符数。
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 程序不向函数返回值
- 如何在另一个函数中使用返回值作为参数?
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 使用 std::p air 进行返回值优化
- std::strftime的返回值