On Sun, 24 May 2015 10:36:41 -0700 (PDT)
woodb...@gmail.com wrote:
> On Sunday, May 24, 2015 at 11:32:32 AM UTC-5, Mr Flibble wrote:
> > On 24/05/2015 16:28,
woodb...@gmail.com wrote:
> > >
> > > I started using a version of PC-BSD that uses clang 3.6
> > > and am getting a warning about this code:
> > >
> > > template <unsigned long N = udp_packet_max>
> > > class SendBufferStack : public SendBuffer
> > > {
> > > ::std::array<char, N> ar;
> > >
> > > public:
> > > SendBufferStack () : SendBuffer(&ar[0], N) {}
> > > };
> > >
> > > The warning is that field ar is uninitialized when used.
> > > I think that taking the address of the field should be
> > > OK. Gcc 4.9.2 and other compilers don't warn about the
> > > code. Is this a problem or is Clang off track? Thanks
> > > in advance.
> >
> > The warning is quite valid: you are indeed using an uninitialised
>
> Is taking/storing the address of an uninitialized variable wrong?
It is not just that the array is uninitialized, but that it doesn't
exist at all, and you cannot take the address of a non-existent
object. It doesn't exist because the constructor of SendBuffer is
called before any of the members of its sub-class (SendBufferStack) are
constructed. You could lawfully do an assignment (not initialization)
in the body of SendBufferStack's constructor if SendBuffer's member
being assigned to is protected or has a protected accessor, but more
likely you want to consider templating the base class or using a
virtual function.
Of course, as Flibble has pointed out, you are not just taking the
array's address, but you are applying operator[] to the non-existent
array in order to take the address of its first (but also non-existent)
member. So you have doubly undefined behaviour.
Possibly your unnecessary use of the initial scoping operator in
declaring 'ar' is adding to the cognitive load when your read your code.
If you write your code more conventionally without such superfluous
nonsense you would find it easier to see errors like this.
Chris