我有一个名为 的类Window,以及一大堆需要一个实例Window才能工作的函数。所以我已经将Window* win参数作为参数传递给了这些函数中的每一个,但是这种方法在Window*每次调用它时都会创建一个副本,而且似乎没有必要将参数传递给每个函数。我试过通过const Window*,但这也行不通,因为里面的函数Window没有const版本。我认为使用std:::shared_ptrandstd::weak_ptr会有所帮助,但我仍然没有正确理解它。这是我当前的代码:
// Window.h
class Window
{
public:
// some getters/setters and other functions
private:
// members are here
};
// on another file
int func1(Window* win /*I want to remove this */, ...) {
// use win and other parameters
}
这是智能指针方法。
// class Window as declared above
// file.h
namespace space
{
struct context;
context* make_context(std::shared_ptr<Window> const& win); // const& to avoid copy
void destroy_context(context* ctx);
int func1(...); // note that ... is used to show some params whose type isn't important for the question.
}
// some other functions
// file.cpp
namespace space
{
struct context
{
std::weak_ptr<Window> target;
};
context* make_context(std::shared_ptr<Window> const& win) // const& to avoid copy
{
context* ctx = new context{};
ctx->target = win;
return ctx;
}
void destroy_context(context* ctx)
{
if(ctx != nullptr)
{
delete ctx;
ctx = nullptr;
}
}
int func1(...)
{
// use ... params
} // int func1(...)
} // namespace space
// main.cpp
int main(int, char**)
{
std::shared_ptr<Window> window{new Window{/*some arguments*/}};
auto ctx{space::make_context(window)};
int func1();
// some other code
delete ctx;
}