Reputation: 1720
I have always thought that auto
should be used in the following form auto varName = someOtherVar;
. Today I have found that I could also use auto varName(someOtherVar);
. At first I thought that maybe this is Argument Depending Lookup at work. But I am not sure. What are the restrictions for using such auto syntax? Below is some code:
#include <iostream>
#include <string>
#include <vector>
class Person {
public:
Person(std::string s) : name(s) {}
Person(const Person& p) : name(p.name) {}
std::string name;
};
int main()
{
Person p("hello");
auto p2(p); // equivalent to auto p2 = p; ?
std::cout << p2.name;
}
Upvotes: 0
Views: 63
Reputation: 141554
auto
may be used in place of the type specifier in a declaration with initializer; then the type is deduced from the initializer.
T a = b;
is called copy initialization , T a(b);
is called direct initialization , there are subtle differences.
So auto p2(p);
is the same as Person p2(p);
. Since the initializer has the same type as the object being initialized, copy-initialization and direct-initialization are identical in this case.
"Argument-dependent lookup" refers to resolving the scope of a function name. But this is an object declaration, not a function call. (There is ADL on the line std::cout << p2.name;
though - operator<<
resolves via ADL to std::operator<<
).
Upvotes: 2