Can the link address of const be other than the address of the link object?

I am having problems with code equivalent to the following:

const auto &const_reference = some_object; assert(&const_reference == &some_object); 

When I compile it with the g ++ -O3 flag, it does not go through this statement. When it is compiled without optimization, the statement is passed.

As far as I know, even if there is UB in my project, such a situation cannot be possible.

Are there any circumstances where such link behavior is expected?

EDIT: Link to the actual code: https://github.com/Gray0Ed/ggp_thesis/blob/67606021020546b315ad63b7fd5c2203f3e0086f/rule_engine/aligner.cpp#L177 - the project is a bit dirty and it’s really not ready to be shown publicly, but not you are interested.

EDIT2: Since the source code for RustyX is different from the "equivalent" one above, check its answer to see the details.

+6
source share
1 answer

This code will always work:

  const auto &const_reference = some_object; assert(&const_reference == &some_object); 

The actual code that doesn't work is actually like this:

  const auto &oc = ai->var_infos[var_id].occurences[0]; assert(&oc == &ai->var_infos[var_id].occurences[0]); 

This does not work because you are overloading operator[] :

See MyArrays.hpp:

 T operator[](size_t i) const { assert(size >= 0); assert(i < size && i >= 0); return items[i]; } 

This returns a copy on every call.

This should probably be:

 const T& operator[](size_t i) const { assert(size >= 0); assert(i < size && i >= 0); return items[i]; } 
+4
source

All Articles