0

我有一个名为 的类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;
}
4

1 回答 1

1

正如在各种评论中已经解释的那样,像 Window* 这样的指针参数永远不会创建 Window 对象的副本。这就是制作指针的原因。

在尝试找出更复杂的工具(如智能指针)之前,我建议您先花时间了解 C++ 基础。你应该从什么是值、什么是指针、什么是引用开始。

于 2020-04-28T12:18:20.657 回答