3

I am not sure about const_cast in this case. Do we have undefined behaviour or not?

#include <iostream>
#include <vector>

using namespace std;

struct A {
    mutable vector<int> a;
    A() : a(1,2) {}
    const vector<int>& get() const {
        return a;
    }
};

int main()
{
    A a;
    vector<int> &b = const_cast<vector<int>&>( a.get() );
    b[0] = 3;
    cout << a.a[0] << endl;
}
  • dupe/related: http://stackoverflow.com/questions/357600/is-const-cast-safe – NathanOliver Mar 16 '16 at 17:26
  • the last part of [this answer](http://stackoverflow.com/a/34842262/2805305) is helpful to understand const casting and what you can and cannot do. – bolov Mar 16 '16 at 17:29

2 Answers2

3

Modifying a variable that is non-const is well defined. const_cast exists precisely to allow modification of a non-const object using a const reference (works similarly for volatile despite the name). There is no undefined behaviour in the example code.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

It is safe to remove const from a reference to a variable that is non-const. In this case, a is non-const, a.a is non-const, so the const_cast is perfectly legal.

The const_cast is also a bad idea because it may result in class the invariant being violated behind its back. Modifications to the vector should be done through an appropriate public interface to the class.

Mark B
  • 95,107
  • 10
  • 109
  • 188