Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is self-initialization 'A a = a;' allowed?

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 543
Yarik Avatar asked Jun 11 '09 15:06

Yarik


People also ask

What is self initialization?

In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Python doesn't force you on using "self". You can give it any name you want. But remember the first argument in a method definition is a reference to the object.

How to initialize an object in Swift?

An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }


1 Answers

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

like image 112
Artur Soler Avatar answered Oct 19 '22 01:10

Artur Soler