我在理解C++11中将智能指针作为类成员的使用方面遇到了困难。我已经阅读了很多有关智能指针的内容,并且我认为我基本上了解了unique_ptr
和shared_ptr
/weak_ptr
的工作原理。但我不明白的是真正的用法。似乎每个人都建议几乎始终使用unique_ptr
。但是,我该如何实现这样的东西:
class Device {
};
class Settings {
Device *device;
public:
Settings(Device *device) {
this->device = device;
}
Device *getDevice() {
return device;
}
};
int main() {
Device *device = new Device();
Settings settings(device);
// ...
Device *myDevice = settings.getDevice();
// do something with myDevice...
}
假设我想要用智能指针替换指针。因为有getDevice()
,所以unique_ptr
行不通,对吧?这时候我就要使用shared_ptr
和weak_ptr
了?没有办法使用unique_ptr
吗?在我看来,除非在非常小的范围内使用指针,否则shared_ptr
在大多数情况下更合适。
class Device {
};
class Settings {
std::shared_ptr<Device> device;
public:
Settings(std::shared_ptr<Device> device) {
this->device = device;
}
std::weak_ptr<Device> getDevice() {
return device;
}
};
int main() {
std::shared_ptr<Device> device(new Device());
Settings settings(device);
// ...
std::weak_ptr<Device> myDevice = settings.getDevice();
// do something with myDevice...
}
那是正确的方式吗?非常感谢!
device
传递给settings
的构造函数后,您是否仍然希望能够在调用范围内引用它,还是只能通过settings
引用?如果是后者,那么使用unique_ptr
很有用。另外,您是否有一种情况,其中getDevice()
的返回值为null
。如果没有,则只需返回一个引用即可。 - Keithshared_ptr
是正确的。另外的2个场景则需要使用unique_ptr
和weak_ptr
。此外,weak_ptr
通常用于打破循环引用;我不确定你的用法是否正确。 - Collin Dauphineedevice
数据成员的所有权是什么?你必须先决定这个。 - juanchopanzaunique_ptr
并在调用构造函数时放弃所有权。但是作为Settings
类的设计者,我不知道调用者是否也想保留引用。也许设备将在许多地方使用。好的,也许这正是你的观点。在那种情况下,我将不是唯一的所有者,这就是我想使用shared_ptr
的时候吧。还有:所以智能指针确实替换了指针,但不是引用,对吗? - michaelkunique_ptr
作为成员变量有许多隐含的限制,其中可能最重要的是标准复制构造函数的隐式删除。这种删除可能会使您的类对任何下游程序员来说极不直观。请参见: https://dev59.com/yGQo5IYBdhLWcg3wdPO8 - ldog