Is it possible to remove constness of vector ? If so, how can it be achieved? For some reason, I don't have access to the main (), can I still remove the constness of arr in the following code snipet? It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;. I guess it is just an example of explicit vs implicit cast,which both creates a copy of original array ````arr```. Is it possible to remove constness inplace without creating a copy?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> func(const vector<int>& arr){
// vector<int> arr0 = arr;
auto arr0 = const_cast<vector<int> & > (arr);
sort(arr0.begin(), arr0.end());
return arr0;
}
int main(){
const vector<int> arr = {3,4,1,5,2};
auto res = func(arr);
for (auto n:res)
cout<<n<<" ";
return 0;
}
Don't attempt to cast away constness. Modifing a const object will result in undefined behaviour.
It is effectively the same. The cast is redundant.
If you wish to sort a vector without making a copy, then don't make the vector const in the first place. If it is const, then you cannot modify it.
It's rarely needed, but there are a few use cases.
You can use it to convert a non-const glvalue expression into a const one:
If you have a provably non-const object, and a const reference referring to the non-const object, then you can cast away constness of the reference:
Same cases apply to volatile qualifier, although that's even more rarely needed.