2

Background information


Consider this simplified implementation of std::any (irrelevant parts omitted) and some code that uses it:

namespace std {
  namespace details {
    // Each instance of this function template has a different address
    template <typename T>
    const char *dummy_function() { return __PRETTY_FUNCTION__; }

    template <typename T> void *construct(T &&);
    void destroy(void *storage, const char *(*type_identifier)());
  }

  class any {
    const char *(*type_identifier)();
    void *storage;

  public:
    template <typename Arg>
    any(Arg &&arg)
      : type_identifier(&details::dummy_function<decay_t<Arg>>)
      , storage(details::construct(forward<Arg>(arg))) {}

    template <typename Arg>
    any &operator=(Arg &&arg) {
      details::destroy(storage, type_identifier);
      type_identifier = &details::dummy_function<decay_t<Arg>>;
      storage = details::construct(forward<Arg>(arg));
    }

    template <typename T>
    friend T *any_cast(any *source) {
      if (source && source->type_identifier == &dummy_function<T>)
        return static_cast<T *>(source->storage);
      return nullptr;
    }
  };
}
#include <any>

// Code that compares any::type_identifier a lot but never calls through it
std::any any = 42;
assert(std::any_cast<int>(&any) != nullptr);
assert(std::any_cast<double>(&any) == nullptr);

any = std::string("Hello");
assert(std::any_cast<std::string>(&any) != nullptr);
assert(std::any_cast<std::vector<char>>(&any) == nullptr);

If an optimizing compiler can prove that std::details::dummy_function<T> is never called in any manner throughout the program, is the compiler permitted to not include the function body of std::details::dummy_function<T> (along with the thereby unreferenced __PRETTY_FUNCTION__s) for any T in the compilation result (and even possibly make their addresses arbitrary pointer-sized integers that are just guaranteed to be distinct but otherwise may not even be valid memory addresses)?

(Or could even the addresses not guaranteed to be distinct for distinct Ts, which unfortunately means my implementation is incorrect to begin with?)

fghzxm
  • 1,185
  • 7
  • 19
  • 3
    Is it allowed to: Yes. Can it: In theory, if the compiler can prove that the function pointer is never called. In practice: Probably not, because the mentioned proof is difficult in general. – eerorika Feb 23 '20 at 04:42
  • Related: [What exactly is the “as-if” rule?](https://stackoverflow.com/q/15718262/978917) – ruakh Feb 23 '20 at 04:43
  • Also related: [Do distinct functions have distinct addresses?](https://stackoverflow.com/q/26533740/978917) – ruakh Feb 23 '20 at 04:45
  • The compller can't even determine that it's never called, given that someone has its address. – user207421 Feb 23 '20 at 10:37

0 Answers0