如何解决const_cast:仅当原始变量为const时,才可以修改以前的const值
https://stackoverflow.com/a/332086/462608
仅当原始变量为const时,才修改未定义的const值
...
如果您使用它来使const脱离对未使用const声明的内容的引用,那将是安全的。
...
例如,这在基于const重载成员函数时非常有用。它还可以用于向对象添加const,例如调用成员函数重载。
我无法理解以上引用的含义。我要求您给我一些例子,以实际说明这些引述的含义。
解决方法
关于前两个引号:
void do_not_do_this(const int& cref) {
const_cast<int&>(cref) = 42;
}
int main() {
int a = 0;
// "if you use it to take the const off a reference
// to something that wasn't declared with const,it is safe."
do_not_do_this(a); // well-defined
// a is now 42.
// "modifying a formerly const value is only
// undefined if the original variable is const"
const int b = 0;
do_not_do_this(a); // undefined behavoiur
}
关于您的最终报价:
// "This can be useful when overloading member functions based
// on const,for instance. It can also be used to add const
// to an object,such as to call a member function overload."
class A {
const int& get() const
{
// ... some common logic for const and
// non-const overloads.
return a_;
}
int& get() {
// Since this get() overload is non-const,the object itself
// is non-const in this scope. Moreover,the a_ member
// is non-const,and thus casting away the const of the return
// from the const get() (after 'this' has been casted to
// const) is safe.
A const * const c_this = this;
return const_cast<int&>(c_this->get());
}
private:
int a_{0};
}
,
如何?
#include <iostream>
void foo(const int& ub,const int& ok)
{
const_cast<int&>(ub) = 0.0; // undefined behaviour - the original object is const
const_cast<int&>(ok) = 1.0; // this is fine - the original object is not const
}
int main()
{
const int ub = 1.0;
int ok = 0.0;
foo(ub,ok);
std::cout << ub << " " << ok << std::ends;
}
请注意,常见编译器的输出为1 1
:理由是编译器知道ub
不能在main
中进行更改,因此它将{中的ub
替换为1 {1}}通话。
您的第三段暗示了一个非std::cout
成员函数的函数体,该成员函数调用const
版本是为了避免代码重复。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。