如何使用其副本构造函数和副本赋值是私有的对象?

编程入门 行业动态 更新时间:2024-10-27 22:28:16
本文介绍了如何使用其副本构造函数和副本赋值是私有的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在阅读 TCPL 时,我遇到了一个问题,如标题所指,然后'private'类是:

class Unique_handle { private: Unique_handle& operator =(const Unique_handle& rhs); Unique_handle(const Unique_handle& rhs); public: // ... };

使用代码为:

struct Y { // ... Unique_handle obj; };

,我要执行此类操作:

int main() { Y y1; Y y2 = y1;虽然,这些代码都来自TCPL,但我仍然不能得到这些代码,因为它们都是通过TCP / IP来实现的。解决方案... 任何人都可以帮助我,欣赏。

解决方案

顾名思义, Unique_handle 不能被复制。它的实现通过禁用拷贝构造函数和拷贝赋值运算符来确保它。

对于访问 Unique_handle 的多个实例,一个解决方案是保存指针并复制指针。然后, Y 的多个实例指向同一个唯一句柄。

但是,在这种情况下,要正确地管理资源。

In reading TCPL, I got a problem, as the title refered, and then 'private' class is:

class Unique_handle { private: Unique_handle& operator=(const Unique_handle &rhs); Unique_handle(const Unique_handle &rhs); public: //... };

the using code is:

struct Y { //... Unique_handle obj; };

and I want to execute such operations:

int main() { Y y1; Y y2 = y1; }

although, these code are come from TCPL, but I still can not got the solution... Can anybody help me, appreciate.

解决方案

As its name suggests, the Unique_handle isn't meant to be copied. Its implementation ensures it by disabling the copy constructor and copy assignment operator.

One solution for multiple instances having access to a Unique_handle is holding a pointer to it, and copying the pointer. Then multiple instances of Y point to the same unique handle.

Take care, however, to manage resources properly in this case.

更多推荐

如何使用其副本构造函数和副本赋值是私有的对象?

本文发布于:2023-11-09 16:08:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副本   赋值   如何使用   函数   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!