自动初始化后变量的大小

size of variable after auto initialization

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    int    i{100};
    float  f{3.14};
    double d{3.14159};
    cout<<"size of int is: "   <<sizeof(i)<<endl;
    cout<<"size of float is: " <<sizeof(f)<<endl;
    cout<<"size of double is: "<<sizeof(d)<<endl<<endl;;

    auto x = sin(3.14159);
    cout<<"size of auto that is double is: "<<sizeof(x)<<endl<<endl;

    auto y{sin(3.14159)};
    cout<<"size of auto that is double is: "<<sizeof(y)<<endl;
    return 0;
}

输出为:

size of int is: 4

size of float is: 4

size of double is: 8

size of auto that is double is: 8

size of auto that is double is: 16

为什么 sizeof(y) 16?

使用 "typeid" 和 gcc 4.8.4 如下:

#include <iostream>
#include <math.h>
#include <typeinfo>

using namespace std;

int main() {
    int    i{100};
    float  f{3.14};
    double d{3.14159};
    cout<<"size of int is: "   <<sizeof(i)<<endl;
    cout<<"size of float is: " <<sizeof(f)<<endl;
    cout<<"size of double is: "<<sizeof(d)<<endl<<endl;;

    auto x = sin(3.14159);
    cout<<"size of auto that is double is: "<<sizeof(x)<<endl<<endl;

    auto y{sin(3.14159)};
    cout<<"size of auto that is double is: "<<sizeof(y)<<endl;

    cout << typeid(y).name() << endl;

    return 0;
}

我得到以下输出:

$ ./main 
size of int is: 4
size of float is: 4
size of double is: 8

size of auto that is double is: 8

size of auto that is double is: 16
St16initializer_listIdE

我认为 "auto y" 实际上并没有被分配两次,而是其中之一: http://en.cppreference.com/w/cpp/utility/initializer_list

它说 "An object of type std::initializer_list is a lightweight proxy object that provides access to an array of objects of type const T. "

所以额外的 space 很可能用于存储指针和向量的大小,或类似的东西。