why i can't compile this in visual c++ 6
#include <cstring>
class Text
{
public:
void bad( const string &parm ) const;
private:
char *_text;
};
void Text::bad( const string &parm ) const
{
_text = parm.c_str();
for( int ix = 0; ix < parm.size(); ++ix )
_text[ix] = parm[ix];
}
int main( int argc, char **argv)
{
return 0;
}
Re: why i can't compile this in visual c++ 6
Quote:
Originally posted by jianmin jin
void Text::bad( const string &parm ) const
{
_text = parm.c_str();
for( int ix = 0; ix < parm.size(); ++ix )
_text[ix] = parm[ix];
}
jianmin jin,
I hope you called this function "bad", because it is bad.
The code you have here will invoke undefined behavior and is flawed. The problem is that c_str() returns a const char *. This means that you are not allowed to change characters. Your loop changes _text which is pointing to a const char *. Your code may crash, it may work, you don't know.
Regards,
Paul McKenzie