简体   繁体   中英

Const pointer to an array of pointers

i have this class

struct A {
    A();
    Item*  m_Items[ON_CPU + ON_GPU];
    Item** m_ItemsOnCpu;
    Item** m_ItemsOnGpu;
};

I need to initialize

m_ItemsOnCpu to m_Items

and

m_ItemsOnGpu to m_Items + ON_CPU

So I need const pointers to two parts of the array. How do I need to declare and then initialize them?

In C++11 you can just do:

struct A {
    A();
    Item*  m_Items[ON_CPU + ON_GPU];
    Item** const m_ItemsOnCpu = m_Items;
    Item** const m_ItemsOnGpu = m_Items + ON_CPU;
};

On other versions of C++, use an initialization list:

struct A {
    A() : m_ItemsOnCpu(m_Items), m_ItemsOnGpu(m_Items + ON_CPU) {};
    Item*  m_Items[ON_CPU + ON_GPU];
    Item** const m_ItemsOnCpu;
    Item** const m_ItemsOnGpu;
};

So you want something like this:

struct A {
    A(): m_ItemsOnCpu(m_Items), m_ItemsOnGpu(m_Items + ON_CPU) {};
    Item*  m_Items[ON_CPU + ON_GPU];
    Item** const m_ItemsOnCpu;
    Item** const m_ItemsOnGpu;
}

As I understand you, you want to have m_ItemsOnCpu point at the beginning of m_Items, and m_ItemsOnGpu somewhere in the middle of m_Items.

I do not know exactly what you want to achieve by pointing to the Item pointers. You could use two separate Item* arrays for that. If they need to be consecutive in memory, this is automatically the case with class or struct members, although there might be a small gap in between due to struct member alignment, which you can set to 1 byte on most compilers, ie MSVS .

I figure you want const pointers so the user of your class cannot modify them (const pointer to pointer to Item, Item ** const m_ItemsOnCpu ). This can be achieved by using a getter function instead of publicly exposing the member variables. Const objects need to be initialized and cannot be assigned to. Since the address of m_Items is determined at run time, I do not see a way to initialize const pointers.

Another possible goal would be that you would not want the user to modify the pointers found where m_ItemsOnCpu and m_ItemsOnCpu point (pointer to const pointer to Item, Item * const * m_ItemsOnCpu ). Then you can initialize them pointing to appropriate places. A minimal example would be:

#define ON_CPU 5
#define ON_GPU 5

class Item {};

struct A {
    A() {
        m_Items[0] = 0; // initialize your array here
        m_ItemsOnCpu = &(m_Items[0]);
        m_ItemsOnGpu = &(m_Items[ON_CPU]);
    };
    Item * m_Items[ON_CPU + ON_GPU];
    Item * const * m_ItemsOnCpu;
    Item * const * m_ItemsOnGpu;
};

int main() {
}

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM