Solved Question about "auto" keyword in combination with "new"
-
Hi all C++ gurus, I have a question about
auto
usage with pointers.
Is there a difference for this two declaration?auto var1 = new MyClass(); auto* var2 = new MyClass();
Is one preferable to ensure C++ compiler compatibility (msvc, gcc, clang)?
Or those it not mather? -
Hi @KroMignon,
Is there a difference for this two declaration?
auto var1 = new MyClass();
auto* var2 = new MyClass();No, they are equal.
Is one preferable to ensure C++ compiler compatibility (msvc, gcc, clang)?
I'm not sure if there are compiler differences, they should all handle both without problems; so it's more a matter of style.
E.g. in QtCreator we use
auto ptr = new Ptr();
(without asterisk).Regards
-
@aha_1980 said in Question about "auto" keyword in combination with "new":
No, they are equal.
In almost all cases!
A quick google search resulted in this stack overflow thread:
https://stackoverflow.com/questions/12773257/does-auto-type-assignments-of-a-pointer-in-c11-require🤷♂️
-
-
@KroMignon said in Question about "auto" keyword in combination with "new":
Is there a difference for this two declaration?
Not sure if you noticed, but if you hover over the "auto" keyword with the mouse in Qt Creator it tells you the type it has deduced most of the time.
-
@KroMignon
Apparently it does have a use:
https://en.cppreference.com/w/cpp/language/autoIs particular:
auto i = 0, *p = &i;
In this case auto is deduced as int. So *p is a pointer to int.
-
@fcarney said in Question about "auto" keyword in combination with "new":
auto i = 0, *p = &i;
But this is nothing special to the auto keyword. It's C basic.