是自初始化'A a = a;'允许? [英] Is self-initialization 'A a = a;' allowed?

查看:121
本文介绍了是自初始化'A a = a;'允许?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在运行时在复制构造函数中失败。

但是编译器(MSVS2008)不会发出警告。

This code fails at runtime in the copy constructor.
But the compiler (MSVS2008) issues no warnings.

引用标准)这段代码是非法还是什么?

Could you explain (preferably cite the standard) whether this code is illegal or what?

我明白A a = a;不应该写在第一个地方,
,但我正在寻找理论背景。

I understand that A a = a; should never be written at the first place, but I am looking for a theoretical background.

 class A
 {
 public: 

    A()
    :p(new int)
    {
    }

    A(const A& rv)
    {
        p = new int(*rv.p);
    }

    ~A()
    {
        delete p;
    }


 private:

    int *p;
 };

 int main()
 {
    A a = a;
 }


推荐答案

您的代码不会调用标准构造函数,但是复制构造函数,因此您正在访问未初始化的指针。

Your code is not calling the standard constructor but the copy constructor, so you are accessing an uninitialized pointer.

这篇关于是自初始化'A a = a;'允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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