Is there a downside to using auto for the return type

closed account (2z0kLyTq)
I'm brushing up on my c++ and my compiler warning told me that I could use auto with c++14. Seems very convenient, but I was wondering if there might be a downside to not specificly stating the return type.

I'll put some code below in case my question is not clear.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

// is there a downside to using auto instead of std::string?
auto print_str()
{ 
	auto str = "hello";
	return str;
}

int main(int argc, char** argv )
{
	std::cout << print_str() << "\n";
	return 0;
}
auto is used for data types which are cumbersome to write such as:
std::shared_ptr<std::array<wchar_t>> ptr = std::make_shared<std::array<whar_t>>();

now, auto helps us write better looking code:
auto ptr = std::make_shared<std::array<whar_t>>();

another use of auto is in templates where you don't know what the return type will be.
> I was wondering if there might be a downside to not specificly stating the return type.

A function with a deduced return type is usable only if its definition is visible at the point of use.

So it can be used only for functions that would be defined in a header file; inline functions, templates and functions with internal linkage.
Topic archived. No new replies allowed.