【发布时间】:2013-03-16 22:38:32
【问题描述】:
我无法理解智能指针在 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...
}
假设我想用智能指针替换指针。 unique_ptr 不会因为 getDevice() 而工作,对吧?那是我使用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的场景。如果没有,只需返回一个参考。 -
是的,
shared_ptr在 8/10 的情况下是正确的。其他 2/10 在unique_ptr和weak_ptr之间分配。另外,weak_ptr通常用于中断循环引用;我不确定您的用法是否正确。 -
首先,您希望
device数据成员拥有什么所有权?您首先必须做出决定。 -
好的,我知道作为调用者我可以使用
unique_ptr代替,并在调用构造函数时放弃所有权,如果我知道我现在不再需要它的话。但作为Settings类的设计者,我不知道调用者是否也想保留引用。也许该设备将在许多地方使用。好吧,也许这正是你的意思。在那种情况下,我不会是唯一的所有者,我猜那时我会使用 shared_ptr。并且:所以智能点确实替换了指针,但不是引用,对吧? -
this->device = device;也使用初始化列表。
标签: c++ c++11 shared-ptr smart-pointers unique-ptr