c++addressof

Is it possible to stop std::addressof on my objects?


For some educational reason I managed to stop others from taking the address of my class objects through overloading the reference operator & as a deleted member function or as a private method. But C++11 presents a new templated-function std::addressof which returns the address of an object. So I want also to disable it, however I'm stuck in half-solution. Here is my code try:

#include "stdafx.h"
#include <memory>


class Foo {
public:
    Foo* operator&() = delete; // declared deleted so no one can take my address
    friend Foo* addressof(Foo&) = delete; // ok here.
private:
    // Foo* operator&() { return nullptr; } // Or I can declare it private which conforms to older versions of C++.

};


int main() {

    Foo f{};
//  std::cout << &f << std::endl;
//  std::cout << addressof(f) << std::endl; // ok
    std::cout << std::addressof(f) << std::endl;// Why I can't stop `std::addressof()`?

    std::cout << std::endl;
}

As you can see if I call addressof which is a friend template function to my class then it works fine. But if someone calls std::addressof on my class object the compiler doesn't prevent him.

I need some way to stop std::addressof to not be called on my objects.

Thank you guys.


Solution

  • No.

    The whole point of std::addressof is to allow people to find the address of the object when the author has tried to make this difficult/obfuscated/awkward.

    There is no way, provided by the language, to disable or inhibit it. This is a feature.

    Speaking practically, you could possibly fake it by specialising std::addressof for your type if you don't mind your program having undefined behaviour as a result! (Seriously, don't do this…).