繁体   English   中英

在C ++中不使用sizeof的情况下对象的大小

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM