gpt4 book ai didi

c++ - 字符串文字绑定(bind)到非常量字符指针

转载 作者:搜寻专家 更新时间:2023-10-31 02:09:04 24 4
gpt4 key购买 nike

考虑以下程序:

#include <iostream>

void myprint(const char* fmt, ...)
{
std::cout << "1 ";
}

void myprint(const char* fmt, char *x)
{
std::cout << "2 ";
}

int main()
{
const char* s = "c";
myprint("a", s);
myprint("a", "b");
}

它产生不同的输出:

我的问题有两个方面:

  1. 为什么即使存在 -std=c++14,字符串文字也会绑定(bind)到非常量 char*?从 C++11 开始不是字符串文字 const 吗?

  2. 省略号重载总是排名最低。为什么clang会选择它? (有人会认为它不允许绑定(bind)到 char* 但如果我删除省略号重载,它仍然可以 - demo )

这是怎么回事,谁是对的?

最佳答案

Why does a string literal bind to a non-const char* even in the presence of -std=c++14?

这是一个已弃用的转换,已从 C++11 开始的标准中正式删除。

Isn't a string literal const since C++11?

不,字符串字面值一直是const

The ellipsis-overload is always ranked lowest. Why does clang select it?

因为另一个无效。没有从 const char*char* 的转换,原因与无法转换 const std::string& 的原因相同到 std::string&

因此重载决议会跳过那个并选择唯一剩余的重载(这也恰好是有效的),并打印 1

one would think it doesn't allow binding to char* but if I remove the ellipsis overload, it still does

是的,这是一个非标准扩展,就像 gcc 一样。您应该尝试使用 -pedantic 进行编译。

What's going on and who is right?

clang绝对是对的。不允许扩展修改格式良好的 C++ 程序 ( [intro.compliance]p8 ) 的行为,因此 gcc 和 MSVC 使用第二个重载是错误的,因为标准不支持从 const char* 的隐式转换char*,因此应该回到第一个。

重申一下,您的演示符合标准,因为该程序根据标准(字符串转换)格式不正确,并且他们会发出诊断,因此它不会与上面链接的段落发生冲突。

关于c++ - 字符串文字绑定(bind)到非常量字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46918850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com