What is the difference between std::addressof<>(var) and &var ?

 int var = 42; std::cout << std::addressof(var); std::cout << '\n'; std::cout << &var; 

    2 answers 2

    The difference is that the unary operator & can be overloaded for class or enum types, do something foreign and return something that has nothing to do with the address of the object. And std::addressof always returns exactly the address of the object. For example, when writing a template code to get the address of an object of some generalized type T , you should use std::addressof , and not unary & , thus you protect your sample code from "surprises".

    For int var there is no difference.

      std::addressof cannot be used to get the address of a non-static method or a class field.

      • Can you give an example of how to do this for & ? - titan
      • @HolyBlackCat struct foo{void bar1(void) {}}; auto p = ::std::addressof(foo::bar1); // ошибка struct foo{void bar1(void) {}}; auto p = ::std::addressof(foo::bar1); // ошибка struct foo{void bar1(void) {}}; auto p = ::std::addressof(foo::bar1); // ошибка - VTT
      • @titan struct foo{void bar1(void) {}}; auto p = &foo::bar1; // ок struct foo{void bar1(void) {}}; auto p = &foo::bar1; // ок struct foo{void bar1(void) {}}; auto p = &foo::bar1; // ок - VTT
      • @VTT: Error in std::addressof(foo::bar1) has nothing to do with std::addressof . In C ++, foo::bar1 no longer a valid expression in itself, even at the syntax level. In an expression, the syntax foo::bar1 can be applied only after & or before () . - AnT
      • @AnT struct foo{static void bar1(void) {}}; auto p = ::std::addressof(foo::bar1); // OK struct foo{static void bar1(void) {}}; auto p = ::std::addressof(foo::bar1); // OK struct foo{static void bar1(void) {}}; auto p = ::std::addressof(foo::bar1); // OK - VTT