[英]Size of an object without using sizeof in C++
這是一個面試問題:
假設有一個班級只有一個int成員。 您不知道int將占用多少字節。 而且您無法查看類的實現(例如,這是一個API)。 但是您可以創建它的對象。 在不使用sizeof的情況下,如何找到int所需的大小。
他也不會接受使用bitset
。
您能否建議最有效的方法來找出這一點?
以下程序演示了一種計算對象大小的有效技術。
#include <iostream>
struct Foo
{
int f;
};
int main()
{
// Create an object of the class.
Foo foo;
// Create a pointer to it.
Foo* p1 = &foo;
// Create another pointer, offset by 1 object from p1
// It is legal to compute (p1+1) but it is not legal
// to dereference (p1+1)
Foo* p2 = p1+1;
// Cast both pointers to char*.
char* cp1 = reinterpret_cast<char*>(p1);
char* cp2 = reinterpret_cast<char*>(p2);
// Compute the size of the object.
size_t size = (cp2-cp1);
std::cout << "Size of Foo: " << size << std::endl;
}
使用指針代數:
#include <iostream>
class A
{
int a;
};
int main() {
A a1;
A * n1 = &a1;
A * n2 = n1+1;
std::cout << int((char *)n2 - (char *)n1) << std::endl;
return 0;
}
不使用指針的另一種選擇。 如果他們在下一次面試中也禁止使用指針,則可以使用它。 您的評論“面試官讓我思考上溢和下溢的問題”可能也指向這種方法或類似方法。
#include <iostream>
int main() {
unsigned int x = 0, numOfBits = 0;
for(x--; x; x /= 2) numOfBits++;
std::cout << "number of bits in an int is: " << numOfBits;
return 0;
}
它獲得unsigned int
的最大值(在無符號模式下遞減零),然后除以2,直到達到零。 要獲得字節數,請除以CHAR_BIT
。
可以使用指針算術而無需實際創建任何對象:
class c {
int member;
};
c *ptr = 0;
++ptr;
int size = reinterpret_cast<int>(ptr);
或者:
int size = reinterpret_cast<int>( static_cast<c*>(0) + 1 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.