加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用const_cast的自动类型推断不起作用

发布时间:2020-12-16 09:22:28 所属栏目:百科 来源:网络整理
导读:在我的工作中,const_cast的使用在某些情况下是不可避免的. 现在我必须const_cast一些非常复杂的类型,实际上我不想在const_cast Clutter中写出所有这种类型的混乱.表达式,特别是如果Clutter非常长. 我的第一个想法是编写const_cast(myType),但是我的编译器无
在我的工作中,const_cast的使用在某些情况下是不可避免的.

现在我必须const_cast一些非常复杂的类型,实际上我不想在const_cast< Clutter>中写出所有这种类型的混乱.表达式,特别是如果Clutter非常长.

我的第一个想法是编写const_cast<>(myType),但是我的编译器无法推导出myType的非const类型.所以我想帮助我的编译器和我编写以下方法,编译.

#include <stdlib.h>
#include <iostream>

int main(int,char**) {
    const int constVar = 6;
    using T = typename std::remove_cv<decltype(constVar)>::type;
    auto& var = const_cast<T&>(constVar);
    var *= 2;
    std::cout << &constVar << " " << &var << "n"; // Same address!
    std::cout << constVar << " " << var << "n";
    return EXIT_SUCCESS;
}

不幸的是,程序给了我输出6 12而不是预期的6 6,我真的不明白?

我的做法有什么问题?

解决方法

const_cast的文档:

const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const object or a reference or pointer to non-volatile type that is actually referring to a volatile object. Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

所以你拥有的是未定义的行为.

同样令人感兴趣的是cv type qualifiers的这张纸条.

const object – an object whose type is const-qualified,or a non-mutable subobject of a const object. Such object cannot be modified: attempt to do so directly is a compile-time error,and attempt to do so indirectly (e.g.,by modifying the const object through a reference or pointer to non-const type) results in undefined behavior.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读