跳转到内容

不透明指针

维基百科,自由的百科全书

程序设计中,不透明指针(Opaque pointer)是不透明数据类型英语Opaque data type的一种特殊情况,这种资料类型被声明为指向某种未指定类型的记录数据结构指针。不透明指针存在于艾达C语言C++D语言Modula-2 等多种编程语言

不透明指针是一种向普通客户端隐藏接口实现细节的方法。这对程序员也有好处,因为可以创建一个简单的接口,而大多数细节可以隐藏在另一个文件中[1]

例子

[编辑]

Ada

[编辑]
package Library_Interface is

   type Handle is limited private;

   -- Operations...

private
   type Hidden_Implementation;    -- Defined in the package body
   type Handle is access Hidden_Implementation;
end Library_Interface;
package body Library_Interface is

   type Hidden_Implementation is record
      ...    -- The actual implementation can be anything
   end record;

   -- Definition of the operations...

end Library_Interface;

[2]

/* obj.h */

struct obj;

/*
 * The compiler considers struct obj an incomplete type. Incomplete types
 * can be used in declarations.
 */

size_t obj_size(void);

void obj_setid(struct obj *, int);

int obj_getid(struct obj *);
/* obj.c */

#include "obj.h"

struct obj {
    int id;
};

/*
 * The caller will handle allocation.
 * Provide the required information only
 */

size_t obj_size(void) {
    return sizeof(struct obj);
}

void obj_setid(struct obj *o, int i) {
    o->id = i;
}

int obj_getid(struct obj *o) {
    return o->id;
}

C++

[编辑]
/* PublicClass.h */

#include <memory>

class PublicClass {
 public:
  PublicClass();                               // Constructor
  PublicClass(const PublicClass&);             // Copy constructor
  PublicClass(PublicClass&&);                  // Move constructor
  PublicClass& operator=(const PublicClass&);  // Copy assignment operator
  PublicClass& operator=(PublicClass&&);       // Move assignment operator
  ~PublicClass();                              // Destructor

  // Other operations...

 private:
  struct CheshireCat;                   // Not defined here
  std::unique_ptr<CheshireCat> d_ptr_;  // Opaque pointer
};
/* PublicClass.cpp */

#include "PublicClass.h"

struct PublicClass::CheshireCat {
  int a;
  int b;
};

PublicClass::PublicClass()
    : d_ptr_(std::make_unique<CheshireCat>()) {
  // Do nothing.
}

PublicClass::PublicClass(const PublicClass& other)
    : d_ptr_(std::make_unique<CheshireCat>(*other.d_ptr_)) {
  // Do nothing.
}

PublicClass::PublicClass(PublicClass&& other) = default;

PublicClass& PublicClass::operator=(const PublicClass &other) {
  *d_ptr_ = *other.d_ptr_;
  return *this;
}

PublicClass& PublicClass::operator=(PublicClass&&) = default;

PublicClass::~PublicClass() = default;

参考文献

[编辑]
  1. ^ Chris McKillop. Programming Tools — Opaque Pointers. QNX Software Systems. [2019-01-16]. (原始内容存档于2021-11-12). 
  2. ^ Robert A. Duff. Re: What's its name again?. Newsgroupcomp.lang.ada. 2002-07-29 [2007-10-11]. (原始内容存档于2009-07-29).