Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c++ - using type alias doesn't work with "const" pointer

Here, const pointer hold the address of const variable. like :

#include <iostream>

int main() 
{    
    const int i = 5;
    const int* ptr = &i;
}

It's working fine.

But, If I use using (Type alias) like:

#include <iostream>

using intptr = int*;

int main() {    
    const int i = 5;
    const intptr ptr = &i;
}

GCC compiler gives an error. [Live demo]

Why pointer does not work with using Type alias?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

const intptr ptr is an equivalent of int * const ptr - const pointer to non-const int, not const int * ptr - non-const pointer to const int.

If you find such right-to-left reading order for pointer declarations confusing you can utilize Straight declarations library which supplies alias templates to declare pointer types with left-to-right reading order:

const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...