Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Vector with fixed memory size?

178 views
Skip to first unread message

JiiPee

unread,
Dec 12, 2018, 3:49:04 PM12/12/18
to
Is it possible to use std::vector so that it keeps the memory allocation
size fixed at some size the whole lifespan? I need this kind of
behaviour in gaming programming where I add elements and delete but I
dont want any memory allocations happening after initial memory allocation.

  I read that the c++ standard does not talk anything about capacity()
when resizing to zero. So I guess its undefined what happens to capacity
after deleting elements?

Or any alternative good way implementing this?

red floyd

unread,
Dec 12, 2018, 4:20:49 PM12/12/18
to
std::vector<>::reserve()

Mr Flibble

unread,
Dec 12, 2018, 5:33:56 PM12/12/18
to
neolib::vecarray

/Flibble

--
“You won’t burn in hell. But be nice anyway.” – Ricky Gervais

“I see Atheists are fighting and killing each other again, over who
doesn’t believe in any God the most. Oh, no..wait.. that never happens.” –
Ricky Gervais

"Suppose it's all true, and you walk up to the pearly gates, and are
confronted by God," Bryne asked on his show The Meaning of Life. "What
will Stephen Fry say to him, her, or it?"
"I'd say, bone cancer in children? What's that about?" Fry replied.
"How dare you? How dare you create a world to which there is such misery
that is not our fault. It's not right, it's utterly, utterly evil."
"Why should I respect a capricious, mean-minded, stupid God who creates a
world that is so full of injustice and pain. That's what I would say."

JiiPee

unread,
Dec 12, 2018, 5:46:35 PM12/12/18
to
but reserve would do re-allocation. So clear() would first delete me
memory and reserve would allocate again. And this is what I would like
to prevent... I would like to keep the original allocated memory even
after clear().

Alf P. Steinbach

unread,
Dec 12, 2018, 6:23:26 PM12/12/18
to
The point is to call `reserve` right after creating the vector.

Deleting items from a vector will not cause it to reallocate.

C++11 added a `shrink_to_fit` function for when you want that, but I
wouldn't trust it to actually do things, and the old idiom of swapping
with an empty vector is trivial to code anyway.


Cheers!,

- Alf

Lynn McGuire

unread,
Dec 12, 2018, 7:56:44 PM12/12/18
to
There is std::array but you would have to implement your own add and
delete methods.

Lynn



leigh.v....@googlemail.com

unread,
Dec 13, 2018, 4:46:30 AM12/13/18
to
std::array doesn't work as all its elements are CONSTRUCTED even if the array is LOGICALLY empty.

neolib::vecarray

/Leigh

Chris M. Thomasson

unread,
Dec 13, 2018, 5:00:05 AM12/13/18
to
;^)

Andrea Venturoli

unread,
Dec 13, 2018, 6:03:58 AM12/13/18
to
On 12/12/18 11:46 PM, JiiPee wrote:

> but reserve would do re-allocation.

Only if newsize>capacity().



> So clear() would first delete me memory

No, you have it wrong here: it calls elements' destructors, but doesn't
free memory (and does not alter capacity()).



> and reserve would allocate again.

Again, only if you reserve() to a bigger size.
If you call reserve() with the old size, it does nothing.



> And this is what I would like to prevent...

Just reserve() as soon as the vector is created and be sure to never
insert/push_back more elements than you reserved for.




> I would like to keep the original allocated memory even
> after clear().

This is what always happens.

JiiPee

unread,
Dec 13, 2018, 6:29:33 AM12/13/18
to
On 12/12/2018 23:23, Alf P. Steinbach wrote:
>
> Deleting items from a vector will not cause it to reallocate.
>
>

Are you sure? Because the standard says about clear():
"

/expression:/|a.clear()|

/return type:/|void|
/Assertion/note pre-/post-condition:/Destroys all elements in a.
Invalidates all references, pointers, and iterators referring to the
elements of a and may invalidate the past-the-end iterator.

/post:/a.empty() returns true.

/Complexity:/Linear.

"

So it does not mention anything about reallocation, so does this mean
its undefined whether reallocation happens or not? If it does not talk
about reallocation issue I would think thats compiler implementation
specific then? So up to compiler how they do it?


JiiPee

unread,
Dec 13, 2018, 6:32:08 AM12/13/18
to
On 13/12/2018 11:03, Andrea Venturoli wrote:
> On 12/12/18 11:46 PM, JiiPee wrote:
>
>> but reserve would do re-allocation.
>
> Only if newsize>capacity().

Does standard promise this?

>
>
>
>> So clear() would first delete me memory
>
> No, you have it wrong here: it calls elements' destructors, but
> doesn't free memory (and does not alter capacity()).

but again, where in the standard it promises this:

/"expression:/|a.clear()|

/return type:/|void|
/Assertion/note pre-/post-condition:/Destroys all elements in a.
Invalidates all references, pointers, and iterators referring to the
elements of a and may invalidate the past-the-end iterator.

/post:/a.empty() returns true.

/Complexity:/Linear."


It does not seem to talk anything about this issue...so we dont know?



Alf P. Steinbach

unread,
Dec 13, 2018, 7:04:03 AM12/13/18
to
Consider

const size_t x = sizeof( int );

The standard doesn't say that an invocation of sizeof shall not output
the message “Ha ha, you're foiled!”.

But you can rely on no such message appearing, because the convention is
that what the standard doesn't explicitly (or sometimes implicitly)
allow, just isn't allowed.

By the way this is a nice illustration that Stack Overflow is now, for
some years, the largest Herb Schildt zone on the internets; information
that you can use to /find/ reliable information, or that you can /test/
yourself, but that you absolutely should not rely on directly by default
without at least reasoning about it, checking that it makes sense.

Namely, I reasoned that for best educational effect I should merely
point you in the direction of a search engine like Google's, but then
I'd best try it myself first, and then I ended up at the Stack Overflow
q/a <url:
https://stackoverflow.com/questions/6882799/does-clearing-a-vector-affect-its-capacity>,
which tells you that you can rely on it in practice but that “That isn't
mandated by the standard”. Which is total bollocks. So much
disinformation and FUD. It pains me.


Cheers & hth.,

- Alf

Andrea Venturoli

unread,
Dec 13, 2018, 7:48:32 AM12/13/18
to
On 12/13/18 12:31 PM, JiiPee wrote:
> On 13/12/2018 11:03, Andrea Venturoli wrote:
>> On 12/12/18 11:46 PM, JiiPee wrote:
>>
>>> but reserve would do re-allocation.
>>
>> Only if newsize>capacity().
>
> Does standard promise this?

I don't have access to the standard, so I won't say so for sure.

All the "standard libraries" I've used work this way.



The closest I can get to the standard is:
https://en.cppreference.com/w/cpp/container/vector/clear
which says capacity() is unchaged.

There you'll also find a pointer to an interesting discussion.
If I had access to the standard, I could check the hypotheses myself,
but I believe them to stand.

Bo Persson

unread,
Dec 13, 2018, 8:00:55 AM12/13/18
to
The guarantees are found in the description of reserve(). There it says:

"After reserve(), capacity() is greater or equal to the argument of
reserve if reallocation happens; and equal to the previous value of
capacity() otherwise."

and

"No reallocation shall take place during insertions that happen after a
call to reserve() until the time when an insertion would make the size
of the vector greater than the value of capacity()."


