Calling copy constructor on yourself

青春壹個敷衍的年華 提交于 2019-12-20 02:28:41

问题


I am curious about what is happening in this code I wrote almost by mistake:

#include <iostream>

class Test
{
public:
  Test() {
    std::cout << "Default constructor";
    a= 10;
  }
  int a;
};

int main() {
  Test obj(obj);
  std::cout << obj.a << std::endl;
}

It compiles in gcc without warnings of any kind (using -Wall -Werror). Executing it only prints garbage.

If I am not mistaken, this is calling the implicit copy-constructor on itself, without ever initialising. I am curious about what the copy-constructor would do in such a situation, but gdb will not stop in that line (breakpoints set to that line jump to the next one).

Everything breaks if "complex" attributes are added to the class (like a std::string), probably because of how the '=' operator is overloaded for such classes.

Is my hypothesis correct? Why doesn't gdb stop in that line? Why no warnings when calling a copy constructor with an uninitialised object?


回答1:


Since you have a member variable of type int, whose indeterminate value is copied to itself, the code is technically Undefined Behavior.

However, in practice, with current computers nothing bad will happen. But on the third hand, nothing good happens either.

Regarding warnings, that's a Quality Of Implementation issue. The C++ standard has nothing to say about that.



来源:https://stackoverflow.com/questions/28590937/calling-copy-constructor-on-yourself

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