对自己调用复制构造函数 [英] Calling copy constructor on yourself

查看:94
本文介绍了对自己调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我几乎是错误地写的这段代码中发生的事情感到好奇:

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

它在gcc中编译,没有任何警告(使用-Wall -Werror) 。
执行它只会打印垃圾。

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

如果我没记错的话,这是在不进行初始化的情况下,对其自身调用隐式复制构造函数。我很好奇复制构造函数在这种情况下会做什么,但是gdb不会在该行停止(设置到该行的断点跳到下一行)。

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

如果将复杂属性添加到类中,一切都会中断(例如 std :: string ),这可能是因为此类类如何重载'='运算符。

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.

我的假设正确吗?为什么gdb不能在那一行停下来?为什么在调用带有未初始化对象的副本构造函数时没有警告?

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

推荐答案

由于您具有类型为<$ c $的成员变量c> int ,其不确定的值被复制到其自身,该代码在技术上是未定义行为。

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.

关于警告,这是实施质量问题。 C ++标准对此无话可说。

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

这篇关于对自己调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