Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Auto and Void?

I am reading the C++ Primer Book (fifth edition) and I have a question upon the book i am reading. It says:

The type void* is a special pointer type that can hold the address of any object. Like any other pointer, a void* pointer holds an address, but the type of the object at that address is unknown.

Ok, so I understand that but… I have many contradictions to the statement. First of all, can't you use auto? Doesn't it do the same thing as void? Meaning aren't

void *somePtr;

and

auto *somePtr;

the same?

Second of all it says the type of the attached address is unknown. Can't you use typeid to get the type? Like this:

int a = 5;
auto *somePtr = 5;
std::cout << typeid(*somePtr).name() << std::endl;
like image 394
amanuel2 Avatar asked Nov 29 '22 06:11

amanuel2


2 Answers

Did you try running your examples through a compiler? As it happens, neither

auto * p;  // error

nor

int a = 0;
void * p = &a;
std::cout << typeid(*p) << '\n';  // error

will compile while both

void * p;

and

int a = 0;
auto * p = &a;
std::cout << typeid(*p) << '\n';

are fine.

To give an informal and easy to remember analogy for void * and auto *, think of void * p as telling the compiler

Don't care about what p pointer points to, I'll handle it myself (at run-time).

whereas auto * p = (expression) tells the compiler

Please figure out for me (at compile-time) what (pointer) type (expression) evaluates to and make the type of p be accordingly.

As a matter of fact, auto * is rarely useful. You can simply write auto instead and if the initializing expression is a pointer type, the auto will be deduced to be a pointer, too.

like image 156
5gon12eder Avatar answered Nov 30 '22 20:11

5gon12eder


auto uses compile-time type inference: the variable has a definite type which is its correct type, however the type is inferred from its value. Throughout the lifetime of the auto variable, the compiler will ensure that it is being used in accordance with its actual inferred type

void* can indeed hold the address of any object, but as opposed to auto, you must explicitly convert the void* pointer to a different type before using it. Unlike auto that conversion is explicit, and unlike auto the compiler cannot warn about improper usage.

like image 22
Mark Nunberg Avatar answered Nov 30 '22 20:11

Mark Nunberg