Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string x(x);

std::string x(x);

This crashes very badly on my compiler. Does this mean I should test for this != &that in my own copy constructors, or can I assume that no client will ever be so stupid?

like image 832
fredoverflow Avatar asked Mar 27 '10 11:03

fredoverflow


2 Answers

You should not test against code that tries to crash badly. See Null References. It says

"Just as you must assume that a non-null pointer is valid, you must assume that a reference is valid. You must have faith in your fellow programmers."

I want to complement

... you must assume that the source of a copy is valid.

If you "fix" your case, what to do for this one?

string x = string(x);
like image 107
Johannes Schaub - litb Avatar answered Sep 26 '22 02:09

Johannes Schaub - litb


Initializing something with itself is undefined behavior, which probably might even mean that once it is invoked you even can't detect it later. Suppose the compiler detects it and out of spite generates assembly for nasal demons, not a call to your copy constructor at all?

In practice, you can assume that the client is not that stupid, and if they are it is their business to debug it and figure it out.

like image 33
UncleBens Avatar answered Sep 25 '22 02:09

UncleBens