Search code examples
c++c++11decltype

Using new with decltype


T *t; //T is an implementation detail
t = new T; //want to avoid naming T to allow for flexibility
t = new decltype(*t); //error: cannot use 'new' to allocate a reference
t = new std::remove_reference<decltype(*t)>::type(); //clunky

This answers why decltype(*t) returns T & and not T.

I can put my last line into a macro, but that seems suboptimal. Is there a better solution than what I have so far? Does this belong on Code Review?


Solution

  • If they're on the same line, you can use auto to only name T once:

    auto t = new T;
    

    Otherwise, you could create a small function template:

    template <class T>
    void do_new(T * &p) {
      p = new T;
    }
    
    
    // Usage:
    int main()
    {
      T *t;
      do_new(t);
    }
    

    As @MadScienceDreams pointed out, you can extend this to allow non-default constructors:

    template <class T, class... Arg>
    void do_new(T * &p, Arg &&... arg) {
      p = new T(std::forward<Arg>(arg)...);
    }
    
    
    // Usage:
    int main()
    {
      T *t;
      do_new(t);
      std::string *s;
      do_new(s, "Abc");
    }