Sizeof (* this) in header constructor implementation only

While “standards” should prefer a sizeof(typename), are there cases where it is sizeof(*this)more error prone or somehow undesirable?

I do not see a single one at first glance, but if so, why with a short explanation would be useful.

+3
source share
3 answers

The only reason I can think, to avoid sizeof(*this), is that it could be misunderstood as the size of an actual object (like a derived class).

+10
source

sizeof(variable) sizeof(type), , , .

+8

My opinion is that sizeof (type) is preferable to sizeof (variable) in order to avoid ambiguity. The following example shows an instance of a derived class that is referenced by a base class pointer. The size method returns sizeof (Derived), so sz1 == sz3 == sz4. The caller can reasonably expect sizeof (Base) if they have no understanding of the implementation.

class Base
{
  public:
    virtual size_t size( void )
    {
        return sizeof( *this ) ;
    }
  private:
    int    a ;
    double b ;
} ;

class Derived : public Base
{
  public:
    virtual size_t size( void )
    {
        return sizeof( *this ) ;
    }
  private:
    long c ;
  } ;

int main( int argc , char * argv[] )
{
    Base    b ;
    Derived d ;

    size_t sz0 = sizeof( Base ) ;
    size_t sz1 = sizeof( Derived ) ;
    size_t sz2 = b.size() ;
    size_t sz3 = d.size() ;

    Base * pb = &d ;
    size_t sz4 = pb->size() ;
}
+3
source

Source: https://habr.com/ru/post/1722502/


All Articles