不是哥们
来点反直觉的 😅
开胃小菜 & 情感铺垫:
int a = 1;
const int *p1 = &a;
int const *p2 = &a; // be equal to p1
int *const p3 = &a;
const auto p4 = &a; // be equal to p3
auto const p5 = &a; // be equal to p3
const int *const p6 = &a;
p1 = &a; // OK
*p1 = 1; // CE, *p1 is read-only
p3 = &a; // CE, p3 is read-only
*p3 = 1; // OK
p6 = &a; // CE, p6 is read-only
*p6 = 1; // CE, *p6 is read-only
拉坨大的:
const int p1 = 1e9 + 7; // OK
int const p2 = 998244353; // OK, be equal to p1
p1 = p2; // CE, p1 is read-only
const_cast<int&>(p1) = p2; // UB, attempt to modify const object p1
auto *p = &p1;
*p = p2; // CE, *p is read-only, OK on VS C++
const struct { mutable int p3; } x { p1 };
x.p3 = p2; // OK, p3 is mutable
开窜:
#include <memory>
#include <string>
#include <iostream>
auto main() -> int {
using Node = struct displayer {
mutable std::string c;
auto operator-> (void) const {
std::cout << "c = " << c << std::endl;
return this;
}
auto& operator, (const int q) {
c += std::to_string(q);
return *this;
}
} const;
std::cout << (displayer{ "1" }, 14, 514)->c << std::endl;
std::cout << (displayer{ "1" }, 14, 514) << std::endl; // CE
std::cout << (Node{ "1" }, 14, 514)->c << std::endl; // CE
std::cout << (Node{ "1" }, 14, 514) << std::endl;
return 0;
}
预期输出:
c = 114514
114514
514
我们 C++ 超厉害!
—— · EOF · ——
真的什么也不剩啦 😖