C++, Classes, Const, and strange syntax

后端 未结 8 2069
广开言路
广开言路 2020-12-18 02:14

I was re-reading c++ primer(4th ed.) today - the section on member functions and const references etc, and I came up with this wierd little program:

using st         


        
8条回答
  •  隐瞒了意图╮
    2020-12-18 02:31

    I'd say the answer by Tony that you marked as correct is incorrect, and the answer by Michael Burr is correct.

    To put what he said more clearly (for me at least):

    There are two potential places for misunderstanding:

    1. The way implicit const works
    2. The way that this is interpreted during construction of a const object

    1. Implicit Const

    Implicit const (the constification internal to ConstCheater when it is made const) doesn't turn cc into a pointer-to-const but rather a const-pointer, that is to say when you do this:

      const ConstCheater cc(7); 
    

    Internally goes from:

      ConstCheater * ccp;
    

    ...to...

      ConstCheater * const ccp;
    

    ...rather than the...

      const ConstCheater * ccp;    
    

    that may have been expected.

    2. Construction of const object

    The stranger thing is though is that this is allowed to be passed to cpp's initializer in the constructor since this, one would think, should be treated as a pointer-to-const, and thus not a valid value to pass to a const-pointer.

    That is to say one might expect:

     ...: ccp(this) ... // expected to fail but doesnt
    

    to fail because conceptually you might expect that this was (somewhat) equivalent to:

     const ConstCheater         cc(7);
     const ConstCheater * const this = &cc; // const-pointer-to-const
    

    and thus you would think that:

     ConstCheater * const ccp = this; //expected error!
    

    would fail! But it doesn't because apparently during construction apparently this is treated specially as if it was:

     const ConstCheater * this = &cc; 
    

    and thus the object is effectively not const during construction.

    I'm not sure I understand completely the reasoning, but Michael Burr points out there appears to be a logical and technical barrier to providing the expected behavior so the standard seems to carve out the current somewhat odd behavior.

    I recently asked a related question which was: Why does C++ not have a const constructor? but thus far haven't really understood completely the reasoning why it would be untenable, though I suppose it would place a burden on C++ developers to have to define an awkward const constructor for any class they'd like to create const object of.

提交回复
热议问题