I have a templated class used for modelling views on objects, like std::shared_ptr and std::weak_ptr but without any owning semantics. The class internally holds a pointer to the viewed object and a functor which is called on class destruction (It is useful for reference counting the viewed object, or for thread-safe locking and releasing of the viewed resource).
Like the standard library counterparts, I would like my class to behave as expected when the owned object is an array (T[]). The problem I am facing comes from the fact that a pointer to an array of unknown bound is, by my understanding, illegal C++. More specifically, given that the template parameter of the class T is, say, int[], when in my class I write:
T& operator*() {
return *internal_pointer;
}
I am in fact invoking undefined behaviour. (Or, possibly, some non-standard compiler extension?)
I am aware of the fact that a class template specialization is needed just to avoid these scenarios - a pointer to the element type int could be kept instead and just treated like a pointer to an array by the class. However, my question is this: why are pointers and references to arrays of unknown bound illegal?
Using them seems to me like the most logical thing to do, since what you're viewing is an array of which you might not necessarily know the length: this preserves the type of the viewed object, while a regular pointer to the element type seems to me nothing more than a hack.
Is there any technical reason to disallow references to arrays of unknown bound?
std::vectororstd::list.int[6]into anint(*)[]orint(&)[], for example -- at least as of C++20.static_cast<int(*)[]>from typeint(*)[2]the compiler complains. I tried to also cast the type through another indirection (cast the pointer to pointer to array) but that still doesn't help. I'm skeptical of usingreinterpret_castbecause there are no guarantees of the usability of the resulting pointer, and casting throughvoid*seems like cheating. Do you know of a solution?