> Would the compiler be allowed to optimize out the non-const phase of i and put it into read-only-memory?

Yes, if it is able to determine what the value would be at compile time, and there are no other observable side-effects.

Otherwise it would have to treat it as if the value could only be known at runtime (like when an arguments is passed to a function).

 

> Would the compiler be allowed to relocate i between non-const memory and read-only-memory and print out two different addresses?

That’s a really good question.

 

I think the behavior should be equivalent to:

 

int i = 0;

std::cout << &i << std::endl;

const int& i2 = i;

std::cout << &i2 << std::endl;

 

Very unsure about this one.

 

 

 

From: Std-Proposals <std-proposals-bounces@lists.isocpp.org> On Behalf Of Sebastian Wittmeier via Std-Proposals
Sent: Sunday, February 16, 2025 5:00 PM
To: std-proposals@lists.isocpp.org
Cc: Sebastian Wittmeier <wittmeier@projectalpha.org>
Subject: Re: [std-proposals] Delayed const declaration

 

For

 

int i = 0;

const i;

std::cout << &i << std::endl;

 

 

Would the compiler be allowed to optimize out the non-const phase of i and put it into read-only-memory?

 

 

For

 

int i = 0;

std::cout << &i << std::endl;

const i;

std::cout << &i << std::endl;

 


Would the compiler be allowed to relocate i between non-const memory and read-only-memory and print out two different addresses?