Имеет ли эта инициализация const с помощью const_cast неопределенное поведение?

Согласно моим небольшим тестам, этот код работает. Но есть ли у него неопределенное поведение? Изменение объекта const с помощью const_cast привело к нарушениям доступа во время выполнения в моих предыдущих тестах, но я не могу вспомнить, чем они отличались. Итак, здесь что-то не так или нет?

// test.h
#pragma once
#include <boost/array.hpp>

typedef boost::array<int,100000> bigLut_t;
extern const bigLut_t constBigLut;

// test.cpp
#include "test.h"

bigLut_t& initializeConstBigLut()
{
    bigLut_t* pBigLut = const_cast<bigLut_t*>( &constBigLut );

    for(int i = 0; i < 100000; ++i) {
        pBigLut->at(i) = i;
    }
    return const_cast<bigLut_t&>(constBigLut);
}

const bigLut_t constBigLut = initializeConstBigLut();

// const_test.cpp
#include <iostream>
#include "test.h"

void main()
{
    for(int i = 0; i < 100; ++i) {
        std::cout << constBigLut[i] << std::endl;
    }
    system("pause");
}

(Обратите внимание, что sizeof (bigLut_t) слишком много, чтобы поместиться в стек.)

EDIT: На самом деле мне больше всего нравится идея небольшого комментария ybungalobill для метода инициализации этих больших объектов:

// test.h
#pragma once
#include <boost/array.hpp>

extern const struct BigLut : public boost::array<int,100000> {
    BigLut();
} constBigLut;

// test.cpp
#include "test.h"

const BigLut constBigLut;
BigLut::BigLut()
{
    for(int i = 0; i < 100000; ++i) {
        this->at(i) = i;
    }
}
7
задан zeroes00 28 November 2010 в 08:34
поделиться