为什么参数中默认的char*必须是const?
Why is the default char* in a parameter must be const?
class MyString {
private:
char *m_pchString;
int m_nLength;
public:
MyString(char* pchString="0") { //problem on this parameter
m_nLength = strlen(pchString)+1;
m_pchString = new char[m_nLength];
strncpy(m_pchString, pchString, m_nLength);
m_pchString[m_nLength-1] = 0;
}
~MyString() {
delete[] m_pchString;
m_pchString = 0;
}
char* GetString() {return m_pchString;}
int GetLength() {return m_nLength;}
};
如果我遵守了这个,编译器会给我一个警告:
warning: deprecated conversion from string constant to 'char*'
除非我将参数从char *pchString = "0"
修改为const char *pchString = "0"
为什么参数中默认的char*必须是const?
原因是与使用字符串 class 相比,char* 被认为是一种过时的做法。
因为像 "some string"
这样的字符串文字是不可变的,并且尝试修改一个(如果通过非常量引用传递,您可以尝试修改它们)会导致未定义的行为。这就是标准 C++ 弃用此转换的原因。
试试这个好玩的(但请不要在生产代码中),实时 here:
#include <iostream>
int main()
{
char* str = "test";
str[0] = 'w';
std::cout << str; // oops
}
相关:Why are string literals const?
当您使用字符串文字时,例如"0"
,它被放入程序的只读部分。对此类数据进行任何更改都会导致未定义的行为。通过尝试将 char*
类型的变量初始化为字符串文字,您允许修改只读数据的可能性。这就是编译器所抱怨的。
类似于:
const int num;
int* ptr = # // Wrong
class MyString {
private:
char *m_pchString;
int m_nLength;
public:
MyString(char* pchString="0") { //problem on this parameter
m_nLength = strlen(pchString)+1;
m_pchString = new char[m_nLength];
strncpy(m_pchString, pchString, m_nLength);
m_pchString[m_nLength-1] = 0;
}
~MyString() {
delete[] m_pchString;
m_pchString = 0;
}
char* GetString() {return m_pchString;}
int GetLength() {return m_nLength;}
};
如果我遵守了这个,编译器会给我一个警告:
warning: deprecated conversion from string constant to 'char*'
除非我将参数从char *pchString = "0"
修改为const char *pchString = "0"
为什么参数中默认的char*必须是const?
原因是与使用字符串 class 相比,char* 被认为是一种过时的做法。
因为像 "some string"
这样的字符串文字是不可变的,并且尝试修改一个(如果通过非常量引用传递,您可以尝试修改它们)会导致未定义的行为。这就是标准 C++ 弃用此转换的原因。
试试这个好玩的(但请不要在生产代码中),实时 here:
#include <iostream>
int main()
{
char* str = "test";
str[0] = 'w';
std::cout << str; // oops
}
相关:Why are string literals const?
当您使用字符串文字时,例如"0"
,它被放入程序的只读部分。对此类数据进行任何更改都会导致未定义的行为。通过尝试将 char*
类型的变量初始化为字符串文字,您允许修改只读数据的可能性。这就是编译器所抱怨的。
类似于:
const int num;
int* ptr = # // Wrong