c# - 防止在 C++ 中创建虚方法表

标签 c# c++

在 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/

相关文章:

c# - Qt 的 moc/C++11 是否具有 C# 的 nameof() 运算符的等效项?

c++ - MacOS 共享库 : Undefined symbols for architecture x86_64

c# - 从 C# 调用 C DLL

javascript - Promise.defer 的正确模式是什么?

c++ - 重载 << 运算符和递归

c++ - 关于比较字符串与字符串

c++ - 我正在尝试用 C++ 做一个方程式,但它一直输出 1

c++ - 为什么会发生内存访问冲突?

c# - Serilog MSSQL Sink 不会将日志写入数据库

c# - 使用 LINQ 检查 List<string> 是否包含另一个 List<string> 中的元素