c++ - 通过 const_cast 进行的这个 const 初始化是否有未定义的行为?

标签 c++ initialization undefined undefined-behavior const-cast

根据我的小测试,这段代码有效。但是,它有未定义的行为吗?在我以前的测试中,通过使用 const_cast 修改 const 对象会导致运行时访问冲突,但我不记得它们有何不同。那么,这里是否存在根本性问题?

// 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) 太大而无法放入堆栈。)

编辑: 我实际上最喜欢 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;
    }
}

最佳答案

您修改定义为常量的对象。无论您何时执行此操作,无论是否在初始化期间,它仍然是未定义的行为。仅当 const 指针是在某个较早阶段从指向该对象的非 const 指针获得时,才定义使用 const_cast 删除 const 性。那不是你的情况。

你能做的最好的事情就是

const bigLut_t& initializeConstBigLut()
{
    static bigLut_t bigLot;

    for(int i = 0; i < 100000; ++i) {
        bigLut.at(i) = i;
    }
    return bigLut;
}

const bigLut_t constBigLut = initializeConstBigLut();

希望编译器能够优化静态临时文件。

关于c++ - 通过 const_cast 进行的这个 const 初始化是否有未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4291253/

相关文章:

c++ - 递增 'masked' 位集

c++ - 有两个 cin 的无限循环

c++ - 如何使用 win32 api 将我的应用程序窗口放置在 Windows 桌面窗口层次结构中的特定位置?

c++ - 变量何时初始化重要吗?

Set[1,2,3] 的 Ruby 语言特性

Python:尝试调用函数时出现 undefined variable 错误?

c++ - 我是否需要使用内存屏障来保护共享资源?

c# - 通过发射/反射初始化类字段

javascript - Node.js - socket.io - 对 io.sockets 的引用突然未定义

C++如何检查char变量是否未定义(未初始化)