Upcast Object Address

Suppose that it Bis a base class D(perhaps virtual, maybe multiple inheritance, it doesn't have to be a direct base class).

Let be objan object of type D(not a subclass D, for sure D).

Let

D * d = std::addressof(obj);
B * b = d;

Is it safe to assume that

(char*) d <= (char*) b && (char*) b < (char*) d + sizeof(D)

?

Background: this will be a step in the routine that determines whether an object was created by placing it newin a concrete one aligned_storage. I must be sure that if so, all pointers to the underlying objects of this object point to some address in aligned_storage.

+4
source share
1 answer

, , D - . .

#include <stdlib.h>
#include <new>

struct B { int i; };
struct D : virtual B { int j; };

int
main()
{
    auto const storage = malloc(sizeof(D));
    D* d = new (storage) D();
    free(storage);
    return 0;
}

B d, , d, " void * operator new (std:: size_t, void *)... ". (http://en.cppreference.com/w/cpp/language/new) B , (char*)d + sizeof(D), ,

, . , , , . , .

0

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


All Articles