So, after a call to reserve() the clear() function is not allowed to
shrink the capacity.

Paavo Helde

unread,
Dec 13, 2018, 8:33:56 AM12/13/18
to
On 13.12.2018 15:00, Bo Persson wrote:
>
> "No reallocation shall take place during insertions that happen after a
> call to reserve() until the time when an insertion would make the size
> of the vector greater than the value of capacity()."

Note that this speaks of *insertions*, while clear() is not an insertion.

If this paragraph was meant to apply to other operations as well, it
should have been phrased something like that:

"No reallocation shall take place during further member function calls,
with the exception of shrink_to_fit(), ...

I'm not claiming that clear() is allowed to reallocate the buffer, just
pointing out this does not follow from this paragraph.

James Kuyper

unread,
Dec 13, 2018, 8:34:52 AM12/13/18
to
On 12/13/18 07:03, Alf P. Steinbach wrote:
> On 13.12.2018 12:29, JiiPee wrote:
>> On 12/12/2018 23:23, Alf P. Steinbach wrote:
>>>
>>> Deleting items from a vector will not cause it to reallocate.
>>>
>>>
>>
>> Are you sure? Because the standard says about clear():
>> "
>>
>> /expression:/|a.clear()|
>>
>> /return type:/|void|
>> /Assertion/note pre-/post-condition:/Destroys all elements in a.
>> Invalidates all references, pointers, and iterators referring to the
>> elements of a and may invalidate the past-the-end iterator.
>>
>> /post:/a.empty() returns true.
>>
>> /Complexity:/Linear.
>>
>> "
>>
>> So it does not mention anything about reallocation, so does this mean
>> its undefined whether reallocation happens or not? If it does not talk
>> about reallocation issue I would think thats compiler implementation
>> specific then? So up to compiler how they do it?
>
> Consider
>
> const size_t x = sizeof( int );
>
> The standard doesn't say that an invocation of sizeof shall not output
> the message “Ha ha, you're foiled!”.
>
> But you can rely on no such message appearing, because the convention is
> that what the standard doesn't explicitly (or sometimes implicitly)
> allow, just isn't allowed.

As a general rule, any container member function for which the standard
says "Invalidates all references, pointers, and iterators referring to
the elements of a ..." implies that a reallocation is allowed - a
reallocation is the only thing that would necessitate invalidating them.

The standard's description of reserve() guarantees that "No reallocation
shall take place during insertions that happen after a call to reserve()
until the time when an insertion would make the size of the vector
greater than the value of capacity()." (23.3.6.3p6).
Note that there is no mention of deletions, and it would have trivially
been feasible to change it to say "insertions or deletions". That fact
that this was not done implies that no such guarantees apply to
deletions. Or, alternatively, they could have replaced the "during ..."
clause with "unless shrink_to_fit() or resize() are called", which would
have been an even stronger restriction.

JiiPee

unread,
Dec 13, 2018, 8:53:25 AM12/13/18
to
ye I found that site as well

Scott Lurndal

unread,
Dec 13, 2018, 8:55:48 AM12/13/18
to
If the size is fixed, just use a plain old C array.

JiiPee

unread,
Dec 13, 2018, 8:56:52 AM12/13/18
to
On 13/12/2018 13:33, Paavo Helde wrote:
> On 13.12.2018 15:00, Bo Persson wrote:
>>
>> "No reallocation shall take place during insertions that happen after a
>> call to reserve() until the time when an insertion would make the size
>> of the vector greater than the value of capacity()."
>
> Note that this speaks of *insertions*, while clear() is not an insertion.
>
> If this paragraph was meant to apply to other operations as well, it
> should have been phrased something like that:
>
> "No reallocation shall take place during further member function
> calls, with the exception of shrink_to_fit(), ...

logically yes

>
> I'm not claiming that clear() is allowed to reallocate the buffer,
> just pointing out this does not follow from this paragraph.

so how it is?


JiiPee

unread,
Dec 13, 2018, 8:58:11 AM12/13/18
to
On 13/12/2018 13:55, Scott Lurndal wrote:
> Lynn McGuire <lynnmc...@gmail.com> writes:
>> On 12/12/2018 2:48 PM, JiiPee wrote:
>>> Is it possible to use std::vector so that it keeps the memory allocation
>>> size fixed at some size the whole lifespan? I need this kind of
>>> behaviour in gaming programming where I add elements and delete but I
>>> dont want any memory allocations happening after initial memory allocation.
>>>
>>>   I read that the c++ standard does not talk anything about capacity()
>>> when resizing to zero. So I guess its undefined what happens to capacity
>>> after deleting elements?
>>>
>>> Or any alternative good way implementing this?
>> There is std::array but you would have to implement your own add and
>> delete methods.
> If the size is fixed, just use a plain old C array.


why not std::array? its a better version of c array? nothing to lose ,
only to get more, isnt it?


Alf P. Steinbach

unread,
Dec 13, 2018, 9:17:27 AM12/13/18
to
No, that's a misunderstanding.

For example, after clearing a vector all items have been destroyed.
That's very much “invalidate”. You can't access items within the
capacity but beyond the current size.


> The standard's description of reserve() guarantees that "No reallocation
> shall take place during insertions that happen after a call to reserve()
> until the time when an insertion would make the size of the vector
> greater than the value of capacity()." (23.3.6.3p6).
> Note that there is no mention of deletions, and it would have trivially
> been feasible to change it to say "insertions or deletions". That fact
> that this was not done implies that no such guarantees apply to
> deletions.

No, that's a misunderstanding.

Insertions and `shrink_to_fit` are the only operations, apart from
`reserve` itself, that can possibly cause a reallocation. With that in
mind the quoted language describes what advantage calling `reserve`
gives you: that no reallocation will happen until... There is no
possible advantage associated with removing items, no need to describe
that, because that does not affect the capacity.

Similarly, `reserve` has no advantage associated with multiplying
integers, so there's no mention of that either.


> Or, alternatively, they could have replaced the "during ..."
> clause with "unless shrink_to_fit() or resize() are called", which would
> have been an even stronger restriction.

Yes, but there's no need.

This is not a defect. It's how the standard works. It does not mention
all the things that are disallowed: only what it says is allowed, is.

Öö Tiib

unread,
Dec 13, 2018, 9:22:37 AM12/13/18
to
boost::container::static_vector

Öö Tiib

unread,
Dec 13, 2018, 9:46:30 AM12/13/18
to
On Thursday, 13 December 2018 16:17:27 UTC+2, Alf P. Steinbach wrote:
> On 13.12.2018 14:34, James Kuyper wrote:
>
> > The standard's description of reserve() guarantees that "No reallocation
> > shall take place during insertions that happen after a call to reserve()
> > until the time when an insertion would make the size of the vector
> > greater than the value of capacity()." (23.3.6.3p6).
> > Note that there is no mention of deletions, and it would have trivially
> > been feasible to change it to say "insertions or deletions". That fact
> > that this was not done implies that no such guarantees apply to
> > deletions.
>
> No, that's a misunderstanding.
>
> Insertions and `shrink_to_fit` are the only operations, apart from
> `reserve` itself, that can possibly cause a reallocation. With that in
> mind the quoted language describes what advantage calling `reserve`
> gives you: that no reallocation will happen until... There is no
> possible advantage associated with removing items, no need to describe
> that, because that does not affect the capacity.

