通过const_cast修改const std :: vector <T>的元素

Arc*_*son 13 c++ stl const-cast stdvector language-lawyer

以下程序是否具有未定义的行为?

#include <iostream>
#include <vector>

struct Foo
{
    const std::vector<int> x;
};

int main()
{
    std::vector<int> v = {1,2,3};
    auto f = new Foo{v};
    const_cast<int&>(f->x[1]) = 42; // Legal?
    std::cout << f->x[1] << "\n";
}
Run Code Online (Sandbox Code Playgroud)

需要注意的是它使用const_cast剥离从常量性f->x,而是从汽提常量性f->x[x],这大概是由一个单独的数组来表示。还是在创建翻译f->x[1]后就假定它是不可变的?

J. *_*rez 2

您的示例中没有未定义的行为。

上面的代码不会调用未定义的行为,因为底层数据 (int) 是可变的。让我们看一个更简单的例子。

#include <iostream>

struct IntPtr {
    int* data;
};

int main() {
    int a = 0;
    const IntPtr p { &a }; 
    *p.data = 10;
    std::cout << a; // Prints 10
}
Run Code Online (Sandbox Code Playgroud)

所有这些都是完全合法的,因为使用IntPtrconst 会导致data成为指向 int 的常量指针,而不是指向常量 int 的指针。p.data我们可以修改指向的数据;我们只是无法改变p.data自己。

const IntPtr p { &a };

*p.data = 10; // This is legal

int b;
p.data = &b; // This is illegal (can't modify const member)
Run Code Online (Sandbox Code Playgroud)

那么这个例子如何应用到 呢std::vector 让我们添加索引的功能IntPtr

class IntPtr {
    int* data;
   public:
    IntPtr() = default;
    IntPtr(int size) : data(new int[size]) {}
    
    // Even though this is a const function we can return a mutable reference 
    // because the stuff data points to is still mutable. 
    int& operator[](int index) const {
        return data[index]; 
    }
};

int main() {
    const IntPtr i(100); 
    i[1] = 10; // This is fine
};
Run Code Online (Sandbox Code Playgroud)

尽管 是IntPtrconst,但底层数据是可变的,因为它是通过分配可变整数数组创建的。对于 来说也是一样的std::vector:底层数据仍然是可变的,所以对它来说是安全的const_cast