views:

366

answers:

4

Can someone explain the following code snippet for me?

// Bind base object so we can compute offsets
// currently only implemented for indexes.
template<class DataObj> void BindAsBase(DataObj &rowbuf)
{
    // Attempting to assign working_type first guarantees exception safety.
    working_type = DTL_TYPEID_NAME (rowbuf);
    working_addr = reinterpret_cast<BYTE*>(&rowbuf);
    working_size = sizeof(rowbuf);
}

My problem is what is the result of sizeof(rowbuf)? Is it the length of DataObj or either the length of Byte*? why?

Another question: why there is a need to calculate offset of pointer? What is the usual use of it?

What is sizeof(working_addr) equal to?

+5  A: 

sizeof(rowbuf) returns the length in bytes of an object of type DataObj. Note that rowbuf is no pointer, but it is a reference which is quite a difference.

If you want to calculate the size of y DataObj pointer use sizeof(&rowbuf) or sizeof(DataObj*).

codymanix
+3  A: 

sizeof(rowBuf) is the number of bytes used by the DataObj type. It is computed at compile time.

Usually it is needed to call methods on a given instance without knowning about the object (so-called method binding like in boost::bind) these bound instance-method can be used as callbacks for algorithms.

jdehaan
+3  A: 

From the MSDN page about sizeof:

When the sizeof operator is applied to a reference, the result is the same as if sizeof had been applied to the object itself

So sizeof(rowbuf) == sizeof(DataObj)

sbk
+1  A: 

rowbuf is a DataObj &. So you'd expect sizeof(rowbuf) to be equal to sizeof(DataObj).

The other day I learned the Visual Studio debugger has a bug with sizeof and references. It will actually give you the size of a pointer rather than the size of the object. The compiler does the right thing.

Adrian McCarthy