可以优化 C++ class 中的引用存储吗?

Can storage for references inside a C++ class be optimized away?

C++ 语言是否允许打印以下代码,例如1 而不是 16?根据其他答案,我猜是的,但这种情况似乎没有具体涉及。

#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;
}

标准在 [dcl.ref] 下说:

It is unspecified whether or not a reference requires storage

此外,由编译器决定对象的大小,因此您可以在此处获得任何非零数字。

还有 as-if 规则(又名优化许可)。因此,当且仅当引用的使用方式需要时,编译器为这些引用使用存储是合法的。

说了这么多;为了拥有稳定的 ABI,我仍然希望编译器为这些引用分配存储空间。

C++ 标准中未指定编译器实现引用行为的方式(包括它们的存储位置和方式)。因此,一些编译器可以 "print e.g. 1 instead of 16" 正如你所要求的那样。

另外,您不需要 breakreturning 之后。

我相信

cout << sizeof(as_array) << endl;

始终returns 两个指针在给定机器上加倍所需的存储空间,可能会扩展间隙以满足打包规则。优化并不意味着减少给定数据结构的存储大小。相反,编译器可以在真实场景中完全优化您的代码。所以如果你有代码:

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

可以完全优化结构的存储,因为编译器知道如何通过您的代码处理这些值。但是 sizeof(arr) 的输出仍然给你结构的理论大小。

总之:如果你想获得更好的优化结果,你应该写更好的代码!如果它们是 const,请创建方法 const!如果您使用 c++11,请尽可能使用 constexpr。