用字符串文字初始化非const参数 [英] Initializing non-const parameter with string literal
问题描述
所以我有这个代码:
class ConstTest {
public:
explicit ConstTest(char* name) {}
};
int main() {
ConstTest t("blarghgh");
}
显然编译,即使我认为它不应该。由于C ++中的字符串文字具有类型 const char []
和 ConstTest
构造函数需要一个const- < c> char * - not const char *
。并且通过C ++隐式生成 const
指向非const常量的指针。
It obviously compiles, even though I thought that it shouldn't. As string literals in C++ have type const char[]
, and ConstTest
constructor requires a const-less char*
— not const char*
. And casting a const
pointer to a non-const one isn't something usually done by C++ implicitly.
,我错了?为什么要编译?我可以在构造函数中合法修改取消引用的指针吗?
So, where I'm wrong? Why it's compiling? Can I legally modify the dereferenced pointer inside the constructor?!
推荐答案
错误?为什么要编译?
So, where I'm wrong? Why it's compiling?
这是编译,因为你的编译器太宽容,而且你的编译器太宽容了,因为在C ++ 03从字符串字面值到 char *
的隐式转换仅被 废弃,无效。
It is compiling because your compiler is too permissive, and your compiler is too permissive because in C++03 the implicit conversion from a string literal to char*
was only deprecated, not invalid.
原理是向后兼容旧版C API。按照C ++ 03标准的第4.2 / 2节:
The rationale was backward compatibility with legacy C APIs. Per paragraph 4.2/2 of the C++03 Standard:
字符串文字(2.13.4)可以转换为类型的指针
char
的右值;一个宽字符串文字可以转换为指向wchar_t
类型的右值。在任何一种情况下,
的结果都是指向数组的第一个元素的指针。只有当有一个
显式的适当的指针目标类型,而不是一般需要从一个左值转换到一个
值时,才会考虑这种转换。 [ 注意:此转化已弃用。请参阅附录D。]
A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type "pointer to
char
"; a wide string literal can be converted to an rvalue of type "pointer towchar_t
". In either case, the result is a pointer to the first element of the array. This conversion is considered only when there is an explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an rvalue. [Note: this conversion is deprecated. See Annex D.]
然而,在C ++ 11中,隐式转换是非法的
In C++11, however, the implicit conversion is illegal (the above paragraph has been removed altogether).
我可以在构造函数中合法解引用和修改指针吗?!
Can I legally dereference-and-modify the pointer inside the constructor?!
可以,但不能修改取消引用的对象。这样做是未定义的行为,因为对象的类型是 const
-qualified。
You can, but you cannot modify the dereferenced object. Doing so would be undefined behavior, since the type of the object is const
-qualified.
这篇关于用字符串文字初始化非const参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!