-
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...
-
}
-
复制代码
-
C++11为我们提供了shared_ptr、unique_ptr和weak_ptr这三种智能指针帮助我们更方便安全的使用动态内存。它们都定义在memory头文件中。智能指针的常见用法大家都应该很熟悉了,今天我想说一下智能指针作为成员变量时的用法。比如上面这段代码,我想类Settings中的Device指针换成智能指针,那么getDevice应该是什么样的呢?
-
这里主要的决定因素是你Device对象的所有权策略,即你想要谁去拥有它,决定它的生命期。如果只有Settings对象拥有它,当Settings析构的时候你希望Device也自动被析构。那么你需要用unique_ptr,此时Settings独自拥有Device对象的,因此Device的析构就只有Settings负责。在这种情况下,getDevice可以返回一个引用。
-
#include <memory>
-
class Device {
-
};
-
class Settings {
-
std::unique_ptr<Device> device;
-
public:
-
Settings(std::unique_ptr<Device> d) {
-
device = std::move(d);
-
}
-
Device& getDevice() {
-
return *device;
-
}
-
};
-
int main() {
-
std::unique_ptr<Device> device(new Device());
-
Settings settings(std::move(device));
-
// ...
-
Device& myDevice = settings.getDevice();
-
// do something with myDevice...
-
}
-
复制代码
- 如果你希望Device对象不只是Settings所独有,那么就需要使用shared_ptr了。这样直到所有拥有Device的对象都析构了之后,Device才会析构。
-
#include <memory>
-
class Device {
-
};
-
class Settings {
-
std::shared_ptr<Device> device;
-
public:
-
Settings(std::shared_ptr<Device> const& d) {
-
device = d;
-
}
-
std::shared_ptr<Device> getDevice() {
-
return device;
-
}
-
};
-
int main() {
-
std::shared_ptr<Device> device = std::make_shared<Device>();
-
Settings settings(device);
-
// ...
-
std::shared_ptr<Device> myDevice = settings.getDevice();
-
// do something with myDevice...
-
}