1

I have:

std::map<double, Foo> map;
for (auto&& [first, second] : map) { /* ... */ }

where Foo is a class declared elsewhere

There are 2 issues that I see as it stands:

1. Mapped type constness

second here is Foo& which is correct, but you can also use std::as_const to make it const Foo&

for (auto&& [first, second] : std::as_const(map)) { /* ... */ }

so this is not a problem.

2. By value copy of built-in types

first here is const double& which is inefficient for built-in types.

Is there a way to make first be taken by value?

I'm sure this wasn't overlooked.

Deadfish
  • 64
  • 5
  • 1
    Why is `const &` inefficient for built-in types? – cigien Apr 16 '20 at 21:02
  • I've answered as best I can but, please, improve your question to state clearly what it is that you are trying to do, and why, and what the problem is that you experienced. At the moment there are loads of gaps where you forgot that we can't read your mind! – Asteroids With Wings Apr 16 '20 at 21:17

1 Answers1

0

first here is const double& which is inefficient for built-in types.

Are you thinking that the compiler will create a pointer, and a pointer dereference, to implement the reference?

That's not really true. Your compiler is smart.

This may be a consideration for function arguments because those can't be "optimised" in the same way across object boundaries, but that's not what you have here.

The following code:

int a = 42;
const int& b = a;
std::cout << b << '\n';

is the same program as:

int a = 42;
std::cout << a << '\n';

and it's going to compile to the same instructions.

Your for-loop example isn't much more complex than that.


second here is Foo& which is correct, but you can also use std::as_const to make it const Foo&

for (auto&& [first, second] : std::as_const(map)) { /* ... */ }

so this is not a problem.

So what's not a problem? There is no problem here.


tl;dr: Don't try to fix problems that don't exist.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35