Typedef const refers to a pointer

Possible duplicate:
Why is it allowed to point to a link pointer?

Why is this compiling:

class Bar {}; int main() { Bar i; Bar *b = &i; typedef const Bar& type; type t = type(b); } 

g ++ ( 4.5 , 4.7 snapshots), Comeau and MSVC are all happy, but warn of unused variables.

What does the compiler think? Is it UB? Why is this not a mistake?

I think this should be a mistake, because I accidentally made Bar* in const Bar& without dereferencing or crazy throws. I thought every part of it was completely safe.

+4
source share
3 answers

C-style listing in turn tries different types of C ++ translation:

[C++11: 5.4/5]: Conversions Performed

  • a const_cast (5.2.11),
  • a static_cast (5.2.9),
  • a static_cast followed by const_cast ,
  • a reinterpret_cast (5.2.10) , or
  • a reinterpret_cast followed by `const_cast ,

can be performed using an explicit type conversion letter. The same semantic restrictions and actions are used, except that when static_cast is executed in the following situations, the conversion is valid even if the base class is not available:

  • [..]

And then various complex rules follow, which I cannot bother to analyze in detail.

You get the necessary warnings that this is a stupid throw, but since this is what you asked for, you tried.

Compare with:

 class Bar {}; int main() { Bar *b = 0; typedef const Bar& type; const type t = static_cast<type>(b); } // In function 'int main()': // Line 6: error: invalid static_cast from type 'Bar*' to type 'const Bar&' // compilation terminated due to -Wfatal-errors. 
+4
source

Because you use it.

 class Bar {}; int main() { Bar *b = 0; typedef const Bar& type; const type t = b; (void)t; } 

In the above example, the following is the following error:

 error: invalid initialization of reference of type 'type {aka const Bar&}' from expression of type 'Bar*' 
+1
source

The links seem to reference pointers. Your expression is essentially

 Bar & r = reinterpret_cast<Bar&>(b); 

But in this explicit form, I get two warnings:

 warning: casting 'Bar*' to 'Bar&' does not dereference pointer [enabled by default] warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] 

But this is not a mistake, it would seem.

0
source

Source: https://habr.com/ru/post/1390273/


All Articles