C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Make all data pointers intercompatible

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Mon, 13 May 2024 07:59:08 +0000

1. I don’t know of a single compiler where the following doesn't do what you expect:
double var = 1.0;
double other = (*(double*)(void*)&var) * 2.0; // = 2.0

> And the Standard should also mandate that aliasing rules no longer apply once you cast a pointer. Consider the following function:
> void Func(double *const a, int const *const b)
> {
> *a += *(double*)b;
> *a += *(double*)b;
> }
>
> A compiler should be forbidden from optimising the above to:
>
> *a += *(double*)b * 2.0;
>
> because the cast from "int*" to "double*" turns off the aliasing rules, and so the compiler must accommodate the possibility that 'a'
> and 'b' point to the same double.

2. I completely disagree. It should be undefined behavior, and the compiler should do whatever it wants.
You advertised "a" as pointing to a "double", and you advertised "b" as pointing to "int const", if they were the same type you could have argued that the language is missing semantics to distinguish when pointers are assumed aliased and when they are assumed as strictly not, but they are clearly not.
You told it they are 2 different things and compilers should be free to make that assumption, that makes everyone's code better.
What you have here is just straight-out bad code, if I have ever saw this in a code review it would have been immediately rejected. There's no circumstance in which you need to advertise a double as an int (unless you are doing some nontrivial bit fidgeting, which rarely happens, and there are better ways to do it that don't require lying to the compiler), if that ever happens it is a good indication that you have a bad design, not that you need to change the standard to accommodate this obvious bad design.

Given 1 and 2, I don't see how this proposal would help anyone, in fact I believe what you want would actually hurt.

Received on 2024-05-13 07:59:14