简体   繁体   English

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

[英]Size of an object without using sizeof in C++

This was an interview question: 这是一个面试问题:

Say there is a class having only an int member. 假设有一个班级只有一个int成员。 You do not know how many bytes the int will occupy. 您不知道int将占用多少字节。 And you cannot view the class implementation (say it's an API). 而且您无法查看类的实现(例如,这是一个API)。 But you can create an object of it. 但是您可以创建它的对象。 How would you find the size needed for int without using sizeof. 在不使用sizeof的情况下,如何找到int所需的大小。

He wouldn't accept using bitset , either. 他也不会接受使用bitset

Can you please suggest the most efficient way to find this out? 您能否建议最有效的方法来找出这一点?

The following program demonstrates a valid technique to compute the size of an object. 以下程序演示了一种计算对象大小的有效技术。

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

Using pointer algebra: 使用指针代数:

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

Yet another alternative without using pointers. 不使用指针的另一种选择。 You can use it if in the next interview they also forbid pointers. 如果他们在下一次面试中也禁止使用指针,则可以使用它。 Your comment "The interviewer was leading me to think on lines of overflow and underflow" might also be pointing at this method or similar. 您的评论“面试官让我思考上溢和下溢的问题”可能也指向这种方法或类似方法。

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

It gets the maximum value of an unsigned int (decrementing zero in unsigned mode) then subsequently divides by 2 until it reaches zero. 它获得unsigned int的最大值(在无符号模式下递减零),然后除以2,直到达到零。 To get the number of bytes , divide by CHAR_BIT . 要获得字节数,请除以CHAR_BIT

Pointer arithmetic can be used without actually creating any objects: 可以使用指针算术而无需实际创建任何对象:

class c {
    int member;
};

c *ptr = 0;
++ptr;
int size = reinterpret_cast<int>(ptr);

Alternatively: 或者:

int size = reinterpret_cast<int>( static_cast<c*>(0) + 1 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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