开发者

Is const_cast acceptable when defining an array?

开发者 https://www.devze.com 2023-01-19 06:19 出处:网络
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,

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开发者_如何学Python being a little silly asking this :D


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.


If you're trying to initialize it, and if it's an array, just do it with an initialization list:

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


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.


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.


first of all, why do you need to change something that is declared constant ?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号