Anna K. Anna K. -3 years ago 46
C++ Question

`auto` making a new variable instance each time?

I'm wondering if using

auto
, or anything other like declaring a variable/iterator/CallItWhatIsMoreAppropriate) will create an instance of that item each time? An example will make things clear:

void my_fun (std::unordered_map<std::string, std::string> & my_map) {

std::string search_str;

cin >> search_str;

while (search_str != "something") {

//Does the next line create an extra overhead each time?
auto search = my_map.find(search_str);

if (search != my_map.end())
{
std::cout << "found \n";

//I should be able to modify the element inside the map here.

} else {
my_map.insert( {search_str, search_str});
}

cin >> search_str;

}

}

Answer Source

Considering this particular code:

while (search_str != "something") {

     //Does the next line create an extra overhead each time?
     auto search = my_map.find(search_str);

if you mean if there is extra overhead vs:

  while (search_str != "something") {
        //Does the next line create an extra overhead each time?
        std::unordered_map<std::string, std::string>::iterator search = my_map.find(search_str);

no there is no difference at all, compiler just deduces type for you. If you asking if declaring iterator outside of loop:

  std::unordered_map<std::string, std::string>::iterator search;
  while (search_str != "something") {
        search = my_map.find(search_str);
        ...

would make it more efficient, it is theoretically possible (on some broken compiler) but I hardly doubt there would be any. And code readability is more important here as variant with declaring variable inside loop would make it cleaner and more readable.

Note change search type either to const auto & or more explicit const std::unordered_map<std::string, std::string>::iterator & also very unlikely to make it more efficient in this case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download