I trust std::vector::assign can also reallocate, otherwise it
does not make sense. About deletions there AFAIK are some
other requirements that imply that those won't reallocate.
For example std::vector::erase and std::vector::pop_back
have to leave the iterators and references up to point of
deletion valid (so can't reallocate) and std::vector::clear
has to leave capacity same (so it also can't reallocate).

Andrea Venturoli

unread,
Dec 13, 2018, 9:48:00 AM12/13/18
to
On 12/13/18 2:34 PM, James Kuyper wrote:

> The standard's description of reserve() guarantees that "No reallocation
> shall take place during insertions that happen after a call to reserve()
> until the time when an insertion would make the size of the vector
> greater than the value of capacity()." (23.3.6.3p6).
> Note that there is no mention of deletions,

As I said, I don't have access to the standard right now...

Doesn't it say elsewhere that reallocation of a vector can only take
place during insertions?
Or, specularly, that deletions don't cause reallocations?

Both are "common sense", I believe...

james...@alumni.caltech.edu

unread,
Dec 13, 2018, 11:30:11 AM12/13/18
to
On Thursday, December 13, 2018 at 9:48:00 AM UTC-5, Andrea Venturoli wrote:
> On 12/13/18 2:34 PM, James Kuyper wrote:
>
> > The standard's description of reserve() guarantees that "No reallocation
> > shall take place during insertions that happen after a call to reserve()
> > until the time when an insertion would make the size of the vector
> > greater than the value of capacity()." (23.3.6.3p6).
> > Note that there is no mention of deletions,
>
> As I said, I don't have access to the standard right now...
>
> Doesn't it say elsewhere that reallocation of a vector can only take
> place during insertions?

No.

> Or, specularly, that deletions don't cause reallocations?

erase() can only invalidate things that refer to positions after the element being erased, which effectively prohibits reallocation. However, clear() invalidated all pointers, references, and iterators; it could, therefore, reallocate so long as it doesn't change capacity().
Actually, I can't find as many statements about what can and cannot change the value returned by capacity() as I thought there were. I'm can't find anything that actually guarantees that capacity() will remain unchanged - by anything.

Lynn McGuire

unread,
Dec 13, 2018, 1:59:23 PM12/13/18
to
That is specifically what the op asked for. The op wants the vector to
contain the max memory usage at startup.

Lynn

Lynn McGuire

unread,
Dec 13, 2018, 1:59:38 PM12/13/18
to
On 12/13/2018 7:55 AM, Scott Lurndal wrote:
> Lynn McGuire <lynnmc...@gmail.com> writes:
>> On 12/12/2018 2:48 PM, JiiPee wrote:
>>> Is it possible to use std::vector so that it keeps the memory allocation
>>> size fixed at some size the whole lifespan? I need this kind of
>>> behaviour in gaming programming where I add elements and delete but I
>>> dont want any memory allocations happening after initial memory allocation.
>>>
>>>   I read that the c++ standard does not talk anything about capacity()
>>> when resizing to zero. So I guess its undefined what happens to capacity
>>> after deleting elements?
>>>
>>> Or any alternative good way implementing this?
>>
>> There is std::array but you would have to implement your own add and
>> delete methods.
>
> If the size is fixed, just use a plain old C array.

I was thinking that also.

Lynn

Mr Flibble

unread,
Dec 13, 2018, 2:01:54 PM12/13/18
to
And that has nothing to do with what I said.

I repeat: std::array doesn't work as all its elements are CONSTRUCTED even
if the array is LOGICALLY empty.

Read these words again but this time engage your brain.

james...@alumni.caltech.edu

unread,
Dec 13, 2018, 2:48:29 PM12/13/18
to
On Thursday, December 13, 2018 at 4:46:30 AM UTC-5, leigh.v....@googlemail.com wrote:
> On Thursday, December 13, 2018 at 12:56:44 AM UTC, Lynn McGuire wrote:
> > On 12/12/2018 2:48 PM, JiiPee wrote:
> > > Is it possible to use std::vector so that it keeps the memory allocation
> > > size fixed at some size the whole lifespan? I need this kind of
> > > behaviour in gaming programming where I add elements and delete but I
> > > dont want any memory allocations happening after initial memory allocation.
> > >
> > >   I read that the c++ standard does not talk anything about capacity()
> > > when resizing to zero. So I guess its undefined what happens to capacity
> > > after deleting elements?
> > >
> > > Or any alternative good way implementing this?
> >
> > There is std::array but you would have to implement your own add and
> > delete methods.
> >
> > Lynn
>
> std::array doesn't work ...

How can you be sure of that?

> ... as all its elements are CONSTRUCTED even if the array is LOGICALLY empty.
123456789012345678901234567890123456789012345678901234567890123456789012
True - but not necessarily a problem. JiiPee has only expressed a desire
to avoid unnecessary memory allocation. It's not clear whether he has
any need to avoid unnecessary default constructor calls. He hasn't said
anything about the type of data he's storing - for all we know, it might
be a type with a trivial default constructor. Even if it's not trivial,
it might be of neglible importance.
There might be other reasons why std::array<> isn't suitable for his
application, but that isn't necessarily one of them.

Mr Flibble

unread,
Dec 13, 2018, 2:58:04 PM12/13/18
to
My answer is based upon making no assumptions about the data type; when
you ASSUME things you make an ass out of you and me.

Chris Vine

unread,
Dec 13, 2018, 4:39:34 PM12/13/18
to
However it does have to do with what the OP said, which is the point in
issue.

It is also somewhat misleading to say that with std::array all its
elements are 'CONSTRUCTED'. If the elements are of trivial type or
aggregates of trivial type, then no initialization is carried out - the
values in the array are indeterminate (there is no value
initialization).

Chris Vine

unread,
Dec 13, 2018, 4:51:07 PM12/13/18
to
On Thu, 13 Dec 2018 21:39:21 +0000
Chris Vine <chris@cvine--nospam--.freeserve.co.uk> wrote:
> It is also somewhat misleading to say that with std::array all its
> elements are 'CONSTRUCTED'. If the elements are of trivial type or
> aggregates of trivial type, then no initialization is carried out - the
> values in the array are indeterminate (there is no value
> initialization).

... unless they are static variables at namespace scope.

james...@alumni.caltech.edu

unread,
Dec 13, 2018, 4:57:52 PM12/13/18
to
On Thursday, December 13, 2018 at 2:58:04 PM UTC-5, Mr Flibble wrote:
> On 13/12/2018 19:48, james...@alumni.caltech.edu wrote:
> > On Thursday, December 13, 2018 at 4:46:30 AM UTC-5, leigh.v....@googlemail.com wrote:
> >> On Thursday, December 13, 2018 at 12:56:44 AM UTC, Lynn McGuire wrote:
...
> >>> There is std::array but you would have to implement your own add and
> >>> delete methods.
> >>>
> >>> Lynn
> >>
> >> std::array doesn't work ...
> >
> > How can you be sure of that?
> >
> >> ... as all its elements are CONSTRUCTED even if the array is LOGICALLY empty.
> >
> > True - but not necessarily a problem. JiiPee has only expressed a desire
> > to avoid unnecessary memory allocation. It's not clear whether he has
> > any need to avoid unnecessary default constructor calls. He hasn't said
> > anything about the type of data he's storing - for all we know, it might
> > be a type with a trivial default constructor. Even if it's not trivial,
> > it might be of neglible importance.
> > There might be other reasons why std::array<> isn't suitable for his
> > application, but that isn't necessarily one of them.
>
> My answer is based upon making no assumptions about the data type; when
> you ASSUME things you make an ass out of you and me.

That popular saying is sheer nonsense. It's not possible to think
without making assumptions; the best that you can do is to be careful
choosing which assumptions you make.

You didn't say that it "wouldn't work if your type is not
DefaultConstructible". You didn't say that it "might not work". There
was nothing conditional at all in your statement. You just said
unconditionally that it "doesn't work" - and such a conclusion can only
be justified by making assumptions about what type he's working with.
Since you say you made no such assumption, then it's an invalid and
unjustified conclusion.

Mr Flibble

unread,
Dec 13, 2018, 4:59:59 PM12/13/18
to
I didn't assume that it wasn't default constructible. Now go and have a
word with yourself mate.

james...@alumni.caltech.edu

unread,
Dec 13, 2018, 6:13:30 PM12/13/18
to
On Thursday, December 13, 2018 at 4:59:59 PM UTC-5, Mr Flibble wrote:
> On 13/12/2018 21:57, james...@alumni.caltech.edu wrote:
...
> > You didn't say that it "wouldn't work if your type is not
> > DefaultConstructible". You didn't say that it "might not work". There
> > was nothing conditional at all in your statement. You just said
> > unconditionally that it "doesn't work" - and such a conclusion can only
> > be justified by making assumptions about what type he's working with.
> > Since you say you made no such assumption, then it's an invalid and
> > unjustified conclusion.
>
> I didn't assume that it wasn't default constructible.

I know that you didn't make that assumption - you said so, appearances
to the contrary not withstanding, so I took you at your word. I said as
much. And it was a very wise thing of you to do, to not assume that.
Unfortunately, without making that assumption, you can't justify saying
unconditionally that std::array doesn't work.

Juha Nieminen

unread,
Dec 14, 2018, 2:52:06 AM12/14/18
to
JiiPee <n...@notvalid.com> wrote:
>> If the size is fixed, just use a plain old C array.
>
> why not std::array? its a better version of c array? nothing to lose ,
> only to get more, isnt it?

Neither a C array nor std::array offer almost any of the same member
functions as std::vector does. Also, they will construct every single
element in the array, even if you don't want to. There's no trivial
way of destructing the elements before the whole array is destroyed.
(Sure, you can explicitly call the destructor of an element, but
then you'll have a destructed element directly accessible. You would
have to make sure to construct it again if you want to reuse it.)

Also, in both cases you need to know the size at compile time, which
might not always be the case.

Using an std::vector with a reserved size ought to be fine (especially
if you only know the size at runtime), as long as you don't call any of
the member functions that change the size of its allocation. These are
quite easy to avoid (ie. push_back(), resize(), etc.)

JiiPee

unread,
Dec 14, 2018, 6:21:06 AM12/14/18
to
On 14/12/2018 07:51, Juha Nieminen wrote:
> JiiPee <n...@notvalid.com> wrote:
>>> If the size is fixed, just use a plain old C array.
>> why not std::array? its a better version of c array? nothing to lose ,
>> only to get more, isnt it?
> Neither a C array nor std::array offer almost any of the same member
> functions as std::vector does.

yes I know array does not fit here, but just that std::array is better
than c-array imo, as you get object orianted benefits for free

> Using an std::vector with a reserved size ought to be fine (especially
> if you only know the size at runtime),

yes I know, I carefully take care of the size myself. Its meant to be
fixed size buffer (possibly increasing at some point, but I manage that)

> as long as you don't call any of
> the member functions that change the size of its allocation. These are
> quite easy to avoid (ie. push_back(), resize(), etc.)

but even push_back(), resize()should be fine as long as the capacity is
enough to do that. And thats why I wanted vector as I could normally use
push_back. if capacity is big, then push_back does not reallocate


JiiPee

unread,
Dec 14, 2018, 6:23:44 AM12/14/18
to
On 13/12/2018 18:59, Lynn McGuire wrote:
I prefer vector because I get all the benefits of vector easy usage
(pushback, remove, clear, insert). array does not have there.. so its
difficult to use. how do you easily add an element in the middel of an
array? :)


JiiPee

unread,
Dec 14, 2018, 6:26:00 AM12/14/18
to
On 13/12/2018 18:59, Lynn McGuire wrote:
Ye it has like 1000 slots to start with. But the main point I wanted
vector is because its easy to use (add element in the middle, pushback,
etc). array is not easy to use.

JiiPee

unread,
Dec 14, 2018, 6:33:17 AM12/14/18
to
On 13/12/2018 19:48, james...@alumni.caltech.edu wrote:
> True - but not necessarily a problem.

true, its not big issue here

> JiiPee has only expressed a desire
> to avoid unnecessary memory allocation.

yes. thats the main point here. And to be able to use vector which is
easy to use.

> It's not clear whether he has
> any need to avoid unnecessary default constructor calls.

I dont need to avoid....

> He hasn't said
> anything about the type of data he's storing -

objects with possible bigger data inside them. so quite big objects. Its
game programming, so in a tight for loop I dont want to do any allocations.
It should be able to survive also even if small images added there
inside objects I guess.

> for all we know, it might
> be a type with a trivial default constructor. Even if it's not trivial,
> it might be of neglible importance.

yes, not important... as it would be done only once at the beginning of
the program.

james...@alumni.caltech.edu

unread,
Dec 14, 2018, 7:00:09 AM12/14/18
to
Judging from your other three most recent messages, there are indeed
many reasons why std::array<> isn't suitable - but as I said, this isn't
one of them.

I've argued that clear(), by reason of invalidating all pointers,
references, and iterators, is permitted to do a reallocation, even after
a reserve. The same is true even if you erase() only the first element
of the vector. Others disagree - but regardless of whether I'm right
about those points, those are the only two operations that have
permission to reallocate after a call to reserve(), until you do an
insert that pushes size() above the current value of capacity(). If you
do the reserve() immediately after creating the vector, I would think
that should be sufficient protection against reallocation. If not, your
only alternative is to create a custom container that reallocates only
at the times you want it to do so.

James Kuyper

unread,
Dec 14, 2018, 7:06:56 AM12/14/18
to
On 12/14/18 06:59, james...@alumni.caltech.edu wrote:
...
> of the vector. Others disagree - but regardless of whether I'm right
> about those points, those are the only two operations that have
> permission to reallocate after a call to reserve(), until you do an

That didn't come out right - I should have replaced "those are the only
two operations that" with "no other operations".

Scott Lurndal

unread,
Dec 14, 2018, 9:02:32 AM12/14/18
to
Juha Nieminen <nos...@thanks.invalid> writes:
>JiiPee <n...@notvalid.com> wrote:
>>> If the size is fixed, just use a plain old C array.
>>
>> why not std::array? its a better version of c array? nothing to lose ,
>> only to get more, isnt it?
>
>Neither a C array nor std::array offer almost any of the same member
>functions as std::vector does. Also, they will construct every single
>element in the array, even if you don't want to.

Not necessarily. I'd make the C array an array of pointers to
objects.

I know that some people believe pointers in C++ should be
avoided. I prefer to think that if you don't understand
how to use them properly, you shouldn't be programming in
a language that supports them.

Martijn van Buul

unread,
Dec 14, 2018, 9:54:30 AM12/14/18
to
* Alf P. Steinbach:
> By the way this is a nice illustration that Stack Overflow is now, for
> some years, the largest Herb Schildt zone on the internets; information
> that you can use to /find/ reliable information, or that you can /test/
> yourself, but that you absolutely should not rely on directly by default
> without at least reasoning about it, checking that it makes sense.

<delurk>
StackOverflow is broken by design, in that the "right answer" gets picked
by the person who is least qualified to do so (namely: the person who
asked the question). It confuses "This answers was useful to me" with
"this is the right answer".

That said, I don't think there's an easy way to organize a site like
this that isn't flawed one way or the other. For example, this newsgroup is
a fond of useful information, but that doesn't mean you can trust everything
at face value either.

<delurk>
--
Martijn van Buul - pi...@dohd.org

JiiPee

unread,
Dec 14, 2018, 9:55:14 AM12/14/18
to
On 14/12/2018 11:59, james...@alumni.caltech.edu wrote:
> If you
> do the reserve() immediately after creating the vector, I would think
> that should be sufficient protection against reallocation.

me also, but also not 100% sure.. thats why I asked :). And I would need
100% assurance...

