Is it possible to optimize storage for links inside a C ++ class?

Does the C ++ language provide the following code for printing, for example. 1 instead of 16? According to other answers, I would suggest that yes, but this case does not seem to have been covered.

#include "iostream" #include "cstdlib" using namespace std; struct as_array { double &a, &b; as_array(double& A, double& B) : a(A), b(B) {} double& operator[](const int i) { switch (i) { case 0: return this->a; break; case 1: return this->b; break; default: abort(); } } }; int main() { cout << sizeof(as_array) << endl; } 
+6
source share
3 answers

The standard says in [dcl.ref]:

It is not indicated whether a storage link is needed

In addition, the compiler must decide what size the object is, so you can get any non-zero number here.

There is also an as-if rule (for example, permission to optimize). Therefore, it would be useful for the compiler to use storage for these links if and only if it required the use of links.

Having said all this; in the interest of having a stable ABI, I would still expect the compiler to assign storage to these links.

+5
source

The way the compiler implements reference behaviors, including where and how they are stored, is not specified in the C ++ standard. Therefore, some compilers may β€œprint, for example, 1 instead of 16,” as you ask.

Separately, you do not need to break after return ing.

+2
source

I think that

 cout << sizeof(as_array) << endl; 

always returns the required storage for two pointers to double on a given machine, possibly with breaks, to comply with packing rules. Optimization has helped reduce the size of the data structure data warehouse. Instead, the compiler can fully optimize your code in the real world. Therefore, if you have code:

 double a=100; double b=200; as_array arr(&a, &b); std::cout << arr[0] << std::endl; 

can lead to full storage optimization for the structure, since the compiler knows how these values ​​are processed through your code. But listing sizeof (arr) still gives you the theoretical size of the structure.

In any case: if you want to improve optimization results, you should write better code! Create const methods if they are const ! If you are using C ++ 11, use constexpr if possible.

+2
source

Source: https://habr.com/ru/post/989174/


All Articles