const_cast
cppreference.com
cv-.
const_cast< - >( )
|
|||||||||
-.
const_cast . , const_cast () .
1) , , , cv- .
3) , , ( cv- cv-) ( C++17)
4) -
, :
- lvalue, - lvalue rvalue ( C++11);
|
( C++11) |
- prvalue.
- const_cast
const_cast , volatile , volatile . volatile volatile glvalue .
#include <iostream>
struct type
{
int i;
type(): i(3) {}
void f(int v) const
{
// this->i = v; // : const
const_cast<type*>(this)->i = v; // ,
}
};
int main()
{
int i = 3; // i
const int& rci = i;
const_cast<int&>(rci) = 4; // OK: i
std::cout << "i = " << i << '\n';
type t; // t, t.f(4)
//
t.f(4);
std::cout << "type::i = " << t.i << '\n';
const int j = 3; // j
[[maybe_unused]]
int* pj = const_cast<int*>(&j);
// *pj = 4; //
[[maybe_unused]]
void (type::* pmf)(int) const = &type::f; // -
// const_cast<void(type::*)(int)>(pmf); // : const_cast
//
}
:
i = 4
type::i = 4