|
-
May 6th, 2003, 01:03 AM
#1
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;
}
-
May 6th, 2003, 01:28 AM
#2
Code:
#include <string>
using namespace std;
Hope this will help you
-
May 6th, 2003, 01:39 AM
#3
Originally posted by rxbagain
Code:
#include <string>
using namespace std;
Hope this will help you
thanks a lot
-
May 6th, 2003, 03:42 AM
#4
Re: why i can't compile this in visual c++ 6
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
Last edited by Paul McKenzie; May 6th, 2003 at 03:45 AM.
-
May 6th, 2003, 04:25 AM
#5
The compiler should cough at the line:
Code:
_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.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|