> If not, your
> only alternative is to create a custom container that reallocates only
> at the times you want it to do so.

Yes, althought would prefer not to do this at this point... I have other
more important things... thats why would rather use vector if possible.


JiiPee

unread,
Dec 14, 2018, 9:58:31 AM12/14/18
to
On 14/12/2018 14:02, Scott Lurndal wrote:
> I prefer to think that if you don't understand
> how to use them properly, you shouldn't be programming in
> a language that supports them.


I see it a safety issue , like in work. That if there is a risk then to
avoid the risk. So if there is another way to do (other than pointers) I
would prefer that. I think Bjarne also talked liked that. So imo its not
about how skillfull C++ programmer I am, its just that regardless of my
skill I would avoid risks.

Real Troll

unread,
Dec 14, 2018, 10:21:17 AM12/14/18
to
On 14/12/2018 14:54, Martijn van Buul wrote:
> <delurk>
> StackOverflow is broken by design, in that the "right answer" gets picked
> by the person who is least qualified to do so (namely: the person who
> asked the question). It confuses "This answers was useful to me" with
> "this is the right answer".

There is no such thing as right answer or wrong answer. The OP decides
what is right for him or her. The feature of marking something is right
should be removed because, as you say, it is subjective.

>
> That said, I don't think there's an easy way to organize a site like
> this that isn't flawed one way or the other. For example, this newsgroup is
> a fond of useful information, but that doesn't mean you can trust everything
> at face value either.
Do you mean to say discussion about religion? If so, I agree, it is
fake and it should be banned from these newsgroups but we don't have a
moderator and there was a stupid chap called Richard who was spending
all his time trying to open a closed moderated newsgroup and he failed
in that project. So religion is going to remain here, unfortunately.


