简体   繁体   中英

Correct way to initialize a const member

I am working on a graphics library and I am currently working on optimization. As far as I know (correct me if I am wrong), in the GCC/G++ compiler, read-only variables and constants are placed in the text section in flash (I am working on an embedded system based on an ARM processor) and this offers an efficient way to hold large chunks of data instead of depending on RAM.

Therefore, I need to initialize a const array declared within a class, this is my approach:

#include <iostream>

using namespace std;

class BITMAP{
    public:
        const uint16_t *BMP; // Image for this graphic object       

        BITMAP(uint16_t *bmp) : BMP(bmp) {} // This is where I initialize the const array

};

class GFX{
    public:
        void init_bmp();
        void render();


    private:
        // Object 
        BITMAP *bmp_image;

};

void GFX::init_bmp()
{
    cout << "Setting..." << endl;
    uint16_t *BMP1 = new uint16_t[2];  
    BMP1[0] = 0xFFFF;
    BMP1[1] = 0xFFFF;
    BITMAP bmp_image(BMP1);
    cout << "done!" << endl;

    delete[] BMP1;
}

void GFX::render()
{
    for( int i=0; i<2; i++ )
    {
        cout << i << ":" << bmp_image->BMP[i] << endl;
    }
}

int main()
{
    GFX img;

    img.test();
    img.render();


    return 0;
}

The above code is giving me a segmentation fault whenever I try to read the contents of BITMAP::BMP . What's the correct to initialize const uint16_t *BMP in the above code?

There are two issues: bmp_image is never initialized, and you delete the array before reading it.

Instead of this:

BITMAP bmp_image(BMP1);

Do this:

bmp_image = new BITMAP(BMP1);

These pointers should be deleted in the destructor of each class, not before.

Moreover, you are not actually creating a constant array. You are creating the array dynamically, because you use new . One way to make it a compile-time constant that is placed in the text section, is to create a global array with the image:

static const uint16_t BMP1[] = {0xFFFF, 0xFFFF};

Then pass this array to the constructor of BITMAP .

What's the correct to initialize const uint16_t *BMP in the above code?

You are initializing it correctly. The problem is that you are delete ing the memory that was allocated, which leaves the member pointer as a dangling pointer.

You can remove the line

delete[] BMP1;

to take care of the problem. However, managing dynamically allocated memory is fraught with problems. Prefer use of std::vector .

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