Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

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

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;
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...