首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >const_casting是一个安全的可变字段吗?

const_casting是一个安全的可变字段吗?
EN

Stack Overflow用户
提问于 2012-11-19 22:51:58
回答 1查看 189关注 0票数 4

考虑以下C++03程序:

代码语言:javascript
复制
#include <iostream>

struct T
{
    mutable int x;

    T() : x(0) {}
};

void bar(int& x)
{
   x = 42;
}

void foo(const T& t)
{
   bar(const_cast<int&>(t.x));
}

int main()
{
   T t;
   foo(t);
   std::cout << t.x << '\n';
}

It appears to work,但它确实安全吗?

我只修改了一个mutable字段,但是完全去掉它的const上下文让我很紧张。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-19 22:54:40

它是安全的,但也是不必要的。因为有了mutablet.x已经是int&类型了。您的示例程序works fine if the cast is removed entirely

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13456242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档