Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'new auto' in C++ constructor

Can C++ somehow accept this use of 'auto'?:

class A {
    public:
        A(): m_member(new auto)
        {
                [...]
        }

    private:
        BoringToTypeType *m_member;
}

The purpose is to take advantage of 'auto' by simplifying the member element initialisation in A's constructor. As it is, the code raises the following error:

new expression for type 'auto' requires a constructor argument.
like image 800
lackadaisical Avatar asked Aug 31 '25 03:08

lackadaisical


1 Answers

new auto(...) deduces the type of the resultant pointer from the expression passed inside (...). In your particular case there's nothing that can be deduced.

You have a few options:

  • m_member(new auto(x)), where x is an expression of type BoringToTypeType.

  • m_member(new std::remove_pointer_t<decltype(m_member)>), which is most certainly not an improvement over BoringToTypeType.

If you don't mind defining an additional helper function, here's an alternative solution:

template <typename T, typename... TArgs>
auto newer(T*, TArgs&&... args)
{
    return new T(std::forward<TArgs>(args)...);
} 

class A 
{
    public:
        A(): m_member(newer(m_member, 12))
        {

        }

    private:
        int *m_member;
};

In this case T is used purely for type deduction purposes. m_member has to be repeated twice, but you avoid typing out its type this way.

Simple tests on godbolt.org show that newer does not incur any additional overhead.

like image 87
Vittorio Romeo Avatar answered Sep 03 '25 02:09

Vittorio Romeo