POV-Ray : Newsgroups : povray.off-topic : C++: Seriously? : Re: C++: Seriously? Server Time
28 Jul 2024 16:25:00 EDT (-0400)
  Re: C++: Seriously?  
From: Warp
Date: 21 Nov 2013 16:15:21
Message: <528e77e9@news.povray.org>
Orchid Win7 v1 <voi### [at] devnull> wrote:
> The suggested solution? "Why don't you just use a std::vector<char>?"

> Erm... because std::vector<char> /= char *. One is basically an 
> unstructured chunk of arbitrary memory, this other is a complex 
> implementation-dependent data structure.

std::vector is not very implementation-dependent because the standard
guarantees certain properties for it. One of these properties is that
std::vector will always allocate contiguous memory (in the same way
as 'new[]' does.)

This means that if you get a pointer to the first element, then you
have effectively a pointer to an array of chars.

> "What's wrong with using vector.front()?"

The usual way to get a pointer to the first element is "&v[0]", but
I suppose "&v.front()" works too.

> OK, so the documentation says that vector.front() gives you a reference 
> to the first element of the vector. Nothing surprising there. However, 
> if you try to pass that to stream.read()... Woah, that's a whole *bunch* 
> of assumptions, right there! o_O

You shouldn't be passing a *reference* to the first element. You should
be passing a *pointer* to the first element (although this is probably
nitpicking.)

> The documentation guarantees that what gets returned is a reference to 
> the first element. Firstly, I wasn't actually aware you could even use a 
> reference as a pointer; I thought they were separate concepts.

You can't. You have to take a pointer to said element (using the
prefix-& operator.)

> But secondly, I had assumed that the actual location of vector elements was 
> implementation-defined; they might be in a tree, a linked list, a table 
> or tables... anything!

No, because the C++ standard guarantees that the memory allocated by
std::vector will always be contiguous, the same as 'new[]' does.

std::vector was specifically designed in the standard so that it could
be used for these kinds of things.

> But this code... this crazy code seems to be *assuming* that all the 
> elements always just happen to be perfectly contiguous in memory.

And that's perfectly standard.

>    Relying on internal library implementation details? Pretty evil.

Not when the standard guarantees the necessary properties.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.