Effective C++: sizeof

sizeof运算符(unevaluated expression): 返回一条表达式或者一个类型名字所占的字节数.返回值得类型为std::size_t.ios

也就是说sizeof的返回值是在编译期完成的!express

主要有如下两种形式:数组

sizeof (type);安全

sizeof expr;lua

在sizeof的运算对象中解引用一个无效的指针仍然是一种安全的行为,由于指针实际上并无被正在的使用。sizeof不须要真正的解引用也能知道指针所指的类型.spa

其次呢:指针

1,sizeof运算符的结果依赖于其做用的类型.code

2,对char类型或者结果为char类型的表达式执行sizeof运算符,结果为1.对象

3,对引用类型执行sizeof运算符获得被引用对象所占的空间大小.it

4,对于解引用指针指向sizeof运算符获得指针所指对象的类型,指针不须要有效.

5,若是是动态分配出来的数组或者其余的class,sizeof获得老是地址所占的bytes.

 

如下demo均是在64bit的win7下的vs15中完成.

demo1:

#include <iostream>
 
struct Empty {};
struct Base { int a; };
struct Derived : Base { int b; };
struct Bit { unsigned bit: 1; };
 
int main()
{
    Empty e;
    Derived d;
    Base& b = d;
    Bit bit;
    int a[10];
    int* f = new int[2];

     
    std::cout << "size of empty class: "              << sizeof e          << '\n' //不管是32bit仍是64bit的系统都为1.
              << "size of pointer : "                 << sizeof &e         << '\n' //32bit的系统为4, 64bit的系统为8.
//            << "size of function: "                 << sizeof(void())    << '\n'  // error 
//            << "size of incomplete type: "          << sizeof(int[])     << '\n'  // error
//            << "size of bit field: "                << sizeof bit.bit    << '\n'  // error
              << "size of array of 10 int: "          << sizeof(int[10])   << '\n'
              << "size of array of 10 int (2): "      << sizeof a          << '\n'
              << "length of array of 10 int: "        << ((sizeof a) / (sizeof *a)) << '\n'
              << "length of array of 10 int (2): "    << ((sizeof a) / (sizeof a[0])) << '\n'
              << "size of the Derived: "              << sizeof d          << '\n'
              << "size of the Derived through Base: " << sizeof b          << '\n'
              << sizeof(f)<< std::endl; //结果为4在x86下,若是是x64为8
 
}

 

demo2:

#include <iostream>

struct A {};
struct B : public virtual A {};
struct C : public virtual A {};
struct D : public B, public C {};


struct E : public A {};


int main()
{
	std::cout << sizeof(A) << '\n'
		<< sizeof(B) << '\n' //32bit为4, 64bit为8
		<< sizeof(C) << '\n'  //同上
		<< sizeof(D) << std::endl; //32bit为8, 64bit位16

	std::cout << std::endl;
	std::cout << sizeof(E) << std::endl; //不管是32bit下仍是64bit下均为1.

	return 0;
}
相关文章
相关标签/搜索