const 값을 할당 할 수없는 이유는 무엇이며 대신 어떻게해야합니까?
-
13-09-2019 - |
문제
다음과 같은 대략적인 서명이있는 코드가 있습니다.
void evaluate(object * this)
{
static const int briefList[] = { CONSTANT_A, CONSTANT_Z };
static const int fullList[] = { CONSTANT_A, CONSTANT_B, ..., CONSTANT_Z};
const int const * pArray;
const int nElements;
int i;
if ( this->needDeepsEvaluation )
{
pArray = fullList;
nElements = sizeof(fullList) / sizeof(fullList[0]);
}
else
{
pArray = briefList;
nElements = sizeof(briefList) / sizeof(briefList[0]);
}
for ( i = nElements; i; i-- )
{
/* A thousand lines of optimized code */
}
this->needsDeepEvaluation = 0;
}
대부분의 컴파일러는 행복하게 앵무새의 할당을 삼키지 만, 릴리랑의 과제를 질식시킵니다. 이 불일치는 나를 혼란스럽게하고 깨달고 싶습니다.
Const Integer를 할당 할 수 없다는 사실을 받아들이는 데 아무런 문제가 없지만 Const-Pointer-to-Const에 대해 왜 예상대로 작동합니까?
빠르고 저렴한 수정 사항은 Const 예선을 떨어 뜨리는 것이지만 루프 내부의 많은 코드가 거대하기 때문에 미묘한 버그를 소개 할 수 있습니다 (한 번은 물론). 상수 요소 카운터를 허용하기 위해 위의 것을 어떻게 재구성 하시겠습니까?
해결책
당신의 선언에서 pArray
const int const * pArray;
두 'const'키워드는 실제로 적용됩니다 int
. 포인터에 적용하려면 int const * const pArray
, 포인터 자체가 불변이되지 않습니다. 그런 다음 컴파일러는 두 할당 모두에 오류를 던져야합니다.
다른 팁
Michiel이 지적했듯이, 당신의 선언은 다음과 같습니다.
const int const * pArray;
정확하지 않습니다.
당신은 네 가지 (4) 신디케이트 선택이 있습니다.
int * pArray; /* The pointer and the dereferenced data are modifiable */
int * const pArray; /* The pointer is constant (it should be initialized),
the dereferenced data is modifiable */
int const * pArray; /* the pointer is modifiable, the dereferenced data
is constant */
int const * const pArray; /* Everything is constant */
나는 Parray와 무슨 일이 일어나고 있는지 전혀 모른다. 그러나 Nelements의 경우 if-else 대신 3 가지를 사용할 수 있습니다.
const int nElements = this->needsDeepEvaluation ? sizeof(fullList) / sizeof(fullList[0]) | sizeof(briefList) / sizeof(briefList[0]);
삼개가 마음에 들지 않으면 랑산을 계산하는 작은 기능을 선언하고이를 사용하여 초기화하십시오.
제휴하지 않습니다 StackOverflow