>
> <delurk>

JiiPee

unread,
Dec 14, 2018, 10:27:35 AM12/14/18
to
On 14/12/2018 15:22, Real Troll wrote:
> On 14/12/2018 14:54, Martijn van Buul wrote:
>> <delurk>
>> StackOverflow is broken by design, in that the "right answer" gets
>> picked
>> by the person who is least qualified to do so (namely: the person who
>> asked the question). It confuses "This answers was useful to me" with
>> "this is the right answer".
>
> There is no such thing as right answer or wrong answer.  The OP
> decides what is right for him or her.  The feature of marking
> something is right should be removed because, as you say, it is
> subjective.

I think there is "best" answer many times objectively speaking. Like if
somebody says "should I put all my code in the main() function?" and
then somebody says "no"... that surely is best answer :).

But from our point of view sure its better it is objectively speaking
best answer.

>>
>> That said, I don't think there's an easy way to organize a site like
>> this that isn't flawed one way or the other. For example, this
>> newsgroup is
>> a fond of useful information, but that doesn't mean you can trust
>> everything
>> at face value either.
> Do you mean to say discussion about religion?  If so, I agree, it is
> fake and it should be banned from these newsgroups but we don't have a
> moderator and there was a stupid chap called Richard who was spending
> all his time trying to open a closed moderated newsgroup and he failed
> in that project.  So religion is going to remain here, unfortunately.
>

I like groups have some freedom though. Even though I dont also like
religion talk here (even though I believe), as its not the right forum,
then if somebody little bit talks religion here and there.... I would
not ban them :). We are humans anyway... and its difficult to keep
conversation 100% purely in programming always. Also couple of non-topic
messages here and there does not bother me, I can skil them easily. But
yes, if its all the time sending them, then I agree better ban.


Bo Persson

unread,
Dec 14, 2018, 12:16:30 PM12/14/18
to
On 2018-12-14 15:55, JiiPee wrote:
> On 14/12/2018 11:59, james...@alumni.caltech.edu wrote:
>> If you
>> do the reserve() immediately after creating the vector, I would think
>> that should be sufficient protection against reallocation.
>
> me also, but also not 100% sure.. thats why I asked :). And I would need
> 100% assurance...
>

You have gotten the correct answer - that it *is* guaranteed - supported
by quotes from the standard.

You have also gotten posts saying "I don't believe that".

This is probably as close as you get by asking random strangers on the
internet.

Bet you will not get 100% agreement on "Is Elvis still alive?" either. :-)


Bo Persson

james...@alumni.caltech.edu

unread,
Dec 14, 2018, 12:20:03 PM12/14/18
to
There's no way to completely avoid risk, and some risks are worth
taking. You said the objects you're working with are large. A container
of pointers to large objects would be much smaller and correspondingly
less time-consuming to rearrange than a container of the objects
themselves, and you might be able to mitigate most of the risks by using
some variety of smart pointer.

JiiPee

unread,
Dec 14, 2018, 12:56:11 PM12/14/18
to
On 14/12/2018 17:16, Bo Persson wrote:
> Bet you will not get 100% agreement on "Is Elvis still alive?" either. :-)


haha. I think he died...

There are conspiricies for sure, but this is propably not one of them
(no evidence).

Juha Nieminen

unread,
Dec 15, 2018, 3:25:09 AM12/15/18
to
Scott Lurndal <sc...@slp53.sl.home> wrote:
> I'd make the C array an array of pointers to objects.

If you can have an array of objects instead of an array of pointers
to objects, why would you deliberately choose the latter? The former
is much easier to use, and usually much more efficient (especially
if in the latter case you are allocating each object dynamically and
individually). The former is also safer (and easier to use safely)
than the latter.

The main situation where you would want to use an array of pointers
to (dynamically allocated) objects is if those objects are of
different types. (In some situations you might also want to do that
if what you actually need is an array of "references". Since you
can't actually use references in an array, you'll have to use
pointers instead.)

> I know that some people believe pointers in C++ should be
> avoided. I prefer to think that if you don't understand
> how to use them properly, you shouldn't be programming in
> a language that supports them.

If you can easily and fluently avoid using a pointer, in general
it's a good idea to do so. Your code usually becomes simpler, cleaner
and safer. This doesn't mean one isn't very experienced in using
pointers.

JiiPee

