在C ++ 11中有一种很好的方法可以将对其他对象的引用存储为成员吗?

时间:2015-07-16 11:26:12

标签: c++ oop c++11 design-patterns ownership

美好的一天,大家好!

这是我卡住的地方: 我有三个具体的课程:ComputerPeripheralPersonComputerPeripheral都是扩展类Device

Device有一位私人会员Device.ownerPerson,应该存储某种对设备所有者的引用,以及一个公共函数Device.getOwner():{ {1}}。

另一方面,任何Person都有自己的私人成员PersonPerson.peripherals以及公共职能Person.computers等等。

是否有任何设计模式可以在类之间建立这些连接?

不转让直接所有权! (Person.get()无权杀死Computer等实例,这就是我要注意使用指针的原因)

但是如果Person的某些实例将更改其所有者,则必须从之前所有者的计算机列表中消失并显示在新所有者的列表中。与Computer相同。

如果您有问题,请提出任何问题。也许,我对局势的解释很差。抱歉lang错误。

1 个答案:

答案 0 :(得分:1)

You can use std::unique_ptr to ensure that a single reference exists to that object. To change the ownership use std::move.

std::unique_ptr<Device> devicePtr(new Device());
std::unique_ptr<Device> devicePtr2(std::move(devicePtr));

Each Person would have it's unique pointer(s).