Reference to an array of unknown bound (C++)

Viewed 190

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?

1 Answers

The problem I am facing comes from the fact that a pointer to an array of unknown bound is, by my understanding, illegal C++.

You're mistaken. Pointer to an array of unknown bound is not illegal in C++.

I am in fact invoking undefined behaviour. (Or, possibly, some non-standard compiler extension?)

Neither (as long as the pointer is valid). The shown function is standard conforming even if T is an array of unknown bound.

why are pointers and references to arrays of unknown bound illegal?

They aren't illegal.


There used to be a special case that pointers and references to arrays of unknown bound were illegal as function parameters. That was made legal in a defect resolution in 2014

Related