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

Initializing stack of *const pointers

21 views
Skip to first unread message

bitrex

unread,
Apr 3, 2017, 3:45:02 PM4/3/17
to
Is it possible to modify the following code such that class "Bar"
contains a const array of "Foo" with a template size, and a stack
holding *consts into that array? That is to say something like:

std::stack<Foo *const> a;
const std::array<Foo, M> b = init_from_f<M>();

#include <array>
#include <stack>

struct Foo {};

template <size_t M>
struct Bar
{
Bar()
{
for (const auto& ptr : get_ptrs())
{
a.push(ptr);
}
}
std::stack<Foo*> a;
std::array<Foo, M> b = init_from_f<M>();

template <size_t N>
std::array<Foo, N> init_from_f()
{
std::array<Foo, N> a;
for (size_t i = 0; i < N; ++i) { a[i] = Foo(); }
return a;
}

template <size_t N>
std::array<Foo*, N> get_ptrs()
{
std::array<Foo*, N> b;
for (size_t i = 0; i < N; ++i) { b[i] = b.data() + i; }
return b;
}
};

bitrex

unread,
Apr 4, 2017, 12:38:51 PM4/4/17
to
On 04/04/2017 12:27 AM, Stefan Ram wrote:
> bitrex <bit...@de.lete.earthlink.net> writes:
>> Is it possible to modify the following code such that class "Bar"
>> contains a const array of "Foo" with a template size, and a stack
>> holding *consts into that array? That is to say something like:
>
> When const memory, which might be in ROM, is being const-casted
> to non-const, this can lead to problems.
>
> But I think it might be less grave to cast non-const memory to
> const. So what about initializing the memory and then const-casting
> it to const? (Actually one would cast a pointer or some such.)
>
> (I also thought about using placement new to place const objects,
> but it would end up having an effect similar to a const-cast.)
>

Sure, I think that would be OK. Essentially I'd like to have an array of
X number of objects (template parameter) in a container class
instantiated when the container is instantiated (or maybe static), and
then have access to pointers to those objects through a stack data
structure. The const qualification of the pointers on the stack would
enforce that "these are all the objects you get to play with, here, you
can't pull one of these pointers off the stack by non-const reference
and point it at something else."

I had some trouble with the syntax for a stack of const-qualified
pointers; the STL seemed to balk at something like std::stack<MyType
*const>, though I can't remember the exact error and don't have a
compiler handy.


0 new messages