Reputation: 3621
I have come across what I consider strangeness in my C++ code and am curious as to the cause. I have overloaded new for class Object and print the returned value to the console. I also print the value of this in the constructor for Object. These values do not match (they differ by one word). Is this expected?
void* Object::operator new(size_t size)
{
void* startAddress = ...
std::cout << "object starts at absolute address " << (int)startAddress << "\n";
return startAddress;
}
Object(TypeId type)
{
_type = type;
std::cout << "this is address " << (int)this << "\n";
}
Output:
object starts at absolute address 5164888
this is address 5164896
Upvotes: 0
Views: 53
Reputation: 275575
new
is a raw allocator. The use of the address and amount of memory requested is implementation defined.
As an example, debug information, or information about size of block (number of objects to destroy), or (maybe? Tricky, not sure how arrays would work) vtable information can all be put before the "actual object starts".
Only trivially copiable objects are guaranteed to be copied via raw bits after this
.
This means that the return value of placement new
need be used, and not a reinterpreted pointer to raw storage, as an aside.
Upvotes: 2