我正在尝试包装一个使用这样的模式的C库:
Thing* x= new_thing_("blah");
Thing* tmp= thing_copy(x);
free_thing(tmp);
Other* y=get_other(x,7);
char* message=get_message(x,y);
free_thing(x);
free_other(y);
Run Code Online (Sandbox Code Playgroud)
在c ++中,我希望能够做类似的事情
auto_ptr<CXXThing> x=new CXXThing("blah");
auto_ptr<CXXThing> tmp=new CXXThing(*x);
auto_ptr<CXXOther> y=x->get_other(7);
char* message = y->get_message();
Run Code Online (Sandbox Code Playgroud)
显然,CXXOther也包含指向CXXThing的指针.所以我遇到的问题是,基本上我只想将函数和成员"插入"到现有的结构中(我认为这被称为"Mixin"的想法).
问题是,如果我将Thing作为CXXThing的一个元素包含在内,那么我不知道我是如何声明构造函数的,如果我包含一个指向包装类的指针,那么我有一个额外级别的无用间接.
我应该如何包装它以便这可能?(回答"你想做什么不是最好/可能......这里是正确的方法"也是可以接受的.)
auto_ptr您可以更直接地使用RAII习语,而不是使用s.这是你可以做到的一种方式:
包含以下内容的CXXThing类Thing:
class CXXThing
{
public:
// Acquire a Thing
explicit CXXThing(const char* str) : x(::new_thing_(str)) {}
// Copy a Thing
CXXThing(const CXXThing& rhs) : x(::thing_copy(rhs.x)) {}
// Copy-and-swap idiom
CXXThing& operator=(CXXThing rhs)
{
swap(*this, rhs);
return *this;
}
// Release a Thing
~CXXThing() { ::free_thing(x); }
friend void swap(CXXThing& lhs, CXXThing& rhs)
{
Thing* tmp = lhs.x;
lhs.x = rhs.x;
rhs.x = tmp;
}
private:
Thing* x;
friend class CXXOther;
};
Run Code Online (Sandbox Code Playgroud)
包含以下内容的CXXOther类Other:
class CXXOther
{
public:
// Acquire an Other
explicit CXXOther(CXXThing& thing, int i) : y(::get_other(thing.x, i)) {}
// Release an Other
~CXXOther() { ::free_other(y); }
// Get a message
char* get_message(const CXXThing& x) { return ::get_message(x.x, y); }
private:
// Instaces of Other are not copyable.
CXXOther(const CXXOther& rhs);
CXXOther& operator=(const CXXOther& rhs);
Other* y;
};
Run Code Online (Sandbox Code Playgroud)
使用上述类将C代码转换为C++代码:
int main()
{
CXXThing x("blah");
{
CXXThing tmp = x;
} // tmp will go away here.
CXXOther y(x, 7);
char* msg = y.get_message(x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)