Mathieu Van Nevel
Mathieu Van Nevel

Reputation: 1486

Q : std::tuples / std::array

I've always thinking std::tuple was something fancy but not really efficient.

But I learned that tuple are contiguous memory because of the rules of object layout. I know that tuples are generate by inheritance and that's why we can't have dynamic tuples. But at this point that's mean that tuples are crazy good std::array which can contains any type without any drawbacks.

Seems to me a little too powerful said like that.

So I wonder, how are tuples inside the memory? There is really no other problems to tuples?


Thanks to the answers which cleared my mind I got one big question

Is a "big" struct (can't really write a big one here) like

struct Foo {
  int a;
  float b;
  double c;
};

as cache friendly than an array like

std::array<double, 3>

I need to often access to an element and change it. So I wonder if a computer will save a big struct in cache memory as easily than an array.


Anyway thanks

Upvotes: 0

Views: 727

Answers (1)

eerorika
eerorika

Reputation: 238351

I've always thinking std::tuple was something fancy but not really efficient.

As you now know, this is nonesense. Tuple is typically as efficient as a regular class with the same members.

I know that tuples are generate by inheritance and that's why we can't have dynamic tuples.

Inheritance is one (typical) approach to implement tuples. You cannot have dynamic tuples, because std::tuple is a template. Templates are instantiated at compile time.

But at this point that's mean that tuples are crazy good std::array which can contains any type without any drawbacks.

Comparing arrays and tuples is like comparing apples to oranges. Being able to construct a tuple of multiple types is just as much a drawback as it is an advantage. Arrays and tuples are used for different things.

A more apt comparison is with a regular class structure, with the same members. The main advantage of tuple is that it can be generated by template arguments. The main disadvantage of tuple is that you cannot name the members.

So I wonder, how are tuples inside the memory?

Depends on how the tuple is implemented. In practice, it is typically very similar to the layout of a class with the same members. But not necessarily identical. In particular, the order of the members in memory may or may not be reversed.

There is really no other problems to tuples?

You ask of other problems, but you haven't demonstrated any problem with them. Tuples have their niche and they are useful. If you try to use them outside of their useful context, then you can find problems.

is a big struct as cache friendly as an array?

Tuples, other classes, and arrays are all very similar. They are all flat containers of subobjects (the members). They are each as friendly and as unfrinedly to the cache as the other.

Upvotes: 1

Related Questions