Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign variable to itself on declaration [duplicate]

Tags:

c++

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?

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;
 }
like image 430
Yarik Avatar asked Jul 17 '26 08:07

Yarik


1 Answers

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

like image 104
Artur Soler Avatar answered Jul 19 '26 22:07

Artur Soler