Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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);

That code is not correct according to the standard and it does not make sense to check it and the best thing that can happen is a fast failure so that the user can correct their code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top