std::string x(x);
这在我的编译器上崩溃得非常严重。这是否意味着我应该this != &that
在自己的复制构造函数中进行测试,或者我可以假设没有客户会如此愚蠢?
std::string x(x);
这在我的编译器上崩溃得非常严重。这是否意味着我应该this != &that
在自己的复制构造函数中进行测试,或者我可以假设没有客户会如此愚蠢?
您不应该针对试图严重崩溃的代码进行测试。请参阅空引用。它说
“就像你必须假设一个非空指针是有效的一样,你必须假设一个引用是有效的。你必须对你的程序员伙伴有信心。”
我要补充
...您必须假设副本的来源是有效的。
如果你“修复”你的案子,这个案子该怎么办?
string x = string(x);
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.
根据标准,该代码不正确,检查它没有意义,可能发生的最好的事情是快速失败,以便用户可以更正他们的代码。