使用 const_cast 进行自动类型推导不起作用 [英] Automatic type deduction with const_cast is not working
问题描述
在我的工作中,const_cast
的使用在某些情况下是不可避免的.
现在我必须const_cast
一些非常复杂的类型,实际上我不想在const_cast
表达式中编写所有这些类型的混乱,特别是如果<代码>杂乱很长.
我的第一个想法是编写 const_cast<>(myType)
,但我的编译器无法推导出 myType
的非常量类型.所以我想帮助我的编译器,我设计了以下方法,它可以编译.
#include #include int main(int, char**) {const int constVar = 6;using T = typename std::remove_cv::type;自动&var = const_cast<T&>(constVar);无功*= 2;std::cout <<&constVar <<" " <<&var <<"\n";//同一个地址!std::cout <<常量变量<<" " <<变量<<"\n";返回退出成功;}
不幸的是,程序给了我输出 6 12
而不是预期的 6 6
,我真的不明白?
我的方法有什么问题?
来自 const_cast
:
const_cast
可以形成一个指向实际指向 const 对象的非 const 类型的引用或指针,或者指向实际指向 volatile 的非 volatile 类型的引用或指针目的.通过非常量访问路径修改常量对象并通过非易失性泛左值引用易失性对象会导致未定义的行为.
所以你所拥有的是未定义的行为.
同样令人感兴趣的是来自 cv 类型限定符的注释.><块引用>
const object - 类型为 const 限定的对象,或 const 对象的非可变子对象.此类对象不能被修改:直接尝试这样做是编译时错误,并且尝试间接这样做(例如,通过引用或指向非常量类型的指针修改 const 对象)会导致未定义的行为.>
In my work the use of const_cast
is under some circumstances unavoidable.
Now I have to const_cast
some pretty complicated types and actually I don't want to write all this type clutter in the const_cast<Clutter>
expressions, especially if Clutter
is very long.
My first idea was to write const_cast<>(myType)
, but my compiler cannot deduce the non-const type of myType
. So I thought about helping my compiler and I deviced the following approach, which compiles.
#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;
}
Unfortunately, the program gives me the output 6 12
instead of the expected 6 6
, which I really didn't understand?
What is wrong with my approach?
From the documentation of 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.
So what you have is undefined behavior.
Also of interest is this note from 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.
这篇关于使用 const_cast 进行自动类型推导不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!