unread,
Dec 15, 2018, 5:25:29 AM12/15/18
to
On 15/12/2018 08:25, Juha Nieminen wrote:
> Scott Lurndal <sc...@slp53.sl.home> wrote:
>> I'd make the C array an array of pointers to objects.
> If you can have an array of objects instead of an array of pointers
> to objects, why would you deliberately choose the latter?

I used to do the pointer array when I was a beginner because "it looked
cool", hehe. But now I prefer objects.
Although storing unique pointers is also very safe nowadays, but no
reason really to do it other than what you said (polymorphism).

>> I know that some people believe pointers in C++ should be
>> avoided. I prefer to think that if you don't understand
>> how to use them properly, you shouldn't be programming in
>> a language that supports them.
> If you can easily and fluently avoid using a pointer, in general
> it's a good idea to do so. Your code usually becomes simpler, cleaner
> and safer. This doesn't mean one isn't very experienced in using
> pointers.

yes, I think safety always first even if experienced. It just reduces
risk, and reducing risk is good for experienced as well


Scott Lurndal

unread,
Dec 15, 2018, 10:36:28 AM12/15/18
to
Juha Nieminen <nos...@thanks.invalid> writes:
>Scott Lurndal <sc...@slp53.sl.home> wrote:
>> I'd make the C array an array of pointers to objects.
>
>If you can have an array of objects instead of an array of pointers
>to objects, why would you deliberately choose the latter?

Cache management.

Alf P. Steinbach

unread,
Dec 15, 2018, 12:34:43 PM12/15/18
to
On 15.12.2018 09:25, Juha Nieminen wrote:
> Scott Lurndal <sc...@slp53.sl.home> wrote:
>> I'd make the C array an array of pointers to objects.
>
> If you can have an array of objects instead of an array of pointers
> to objects, why would you deliberately choose the latter?

Generally, not considering the context of the question, the main example
is a jagged array.

Then there is the array of items of different most derived types.

And the case where the pointers /are/ your objects to be stored.

But in context, Scott was most probably giving one way of postponing
initialization until actual use.

Another way to do that is like `std::vector`, with in-place construction
in a raw buffer.


Cheers!,

- Alf

James Kuyper

unread,
Dec 15, 2018, 3:31:17 PM12/15/18
to
On 12/15/18 03:25, Juha Nieminen wrote:
> Scott Lurndal <sc...@slp53.sl.home> wrote:
>> I'd make the C array an array of pointers to objects.
>
> If you can have an array of objects instead of an array of pointers
> to objects, why would you deliberately choose the latter?

Because the objects are much bigger than the pointers, and the array
frequently needs to be rearranged.

woodb...@gmail.com

unread,
Dec 16, 2018, 8:28:59 AM12/16/18
to
On Saturday, December 15, 2018 at 2:25:09 AM UTC-6, Juha Nieminen wrote:
> Scott Lurndal <sc...@slp53.sl.home> wrote:
> > I'd make the C array an array of pointers to objects.
>
> If you can have an array of objects instead of an array of pointers
> to objects, why would you deliberately choose the latter? The former
> is much easier to use, and usually much more efficient (especially
> if in the latter case you are allocating each object dynamically and
> individually). The former is also safer (and easier to use safely)
> than the latter.
>
> The main situation where you would want to use an array of pointers

I would change that to: One situation ...
I've not found many users of this library:
https://www.boost.org/doc/libs/1_69_0/doc/html/poly_collection.html
Maybe there's something wrong with that library? The author
spent a lot of time on it and is very experienced. From
what I can tell it's one of the good parts of Boost.

> to (dynamically allocated) objects is if those objects are of
> different types. (In some situations you might also want to do that
> if what you actually need is an array of "references". Since you
> can't actually use references in an array, you'll have to use
> pointers instead.)
>


Brian
Ebenezer Enterprises - In G-d we trust.
https://github.com/Ebenezer-group/onwards

Juha Nieminen

unread,
Dec 17, 2018, 3:50:35 AM12/17/18
to
Scott Lurndal <sc...@slp53.sl.home> wrote:
>>If you can have an array of objects instead of an array of pointers
>>to objects, why would you deliberately choose the latter?
>
> Cache management.

I think an array of objects is more cache-friendly than individually
allocated objects. (The array of objects will be all in consecutive
memory, while the individually allocated objects may end up really
scattered in memory, potentially causing memory fragmentation and
cache misses.)

Öö Tiib

unread,
Dec 17, 2018, 3:50:56 AM12/17/18
to
On Friday, 14 December 2018 17:21:17 UTC+2, Real Troll wrote:
> On 14/12/2018 14:54, Martijn van Buul wrote:
> > <delurk>
> > StackOverflow is broken by design, in that the "right answer" gets picked
> > by the person who is least qualified to do so (namely: the person who
> > asked the question). It confuses "This answers was useful to me" with
> > "this is the right answer".
>
> There is no such thing as right answer or wrong answer. The OP decides
> what is right for him or her. The feature of marking something is right
> should be removed because, as you say, it is subjective.

StackOverflow tries to filter out such questions to what there are no
correct answers. The issue there is that asker can mark one of answers
as "accepted". Reader of it should just know that people can (and
often do) accept incorrect answers. It happens because that answer
seemed to fit with asker's expectations or seemed to work for them,
not because that question was subjective, controversial or unclear.

Scott Lurndal

unread,
Dec 17, 2018, 8:52:11 AM12/17/18
to
Often (usually), the objects are accessed randomly via the pointers, and
the fact that the objects are located contiguously doesn't help in
that case.

Juha Nieminen

unread,
Dec 17, 2018, 9:23:15 AM12/17/18
to
Scott Lurndal <sc...@slp53.sl.home> wrote:
>>I think an array of objects is more cache-friendly than individually
>>allocated objects. (The array of objects will be all in consecutive
>>memory, while the individually allocated objects may end up really
>>scattered in memory, potentially causing memory fragmentation and
>>cache misses.)
>
> Often (usually), the objects are accessed randomly via the pointers, and
> the fact that the objects are located contiguously doesn't help in
> that case.

It still reduces memory fragmentation, which may increase efficiency
overall.

Scott Lurndal

unread,
Dec 17, 2018, 11:08:32 AM12/17/18
to
I don't see that as too likely, and highly dependent upon the
usage model of the data structure in question. But, YMMV.

Juha Nieminen

unread,
Dec 18, 2018, 4:42:04 AM12/18/18
to
Scott Lurndal <sc...@slp53.sl.home> wrote:
>>It still reduces memory fragmentation, which may increase efficiency
>>overall.
>
> I don't see that as too likely, and highly dependent upon the
> usage model of the data structure in question. But, YMMV.

If you are, for example, allocating a thousand objects, it significantly
reduces memory fragmentation if you make one single allocation (ie. an
array of a thousand objects), than if you make a thousand individual
allocations.

(Granted, if these are the very first allocations you are doing in the
program, there probably will be no memory fragmentation. However, if this
is happening during the execution of large program, with tons and tons of
allocations and deallocations, the amount of memory fragmentation will
increase further and further the more individual allocations and
deallocations you make. If you minimize the number of allocations, and
if you allocate large chunks of memory at a time (in the form of arrays),
this will help reduce the overall amount of memory fragmentation.)

Memory fragmentation increses overall memory consumption and slows down
speed (because it increases the amount of cache misses).

Scott Lurndal

