tags:

views:

165

answers:

3

The title says it all, and whilst the 'standards' are to prefer a sizeof(typename), are there any instances where the sizeof(*this) is more error-prone or somehow undesirable?

I cannot see any at the first glance, but if yes, why with a short explanation would be helpful.

Thanks.

+8  A: 

I prefer sizeof(variable) over sizeof(type) wherever possible since it's less error prone, in case your variable changes type.

Grumdrig
+8  A: 

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

Tim Sylvester
+3  A: 

My view is that sizeof( type ) is preferable to sizeof( variable ) in order to preclude ambiguity. The following example shows an instance of a derived class referenced through a base class pointer. The size method returns sizeof( Derived ) so sz1 == sz3 == sz4. The caller could reasonably expect sizeof( Base ) if they have no insight into 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() ;
}
William Bell
But then it might be more useful to know the size of the real type? - P.S The `reinterpret_cast` looks suspicious and if it does the right thing - preserving the type of `*pb` as Derived? - is entirely unneeded for upcast.
UncleBens
You must use sizeof( variable ) when the size of the real type is needed. The point is that it is preferable to use sizeof( type ) to obtain the size of a specific class to avoid that effect. (You are correct that the cast is superfluous, I have edited it out)
William Bell