在 C# 中,作为值类型的结构可以在没有大小开销的情况下实现具有所有优点的接口(interface),请看这个片段:
interface IMove
{
void Move(Int32 l);
}
struct Point : IMove
{
public Int32 x;
public Int32 y;
public void Move(Int32 l)
{
this.x += l;
this.y += l;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Marshal.SizeOf(typeof(Int32))); // Prints "4"
Console.WriteLine(Marshal.SizeOf(typeof(Point))); // Prints "8"
}
}
但是当我尝试在 C++ 中实现它时,结构的大小变大了:
#include <iostream>
class IMove
{
public:
virtual void move(int l) = 0;
};
class Point : public IMove
{
public:
int x;
int y;
void move(int l)
{
this->x += l;
this->y += l;
}
};
int main()
{
std::cout << sizeof(int) << "\n"; // Prints "4"
std::cout << sizeof(Point) << "\n"; // Prints "12"
}
我认为是因为指向虚方法表的指针。是否可以在不增加对象大小开销的情况下实现类似的功能?
最佳答案
如果你真的不想存储额外的 v-table 指针的开销,你总是可以在将点作为 IMove 传递之前使用包装器对象:
struct Point { int x; int y; };
struct MoveablePoint : public IMove {
Point& point;
MovablePoint(Point& point) : point(point) {}
virtual void move(int l) { point.x += l; point.y += l; }
};
示例用法:
Point point = {0};
MovablePoint movablePoint(point);
doSomething(movablePoint);
现在,当您需要持久化时,无需存储 v 表。
关于c# - 防止在 C++ 中创建虚方法表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28932728/