Suppose I have a class with two fields of the same access level and type; if I have a pointer p
to the first one, will p + 1
invariably be a pointer to the second? e.g. for a class
class A {
public:
B first;
B second;
};
If I then have A a;
and B *p = &(a.first);
, are there any situations in which (p + 1) == &(a.second)
could be false? Does the same apply to member pointers (e.g. B A::*p = &A::first
and (p + 1) == &A::second
)?
As a larger case, suppose I'm trying to recreate std::array
without using builtin arrays. I might try something like this:
template<class T, size_t N>
class array {
T head;
array<T, N - 1> rest;
public:
// ... and all the constructors and methods and whatnot
};
template<class T>
class array<T, 1> {
T head;
public:
// ...
};
template<class T>
class array<T, 0> {
public:
// ...
};
(the special case for 1 is because sizeof(array<T, 0>)
is 1
just like any other empty class, meaning that if it is included in the recursion then sizeof(array<T, N>)
is sizeof(T) * N + 1
instead of the expected sizeof(T) * N
)
Given the above class definition, can I safely define the class's T& operator [](size_t index)
simply to return *(&head + index)
?
(I realize I could define it to return index ? rest[index - 1] : head
, but the recursion would incur some significant overhead, and even if it's tail-call optimized or inlined, it still effectively becomes index ? (index - 1 ? (index - 2 ? ... : rest.rest.head) : rest.head) : head
which still involves a lot more jumps than the pointer arithmetic version)
Note: I am not asking if this should be done, but if it can; I am not planning on applying this, I'm just curious. Also, my question is just about the pointer arithmetic stuff, not anything else in my examples.