我想使用智能指针,但不确定在哪里使用以及何时使用

发布于 2025-01-13 19:07:39 字数 1437 浏览 7 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一直在等你来 2025-01-20 19:07:39

如果您想学习如何使用智能指针,请暂时忘记这段代码。启动一个新的小程序,确保您了解它们的工作原理。

  • 定义一个仅包含字符串和 int 的测试类。将它们公开
  • 添加一个构造函数,以便您可以看到其创建时间。
  • 添加一个析构函数,以便您可以看到它何时被删除。

使用 std::make_unique 创建实例

测试对象中重复的字段

在实例中设置内容,编写一个接受 unique_ptr 作为参数的函数,并使用 std::shared_ptr 计算 code>

确保您了解正在发生的事情,不要只是尝试盲目地将内容钉入堆栈实现中。如果您遇到困难,请在此发布一个新问题。

上面的代码有很多其他错误,您将无法获得针对您的特定“智能指针”问题的一组干净的答案。另外你将无法让它可靠地工作

If you want to learn how to use smart pointers then forget this code for a moment. Start a new small program that just makes sure you understand how they work.

  • Define a test class with just a string and an int in it. Make them public
  • Add a constructor so you can see when its created.
  • Add a Destructor so you can see when its deleted.

Create an instance using std::make_unique

Set things in the instance, write a function that accepts the unique_ptr as an argument and cout the fields in the test object

repeat with std::shared_ptr

Make sure you understand what is going on, dont just try to blindly nail stuff into your stack implementation. If you get stuck post a new question just on this.

The code above has so many other errors in it you will not get a clean set of answers to your specific 'smart pointers' question. Plus you wont be able to make it work reliably

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文