C++ 包装类的含义是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5307169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:52:30  来源:igfitidea点击:

What is the meaning of a C++ Wrapper Class?

c++classwrapper

提问by Mahesh

I have a little trouble in understanding a wrapper class. It would be great if some one could help providing apt examples.

我在理解包装类时遇到了一些麻烦。如果有人可以帮助提供恰当的示例,那就太好了。

  1. What is a C++ Wrapper Class and what are the circumstances of writing it ?
  2. What is it's use any way ?
  1. 什么是 C++ 包装类,编写它的环境是什么?
  2. 它有什么用?

Thanks.

谢谢。

采纳答案by GManNickG

A "wrapper class" is a de facto term meaning a class that "wraps around" a resource; i.e, that manages the resource. When people write a wrapper, then, they are doing something like this:

“包装类”是一个事实上的术语,意思是“包装”资源的类;即,管理资源。当人们编写包装器时,他们正在做这样的事情:

class int_ptr_wrapper
{
public:
    int_ptr_wrapper(int value = 0) :
    mInt(new int(value))
    {}

    // note! needs copy-constructor and copy-assignment operator!

    ~int_ptr_wrapper()
    {
        delete mInt;
    }

private:
    int* mInt;
};

This class manages ("wraps") a pointer to an int. All resources should be wrapped in some fashion, for cleanliness (no explicit clean up code or noise) and correctness (destructor is guaranteed to run; cannot forget to clean up, and safe with exceptions).

此类管理(“包装”)指向int. 所有资源都应该以某种方式包装,以保持清洁(没有明确的清理代码或噪音)和正确性(保证析构函数运行;不能忘记清理,并且安全有异常)。

This pattern is called Scoped-bound Resource Management (SBRM), though a far more common (but most esoteric) name is Resource-Acquisition is Initialization (RAII). The idea is to bind a resource's clean-up to a destructor, for the reasons given above: the scope handles the rest.

这种模式称为范围绑定资源管理 (SBRM),尽管更常见(但最深奥)的名称是资源获取即初始化 (RAII)。这个想法是将资源的清理绑定到析构函数,出于上述原因:作用域处理其余的。

Note that I said it was missing a copy-constructor and copy-assignment operator. This is due to the Rule of Three. (See linked question for detailed explanation.) The simplest way to correctly implement this rule is with the copy-and-swap idiom, explained here.

请注意,我说它缺少复制构造函数和复制赋值运算符。这是由于三规则。(有关详细说明,请参阅链接问题。)正确实施此规则的最简单方法是使用复制和交换习语,在此处解释。



Sometimes, it's not pragmatic to write wrapper class for resource clean-up, usually when the resource is unique or used once. (Or with transactional programming.) The solution to this is called scope guard, a way of writing clean-up code inside the function that needs it.

有时,为资源清理编写包装类并不实用,通常是在资源唯一或使用一次时。(或使用事务编程。)对此的解决方案称为作用域保护,这是一种在需要它的函数内编写清理代码的方法。

You may find more information by searching for it in your favorite search provider (that is, Google), or going to the "primary" document here. Note that Boost provides a utilityfor this, as it usually does for good idioms.

您可以通过在您最喜欢的搜索提供商(即 Google)中搜索来找到更多信息,或者转到此处的“主要”文档。请注意,Boost为此提供了一个实用程序,因为它通常用于良好的习语。

回答by John Zwinck

A wrapper is just some smallish class whose purpose is to provide a different interface than the thing it wraps. For example, it is common to take a C API and write one or more classes that "wrap" it to provide an object-oriented interface rather than a procedural one.

包装器只是一些小类,其目的是提供与它包装的东西不同的接口。例如,通常采用 C API 并编写一个或多个“包装”它的类以提供面向对象的接口而不是过程接口。

回答by hAcKnRoCk

You asked for circumstances of writing wrapper classes.For example, if you are in a company that makes use of different types of cameras, let us say USB, firewire etc. Each of the manufacturers will provide a different set of functions through an API to start the camera, set the parameters and read the image stream from it.

您询问了编写包装类的情况。例如,如果您所在的公司使用不同类型的相机,我们说 USB、火线等。每个制造商都会通过 API 提供一组不同的功能以启动相机,设置参数并从中读取图像流。

