Click to See Complete Forum and Search --> : why i can't compile this in visual c++ 6
jianmin jin
May 6th, 2003, 01:03 AM
#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;
}
rxbagain
May 6th, 2003, 01:28 AM
#include <string>
using namespace std;
Hope this will help you
jianmin jin
May 6th, 2003, 01:39 AM
Originally posted by rxbagain
#include <string>
using namespace std;
Hope this will help you
thanks a lot :)
Paul McKenzie
May 6th, 2003, 03:42 AM
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
Graham
May 6th, 2003, 04:25 AM
The compiler should cough at the line:
_text = parm.c_str();
since the assignment loses cv-qualifiers.
Also, can I once again point out that leading underscores in names are reserved by the standard for use by compiler and standard library writers only:
Section 17.4.3.1.2:
— Each name that contains a double underscore (_ _) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.