c++template-meta-programming

C++ check if const qualified variables are the same object at compile-time


I am working on a project that uses some compile-time logic based on whether two arguments are the same object (i.e. same memory address). The following is a simplified example that compiles and runs as hoped on my machine with c++20 standard and GNU compiler:

#include <iostream>

template <typename T1, typename T2>
consteval bool is_same_object(T1 const& a, T2 const& b) 
{return &a == &b;}

int main()
{
    const int x(1),y(1);

    std::cout << is_same_object(x, y) << std::endl; // Should print 0 (false)
    std::cout << is_same_object(x, x) << std::endl; // Should print 1 (true)

    return 0;
}

Because memory addresses are typically assigned at runtime (to the best of my knowledge), I am unsure if this design pattern will be portable and robust. Will this comparison reliably work or are there better ways of accomplishing this? What restrictions should one be aware of when using such comparisons for template metaprogramming?


Solution

  • So to summarize several comments and to add some more details:
    No, your code will not relyably work.

    Short answer:
    What will work as expected is:

    What may not work as expected is:

    Detailed anser:

    Side note:
    Remember that the final code does not run as C++, but as assembler code and that some C++ variables may never occupy any address.
    Assembler code performs the computations in registers and uses the addresses mainly to load or save information. For some simple constant numeric values it can be possible to load the content directly from the assembler code into the register without the need of a RAM address.
    Also for local variables it can be possible that they are optimized out so that they only appear temporarily in a register and never require a RAM address.
    Of course, when you write code which operates on addresses then such optimizations won't happen, so your code is not affected by this.