std::string x(x);

允我心安 提交于 2019-11-28 07:21:44

问题


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?


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2529111/stdstring-xx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!