我找不到太多的信息const_cast.我能找到的唯一信息(在Stack Overflow上)是:
将
const_cast<>()用于添加/删除变量的常量(岬)(或挥发性岬).
这让我很紧张.可能const_cast会导致意外行为?如果是这样,什么?
或者,什么时候可以使用const_cast?
想象一下,我有这个C函数(以及头文件中的相应原型)
void clearstring(const char *data) {
char *dst = (char *)data;
*dst = 0;
}
Run Code Online (Sandbox Code Playgroud)
有未定义行为在上面的代码,铸造const走,或者是它只是一个非常不好的编程习惯?
假设没有使用const限定对象
char name[] = "pmg";
clearstring(name);
Run Code Online (Sandbox Code Playgroud) 我想知道以下是否是未定义的行为
// Case 1:
int *p = 0;
int const *q = *const_cast<int const* const*>(&p);
// Case 2: (I think this is the same)
int *p = 0;
int const *const *pp = &p;
int const *q = *pp;
Run Code Online (Sandbox Code Playgroud)
这是一种未定义的行为,通过读取int*它就像是一个int const*?我认为这是未定义的行为,但我以前认为只添加const一般是安全的,所以我不确定.
class armon
{
static const int maxSize=10;
int array[maxSize];
int count=0;
int* topOfStack=array;
}
Run Code Online (Sandbox Code Playgroud)
为什么maxSize需要static在数组中使用它?
在C++程序中,我有一个结构,其中包含指向其自己类型的另一个实例的指针:
struct Foo
{
const Foo* ptr;
};
Run Code Online (Sandbox Code Playgroud)
我想声明并初始化这个结构的两个const实例,它们指向彼此:
const Foo f1 = {&f2};
const Foo f2 = {&f1};
Run Code Online (Sandbox Code Playgroud)
但是,这会导致编译时错误error: 'f2' was not declared in this scope(显然因为f1在f1之后声明,即使f1的声明引用它).
我正在努力做到可能和合理吗?如果是,我该如何使它工作?
一种解决方法可能是避免使f1 const,然后在声明f2之后重新分配指针f1.ptr = &f2;,但是如果可以的话我宁愿避免这种情况.