unread,
Dec 18, 2018, 8:51:57 AM12/18/18
to
Juha Nieminen <nos...@thanks.invalid> writes:
>Scott Lurndal <sc...@slp53.sl.home> wrote:
>>>It still reduces memory fragmentation, which may increase efficiency
>>>overall.
>>
>> I don't see that as too likely, and highly dependent upon the
>> usage model of the data structure in question. But, YMMV.
>
>If you are, for example, allocating a thousand objects, it significantly
>reduces memory fragmentation if you make one single allocation (ie. an
>array of a thousand objects), than if you make a thousand individual
>allocations.

Why do you say that? If I allocate all 1000 objects immediately
and store their pointers, how is that fragmenting anything? Or
if I allocate all 1000 objects in a single allocation and
divide the allocation up?

And, for that matter, who cares if virtual memory is "fragmented"?
(Physical memory is, of course, always "fragmented" into pages).

Anyone doing small frequent allocations is already doing something
wrong.

>
>Memory fragmentation increses overall memory consumption and slows down
>speed (because it increases the amount of cache misses).

1) How does it increase overall memory consumption? Are you
referring to the 8-16 byte overhead per allocation? That's
in the noise.

2) How does it 'increase the amount (number) of cache misses',
particularly when each object consumes multiple cache lines?


Juha Nieminen

unread,
Dec 18, 2018, 2:10:45 PM12/18/18
to
Scott Lurndal <sc...@slp53.sl.home> wrote:
> Why do you say that? If I allocate all 1000 objects immediately
> and store their pointers, how is that fragmenting anything? Or
> if I allocate all 1000 objects in a single allocation and
> divide the allocation up?

If all your program ever allocates is those 1000 objects, then maybe.
However, programs do a lot more than that.

> And, for that matter, who cares if virtual memory is "fragmented"?
> (Physical memory is, of course, always "fragmented" into pages).

Traversing RAM in a random order is slower than traversing it
consecutively (regardless of whether it's physical or virtual
memory). When traversing it consecutively, the hardware prefethces
data and other such things.

>>Memory fragmentation increses overall memory consumption and slows down
>>speed (because it increases the amount of cache misses).
>
> 1) How does it increase overall memory consumption? Are you
> referring to the 8-16 byte overhead per allocation? That's
> in the noise.

Because memory fragmentation causes many gaps of free memory to
form between allocated blocks. When these gaps are too small for
a new allocation, additional memory will be allocated even though
there may be a lot of it free. It's just that all that free memory
is in such small gaps that the new allocation may not fit in any of
them.

There's a reason why many garbage-collected runtime systems (such
as the Java runtime) perform memory compaction. (Memory compaction
is rearranging all the allocated blocks into consecutive memory,
removing all the free gaps.)

> 2) How does it 'increase the amount (number) of cache misses',
> particularly when each object consumes multiple cache lines?

Because traversing memory in random order causes more cache misses
than traversing it consecutively.

Scott Lurndal

unread,
Dec 18, 2018, 3:33:57 PM12/18/18
to
Juha Nieminen <nos...@thanks.invalid> writes:
>Scott Lurndal <sc...@slp53.sl.home> wrote:
>> Why do you say that? If I allocate all 1000 objects immediately
>> and store their pointers, how is that fragmenting anything? Or
>> if I allocate all 1000 objects in a single allocation and
>> divide the allocation up?
>
>If all your program ever allocates is those 1000 objects, then maybe.
>However, programs do a lot more than that.

Most of mine are performance sensitive and allocate upon
startup, or use pools.


>
>> And, for that matter, who cares if virtual memory is "fragmented"?
>> (Physical memory is, of course, always "fragmented" into pages).
>
>Traversing RAM in a random order is slower than traversing it
>consecutively (regardless of whether it's physical or virtual
>memory).

That's certainly not accurate. Access latency to DRAM is not
address sensitive (modulo minor effects such as leaving pages
open in a DIMM, any memory controller interleaving behavior,
and internal fifo backpressure).

The various levels (L1I, L1D, L2, LLC) of cache are designed
to reduce the average access latency to DRAM.

>When traversing it consecutively, the hardware prefethces
>data and other such things.

The team I work with is responsible for architecting
prefetchers and we do extensive real-world workload tracing
in order to have sufficient data to decide whether a particular
prefetcher is achieving the required performance. Few
interesting server workloads access memory using regular strides;
random accesses are much more common (large graph data structures,
for example).

>Because traversing memory in random order causes more cache misses
>than traversing it consecutively.

That's entirely dependent upon the stride distance. Which in real-world
workloads is generally larger than the cache line size.

Vir Campestris

unread,
Dec 18, 2018, 4:12:41 PM12/18/18
to
On 14/12/2018 14:02, Scott Lurndal wrote:
> I know that some people believe pointers in C++ should be
> avoided. I prefer to think that if you don't understand
> how to use them properly, you shouldn't be programming in
> a language that supports them.

I may be one of them.

I believe _raw_ pointers should be avoided.

Certainly if I find code that says

... * foo = new ...

alarm bells go off. unique_ptr is almost always a better solution.

Andy

Vir Campestris

unread,
Dec 18, 2018, 4:16:48 PM12/18/18
to
On 14/12/2018 11:25, JiiPee wrote:
> Ye it has like 1000 slots to start with. But the main point I wanted
> vector is because its easy to use (add element in the middle, pushback,
> etc). array is not easy to use.

If you are inserting things in the middle frequently vector may not be
the right type either.

It involves moving all the objects after the insertion up by one.

Andy

Lynn McGuire

unread,
Dec 18, 2018, 4:25:09 PM12/18/18
to
On 12/14/2018 5:23 AM, JiiPee wrote:
> On 13/12/2018 18:59, Lynn McGuire wrote:
>> On 12/13/2018 7:55 AM, Scott Lurndal wrote:
>>> Lynn McGuire <lynnmc...@gmail.com> writes:
>>>> On 12/12/2018 2:48 PM, JiiPee wrote:
>>>>> Is it possible to use std::vector so that it keeps the memory
>>>>> allocation
>>>>> size fixed at some size the whole lifespan? I need this kind of
>>>>> behaviour in gaming programming where I add elements and delete but I
>>>>> dont want any memory allocations happening after initial memory
>>>>> allocation.
>>>>>
>>>>>     I read that the c++ standard does not talk anything about
>>>>> capacity()
>>>>> when resizing to zero. So I guess its undefined what happens to
>>>>> capacity
>>>>> after deleting elements?
>>>>>
>>>>> Or any alternative good way implementing this?
>>>>
>>>> There is std::array but you would have to implement your own add and
>>>> delete methods.
>>>
>>> If the size is fixed, just use a plain old C array.
>>
>> I was thinking that also.
>>
>>
>
> I prefer vector because I get all the benefits of vector easy usage
> (pushback, remove, clear, insert). array does not have there.. so its
> difficult to use. how do you easily add an element in the middel of an
> array? :)

Yup, the key word there is "easily".

Lynn



Juha Nieminen

unread,
Dec 19, 2018, 7:06:35 AM12/19/18
to
Vir Campestris <vir.cam...@invalid.invalid> wrote:
> I believe _raw_ pointers should be avoided.

It depends on what you are doing.

