简体   繁体   中英

Is const_cast acceptable when defining an array?

I have a static const array class member (const pointers to SDL_Surfaces, but that's irrelevant), and have to loop through it in order to populate it. Aside from a const_cast when I'm done looping, which I hear is bad practice, how would I go about doing this?

EDIT: The reason I don't just do...

static SDL_Surface *const myArray[3];
...
class::myArray[3] = {...};

is that I need to read from a different array and run a function on the different array's respective value in order to get the value for this array. Once I've looped all the way through, I'm never changing this array again, so the way I see it, it should be const.

EDIT 2: I think I might have made a conceptual mistake here. Is it possible to const_cast in some way to make something const, instead of to remove it's constness, which is what I was trying to do? If not, then I was being a little silly asking this :D

如果您尝试对其进行初始化,并且它是一个数组,则只需使用初始化列表即可:

static const int myarray[] = {1,2,3,4,5,6};

If your array is const and you are using a const_cast to enable you to write values into it the you are invoking undefined behaviour .

This is almost universally not an acceptable practice.

typedef boost::array< const SDL_Surface *, 100 > surfaces_t;

class A {
   static const surfaces_t surfaces;
};

surfaces_t initialize_surfaces()
{
   // ...
}

const surfaces_t A::surfaces = initialize_surfaces();

As for EDIT 2: You can't change the type of object after it is declared. Casts don't do that, it is not possible in C++. What casts do is to form an expression of a given type from an expression of another type, with appropriate semantics that are different for different types of casts. For const_cast, you can add/remove const and you can add/remove volatile, and nothing else.

One method to provide "logical constness" is to make the data inaccessible, except by non-mutating means.

For example:

class foo
{
public:
    const bar& get_bar() { return theBar; }

private:
    static bar theBar;
};

Even though theBar isn't constant, since foo is the only thing that can modify it, as long as it does so correctly you essentially (logically) have a constant bar .

首先,为什么需要更改声明为常量的内容?

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