const_cast 的自动类型推导不起作用

Automatic type deduction with const_cast is not working

在我的工作中,const_cast 的使用在某些情况下是不可避免的。

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

我的第一个想法是写const_cast<>(myType),但是我的编译器无法推断出myType的非常量类型。所以我想帮助我的编译器,我设计了以下编译方法。

#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.

如果你有

void foo(const int& a)
{
    const_cast<int&>(a) = 4;
}

然后

int a = 1;
foo(a);

完全合法,但是

const int a = 1;
foo(a);

调用未定义的行为,因为在 foo 中,a 最初是 const

这在某些情况下很有用(通常在连接旧的 C 库时),但在大多数情况下,您做错了什么,应该重新考虑您的解决方案。

要回答为什么 const_cast<> 不是问题,我想说有两个原因。首先,当你做 const_cast 你应该真正知道你在做什么,如果允许某种模板推导,它会更容易发生意想不到的错误。其次 const_cast 也可以用来删除 volatile 编译器怎么知道你想扔掉什么?