gpt4 book ai didi

c++ - 强制转换为模板中的引用似乎抛弃了 const-ness

转载 作者:可可西里 更新时间:2023-11-01 17:57:44 27 4
gpt4 key购买 nike

考虑以下 C++ 代码:

typedef std::string& mutable_string_ref;
const std::string str = "abc";
mutable_string_ref ref(str);

这显然会导致编译器错误,因为您无法创建对常量字符串的可变引用。对于 GCC 4.7.2,产生的错误是:

error: invalid initialization of reference of type ‘mutable_string_ref {aka std::basic_string<char>&}’ from expression of type ‘const string {aka const std::basic_string<char>}’


但是...为什么如果我们尝试同样的事情,只是我们将引用类型作为模板参数传递,突然间它似乎忽略了常量-性?

考虑:

template <class T>
T get()
{
const static std::string s = "abc";
return T(s);
}

int main()
{
std::string& s = get<std::string&>();
s = "blah"; // undefined behavior!!
}

以上代码在 GCC 4.7.2 上编译良好,没有警告。我不明白为什么要编译。似乎表达式 T(s) 基本上被解释为 C 风格的强制转换,只是抛弃了 const-ness。但为什么?我用 T = std::string& 实例化了函数模板 get,所以表达式 return T(s) 应该无法编译,因为 sconst。然而它并没有失败。

Ideone 链接:http://ideone.com/TAO5C6

这是编译器错误吗?还是有一些合理的理由可以编译?

最佳答案

你不是在初始化,你是 C 风格的转换,它确实有能力抛弃 constness。

来自标准:

5.2.3 Explicit type conversion (functional notation) [expr.type.conv]

1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).

5.4 Explicit type conversion (cast notation)

1 The result of the expression (T) cast-expression is of type T. [...]

关于c++ - 强制转换为模板中的引用似乎抛弃了 const-ness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973064/

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