自动初始化后变量的大小

时间:2015-08-15 15:25:42

标签: c++ c++11 auto initializer-list type-deduction

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

输出结果为:

  

int的大小是:4

     

浮点数的大小是:4

     

双倍的大小是:8

     

双倍的汽车大小是:8

     

双倍的汽车大小是:16

为什么sizeof(y) 16?

1 个答案:

答案 0 :(得分:7)

使用&#34; typeid&#34;与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

我认为&#34; auto y&#34;实际上并没有被赋予双重权限,而是其中之一: http://en.cppreference.com/w/cpp/utility/initializer_list

它说&#34;类型为std :: initializer_list的对象是一个轻量级代理对象,它提供对const T类型对象数组的访问。&#34;

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