Given my variable being a pointer, if I assign it to a variable of “auto” type, do I specify the “*” ?
std::vector<MyClass> *getVector(); //returns populated vector
//...
std::vector<MyClass> *myvector = getVector(); //assume has n items in it
auto newvar1 = myvector;
// vs:
auto *newvar2 = myvector;
//goal is to behave like this assignment:
std::vector<MyClass> *newvar3 = getVector();
I’m a bit confused on how this auto works in c++11 (this is a new feature to c++11, right?)
Update: I revised the above to better clarify how my vector is really populated in a function, and I’m just trying to assign the returned pointer to a variable. Sorry for the confusion
Both of these are the same and will declare a pointer to
std::vector<MyClass>(pointing to random location, since. So basically you can use any one of them. I would prefermyvectoris uninitialized in your example and likely contains garbage)auto var = getVector(), but you may go forauto* var = getVector()if you think it stresses the intent (thatvaris a pointer) better.I must say I never dreamt of similar uncertainity using
auto. I thought people would just useautoand not think about it, which is correct 99 % of the time – the need to decorateautowith something only comes with references and cv-qualifiers.However, there is slight difference between the two when modifies slightly:
In this case,
newvar2will be a pointer (and something must be too).Here,
newvar2is the pointee type, eg.std::vector<MyClass>, and the initializer must be adequate.In general, if the initializer is not a braced initializer list, the compiler processes
autolike this:It produces an artificial function template declaration with one argument of the exact form of the declarator, with
autoreplaced by the template parameter. So forauto* x = ..., it usesIt tries to resolve the call
foo(initializer), and looks what gets deduced forT. This gets substituted back in place ofauto.If there are more declarators in a single declarations, this is done for all of them. The deduced
Tmust be the same for all of them…