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

前端 未结 4 639
半阙折子戏
半阙折子戏 2020-12-01 21:46

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

相关标签:
4条回答
  • 2020-12-01 22:20

    According to the standard (12.6.1 [class.expl.init] ) self initialization is perfectly legal.

    Therefore the following is legal.

    A a = a;
    

    You just need to write your copy constructor to deal with it correctly.

    A(const A& rv)
    {
        if(&rv == this) {
            p = new int(0);
            return;
        }
    
        p = new int(*rv.p);
    }
    

    Edit: Updated code based on comments.

    0 讨论(0)
  • 2020-12-01 22:27

    Interesting reading on self-assignment: http://www.gotw.ca/gotw/011.htm

    In particular, note "Postscript #1" in relation to this question and some of the answers given.

    0 讨论(0)
  • 2020-12-01 22:28

    A a = a; definitely should not be written. But a = a could be written. Your assignment operator must check for &rv == this and do nothing in case of a self-copy.

    Oh, yes, you do need to write an assignment operator for class A.

    0 讨论(0)
  • 2020-12-01 22:36

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

    0 讨论(0)
提交回复
热议问题