I am puzzled by std::is_const
's behaviour in identifying a const
pointer as non-const
.
My own implementation of is_const
does exactly the same thing. I'm not sure why the more general templated struct <T>
is being picked over the <const T>
version. Both gcc4.7 and clang3.1-svn show the same behaviour. Can anyone explain what's going on? Code is given below:
#include <iostream>
#include <sstream>
#include <type_traits>
class CEmptyClass {};
namespace jbc
{
template <typename T>
struct is_const : std::false_type {};
template <typename T>
struct is_const<const T> : std::true_type {};
}
int main(int argc, char* argv[])
{
std::cout << "Is 'const CEmptyClass*' constant according to std lib : "
<< std::is_const<const CEmptyClass*>::value << std::endl;
std::cout << "Is 'const CEmptyClass*' constant according to jbc : "
<< jbc::is_const<const CEmptyClass*>::value << std::endl;
}
In both instances is_const<const CEmptyClass*>::value
returns 0
The declaration of const data merely requires that the const precede the *, so either of the following two declarations are valid. type const * variable; The memory address stored in a pointer to constant data cannot be assigned into regular pointers (that is, pointers to non-const data) without a const cast.
Changing Value of a const variable through pointerBy assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier.
A const pointer to a const value can not have its address changed, nor can the value it is pointing to be changed through the pointer. It can only be dereferenced to get the value it is pointing at.
Note: It is necessary to initialize the constant pointer during declaration itself, unlike a normal pointer which can be left uninitialized. <data type> * const <pointer name> = <memory address>; Note: Here the const keyword must appear after the * in the declaration.
There is no such thing as a const
reference, a reference is never const
. Code like this does not compile:
int& const i;
Now if you were to remove your reference, it would work. If you were to place const
on the right side (semantically is the same thing), and read the type backwards
CEmptyClass const&
it would read a reference to a const CEmptyClass, not a const reference to an CEmptyClass.
Update: Now that you changed the reference to a pointer, the same misconstruction persist:
const CEmptyClass*
CEmptyClass const*
both are the same, a non-const pointer to a const CEmptyClass
CEmptyClass* const
is a const pointer to a CEmptyClass
and
const CEmptyClass* const
CEmptyClass const* const
are a const pointer to a const CEmptyClass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With