What is the type of an 'auto' return type when returning *this in an anonymous class?
What is type of
auto
in here ?
The type is decltype(m_some_class)
- I.e., the return value is of the same type as the variable m_some_class
.
Note that the function will return a copy of *this
.
If a reference to *this
is wanted instead, you can use
auto&
or, since C++14, the more generic decltype(auto)
.
For anonymous structure types, internally the compiler creates a name and the auto in your case return the structure.
You can see below, that your anonymous structure is given name __anon_1_1
and the operator[]
function returns object of __anon_1_1
structure. m_some_class
is instance of type __anon_1_1
cppinsights website provides a way to understand
your code
struct
{
auto operator[](const char*)
{
return *this;
}
}m_some_class;
compiler version
struct __anon_1_1
{
inline __anon_1_1 operator[](const char *)
{
return __anon_1_1(*this);
}
// inline constexpr __anon_1_1() noexcept = default;
// inline constexpr __anon_1_1(const __anon_1_1 &) noexcept = default;
};
__anon_1_1 m_some_class = __anon_1_1();
The line in the given code:
return *this;
returns the struct m_some_class
itself, i.e. the type of the operator[]
is:
decltype(m_some_class); // i.e. the type returned is the same as the struct
Also, notice that this will only return a copy instance of the struct since the passed argument isn't given any reference-to operator. Any changes made to the copy of the struct won't affect the original struct.
What's the auto
keyword?
The auto
keyword is typically used in those situations when the type of something is not known to the programmer or it's too lengthy to type either.
Also, the type defined by auto
may vary dependent upon the various situations. For instance:
auto len = vector.size(); // len is now defined as size_t in compile time
In some systems, the type of len
maybe unsigned long
and in my case, it's unsigned long long
, here you can't explicitly define which qualifier to use correctly in this indeterminate place. Here we use auto
keyword.