dimanche 28 juin 2015

Template class optimizations during compiling

I was curious to know the internals of template class compilation in specific circumstances. I ask this because I'd like to extend some existing classes.

For example, let's assume a starting

template<typename T>
class LargeClass {
  private:
    std::unique_ptr<T> data;
    // many other fields

  public:
    const std::unique_ptr<T>& getData() { return data; }
    void setData(T* value) { data = std::unique_ptr<T>(value); }
    // many other methods that don't depend on T
}

This example makes me think that, since sizeof(std::unique_ptr<T>) == sizeof(T*) (without a custom deleter) then sizeof(LargeClass<T1>) == sizeof(LargeClass<T2>) for any T1 and T2. Which implies that all offsetof(field, LargeClass<T>) are the same for any field and T.

So why the compiler would create a copy of each LargeClass method if they don't depend on T?

A different approach, like

class LargeClass {
  private:
    T data
    ...

  private
    ...
}

instead should force the compiler to create multiple definitions of the methods for different types since sizeof(T) could change, but using an std::aligned_storage with a static_assert (to avoid storing too large data) could make this fallback to the first case. Would a compiler be smart enough to realise it?

In general I was wondering if a compiler is smart enough to avoid generating multiple definition of a template class method if the type variable is not used and the class structure doesn't change (or at least doesn't change for accessing the fields accessed in the method) or not. Does the standard enforce anything about it?

Aucun commentaire:

Enregistrer un commentaire