是否应使用未命名的结构或未定义的标记实现不透明指针?

时间:2014-05-07 21:14:52

标签: c++ pointers struct opaque-pointers

我目前正在设计一个API,允许用户传递一个不透明的指针,当他必须实现的接口的方法被调用时,他将在稍后传回。

这基本上归结为以下几点:

API侧:

class IAPIInterface
{
  public:
    virtual void APIMethod(CustomContext ctx) = 0;
}

void SetInterface(IAPIInterface* api, CustomContext ctx);

用户端:

class UserInterfaceImpl : public IAPIInterface
{
  public:
    virtual void APIMethod(CustomContext ctx) {...}
};


UserInterfaceImpl* userInterfaceImpl = new UserInterfaceImpl();

struct UserContext {...} userContext;

SetInterface(userInterfaceImpl, &userContext); // May need a cast

在该场景中定义不透明指针的最佳方法是什么?

基本上我想到了 typedef struct _CustomContext* CustomContext; 它定义了一个指向未定义(前向声明)结构的指针。

但我也想知道是否 typedef struct {} * CustomContext; 定义指向未命名结构的指针可能是一个很好的选择?我看到的主要问题是,如果包含在不同的翻译单元中,它可能会定义不同的结构。这是正确的吗?

当然,由于类型安全问题,我不想使用void*

1 个答案:

答案 0 :(得分:1)

如果你要强迫演员,为什么不只是void *

但你只是在这里写C。为什么同时传递接口和上下文 - 接口的实现是上下文;它是一个对象,它需要任何成员变量。

相关问题