If you are creating your own STL-style dynamic data container, raw pointers
*inside* the class may be complete A-ok, and the best way to go (after all,
that's what all standard library data container implementations do).

Also, sometimes raw pointers can be used for more than just handling
dynamically allocated memory. For example "iterators" to a static array
are raw pointers, and there's nothing wrong in using them there.
(In fact, quite often std::vector iterators are nothing more than
typedeffed raw pointers, so you are probably using them even without
knowing.)

Vir Campestris

unread,
Dec 20, 2018, 4:34:48 PM12/20/18
to
On 19/12/2018 12:06, Juha Nieminen wrote:
> Vir Campestris <vir.cam...@invalid.invalid> wrote:
>> I believe _raw_ pointers should be avoided.
>
> It depends on what you are doing.
>
> If you are creating your own STL-style dynamic data container, raw pointers
> *inside* the class may be complete A-ok, and the best way to go (after all,
> that's what all standard library data container implementations do).
>
I said avoided. That's one of the places where you can't easily avoid
them. In that case you should be careful that the pointer is managed by
the container, zeroed on construction, and freed on destruction.

Or if you were really paranoid you'd make the member pointer a unique_ptr...

But how often do you write such code? For me there are gaps of years.

> Also, sometimes raw pointers can be used for more than just handling
> dynamically allocated memory. For example "iterators" to a static array
> are raw pointers, and there's nothing wrong in using them there.
> (In fact, quite often std::vector iterators are nothing more than
> typedeffed raw pointers, so you are probably using them even without
> knowing.)
>

And in the bit of my message you snipped you'd see


>>Certainly if I find code that says

>>.... * foo = new ...

>>alarm bells go off. unique_ptr is almost always a better solution.

Those raw pointers don't own the objects.

Andy

Jorgen Grahn

unread,
Dec 22, 2018, 7:34:11 AM12/22/18
to
On Fri, 2018-12-14, JiiPee wrote:
> On 13/12/2018 18:59, Lynn McGuire wrote:
>> On 12/13/2018 3:46 AM, leigh.v....@googlemail.com wrote:
>>> On Thursday, December 13, 2018 at 12:56:44 AM UTC, Lynn McGuire wrote:
>>>> On 12/12/2018 2:48 PM, JiiPee wrote:
>>>>> Is it possible to use std::vector so that it keeps the memory
>>>>> allocation
>>>>> size fixed at some size the whole lifespan? I need this kind of
>>>>> behaviour in gaming programming where I add elements and delete but I
>>>>> dont want any memory allocations happening after initial memory
>>>>> allocation.
>>>>>
>>>>>     I read that the c++ standard does not talk anything about
>>>>> capacity()
>>>>> when resizing to zero. So I guess its undefined what happens to
>>>>> capacity
>>>>> after deleting elements?
>>>>>
>>>>> Or any alternative good way implementing this?
>>>>
>>>> There is std::array but you would have to implement your own add and
>>>> delete methods.
>>>>
>>>> Lynn
>>>
>>> std::array doesn't work as all its elements are CONSTRUCTED even if
>>> the array is LOGICALLY empty.

Yes, except for the "logically empty" part. Unless I'm missing
something vital about std::array, an array<string, 5> always contains
exactly five strings.

Of course you can have application specific rules like "I only care
about the N first elements" or "empty strings don't count", but that's
not something std::array is responsible for.

>>> neolib::vecarray
>>>
>>> /Leigh
>>
>> That is specifically what the op asked for.  The op wants the vector
>> to contain the max memory usage at startup.
>>
>
> Ye it has like 1000 slots to start with. But the main point I wanted
> vector is because its easy to use (add element in the middle, pushback,
> etc). array is not easy to use.

It's not easy to use /as a vector/ because it has a different purpose.
You cannot add elements to a std::array, in the middle or anywhere else.

/Jorgen

--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .

Mr Flibble

unread,
Dec 22, 2018, 10:46:40 AM12/22/18
to
Correct so we say the array cannot be PHYSICALLY empty; it can however be
LOGICALLY empty.

>
> Of course you can have application specific rules like "I only care
> about the N first elements" or "empty strings don't count", but that's
> not something std::array is responsible for.

Correct so the array plus something else determines the invariant
IS-ARRAY-LOGICALLY-EMPTY.

/Flibble

--
“You won’t burn in hell. But be nice anyway.” – Ricky Gervais

“I see Atheists are fighting and killing each other again, over who
doesn’t believe in any God the most. Oh, no..wait.. that never happens.” –
Ricky Gervais

"Suppose it's all true, and you walk up to the pearly gates, and are
confronted by God," Bryne asked on his show The Meaning of Life. "What
will Stephen Fry say to him, her, or it?"
"I'd say, bone cancer in children? What's that about?" Fry replied.
"How dare you? How dare you create a world to which there is such misery
that is not our fault. It's not right, it's utterly, utterly evil."
"Why should I respect a capricious, mean-minded, stupid God who creates a
world that is so full of injustice and pain. That's what I would say."

ViralTaco

unread,
Dec 26, 2018, 3:34:01 PM12/26/18
to
On Wednesday, December 12, 2018 at 9:49:04 PM UTC+1, JiiPee wrote:
> Is it possible to use std::vector so that it keeps the memory allocation
> size fixed at some size the whole lifespan? I need this kind of
> behaviour in gaming programming where I add elements and delete but I
> dont want any memory allocations happening after initial memory allocation.
>
>   I read that the c++ standard does not talk anything about capacity()
> when resizing to zero. So I guess its undefined what happens to capacity
> after deleting elements?
>
> Or any alternative good way implementing this?

std::array can be created with a fixed size.
If you don't want any extra memory allocation once you've initialised the vector (ie: it stays in it's bounds all the time)
you can use the reserve() function from the std::vector library on your vector. Ie:
`std::vector<int> foo; foo.reserve(128);` But be careful not to go above that reserve.
Here is why: https://en.cppreference.com/w/cpp/container/vector/reserve

james...@alumni.caltech.edu

unread,
Dec 26, 2018, 4:36:00 PM12/26/18
to
On Wednesday, December 26, 2018 at 3:34:01 PM UTC-5, ViralTaco wrote:
> On Wednesday, December 12, 2018 at 9:49:04 PM UTC+1, JiiPee wrote:
> > Is it possible to use std::vector so that it keeps the memory allocation
> > size fixed at some size the whole lifespan? I need this kind of
> > behaviour in gaming programming where I add elements and delete but I
> > dont want any memory allocations happening after initial memory allocation.
> >
> >   I read that the c++ standard does not talk anything about capacity()
> > when resizing to zero. So I guess its undefined what happens to capacity
> > after deleting elements?
> >
> > Or any alternative good way implementing this?

You should generally review previous answers before posting a new one of
your own. Both of the answers you given have already been mentioned
several times apiece.

> std::array can be created with a fixed size.

He's already indicated a desire to perform push_back(), remove(),
insert(), and clear(), operations that are not supported for
std::array<>.

> If you don't want any extra memory allocation once you've initialised the vector (ie: it stays in it's bounds all the time)
> you can use the reserve() function from the std::vector library on your vector.

He seems doubtful about whether "no reallocation" is absolutely
guaranteed in that case. There's some basis for his concern: that
guarantee is only provided for inserts, not deletions. The requirements
for the validity of interators, pointers, and references to the elements
of a std::vector<> effectively prohibit reallocation during most
deletions, but allow it if one of the elements being deleted is the
first element of the array. The only protection he has against such a
reallocation is that there's no apparent reason for one to occur in that
situation.
0 new messages