Now the programmer who builds the applications in your company need to be insulated from all the specific details in the various APIs. Now, what you can do is write a wrapper class around the APIs for each of the cameras or smarter, just one class with simple functions, wrapping around the existing code provided by the API.

现在,在您的公司中构建应用程序的程序员需要与各种 API 中的所有特定细节隔离开来。现在,您可以做的是围绕每个相机的 API 编写一个包装类,或者更聪明的,只是一个具有简单功能的类,包装 API 提供的现有代码。

For instance, we can design classes MyUSBCameraWrapperClass, MyFirewireCameraWrapperClass with some member functions like setFrameRate(int fps), getImgFrame(*framebuffer), etc.

例如,我们可以设计类 MyUSBCameraWrapperClass、MyFirewireCameraWrapperClass 和一些成员函数,如 setFrameRate(int fps)、getImgFrame(*framebuffer) 等。

The programmers in your company can then use MyUSBCameraWrapperClass usbcam; usbcam.setFrameRate(30), etc. You get the point??

贵公司的程序员可以使用 MyUSBCameraWrapperClass usbcam;usbcam.setFrameRate(30) 等等。你明白了吗??

回答by hAcKnRoCk

I use two kinds:

我使用两种:

  1. resource wrappers for function pairs provided by the OS like

    • UNIXs: open/close, mmap/munmap, dlopen/dlclose
    • Windows: CreateFile/DestroyHandle, CreateFileMapping/CloseHandle, LoadLibrary/FreeLibrary
  2. functional wrappers for functions provided by the OS like

    • UNIXs: write, read, dlsym
    • Windows: ReadFile, WriteFile, GetProcAddress
  1. 操作系统提供的函数对的资源包装器,如

    • UNIX:打开/关闭、mmap/munmap、dlopen/dlclose
    • Windows:CreateFile/DestroyHandle、CreateFileMapping/CloseHandle、LoadLibrary/FreeLibrary
  2. 操作系统提供的功能的功能包装器,如

    • UNIX:写、读、dlsym
    • Windows:ReadFile、WriteFile、GetProcAddress

The resource wrapper makes certain, that compiler generated code worries about the destruction of the resource created by the constructor via what is today called RAII. It is easy to combine such classes via base/member class relationships into complex classes. In case of the creation function fails, a system error exception is thrown, providing rich error information about the error.

资源包装器确保编译器生成的代码担心构造函数通过今天称为 RAII 创建的资源的破坏。很容易通过基类/成员类关系将这些类组合成复杂的类。如果创建函数失败,则抛出系统错误异常,提供丰富的错误信息。

The functional wrapper is used instead of the plain OS function. Also in case of failure a system exception is being thrown.

使用函数包装器代替普通的 OS 函数。此外,在失败的情况下,将引发系统异常。

This way somebody using my code doesn't need a debugger and debug code to find out what is failing in a complex environment with many libraries and processes and remote machines.

这样,使用我的代码的人就不需要调试器和调试代码来找出在具有许多库和进程以及远程机器的复杂环境中发生了什么故障。

Also these wrappers provide some OS abstraction -- the code using them does not have to worry about OS differences.

这些包装器还提供了一些操作系统抽象——使用它们的代码不必担心操作系统差异。

回答by wilhelmtell

A wrapper class is a class that wraps a functionality with another interface.

包装类是用另一个接口包装功能的类。

Suppose you have the function f():

假设你有这个功能f()

void f() { std::cout << "hello\n"; }

A simple wrapper class might be

一个简单的包装类可能是

class C {
    f() { std::cout << "hello\n"; }
};

You might write a wrapper when your existing codebase expects a particular interface. This is the essence of the adapter design pattern. Or you might wrap a function in a class if you wish to maintain state for that function. Or you might wrap a function in a class' constructor or destructor if you want it to conveniently and automatically be called for you in a correct and deterministic manner. And the list goes on.

当您现有的代码库需要特定接口时,您可能会编写一个包装器。这就是适配器设计模式的本质。或者,如果您希望维护该函数的状态,您可以将一个函数包装在一个类中。或者,如果您希望以正确和确定性的方式方便且自动地为您调用函数,您可以将函数包装在类的构造函数或析构函数中。而这样的例子不胜枚举。