对类成员使用智能指针

Using smart pointers for class members

本文关键字:智能 指针 成员      更新时间:2023-10-16

我在理解 C++11 中智能指针作为类成员的用法时遇到了麻烦。我已经阅读了很多关于智能指针的信息,我想我确实了解unique_ptrshared_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_ptrweak_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...
}

这是要走的路吗?非常感谢!

unique_ptr不会因为getDevice()而起作用,对吧?

不,不一定。这里重要的是确定Device对象的适当所有权策略,即谁将成为您的(智能(指针所指向的对象的所有者。

它是否会单独成为Settings对象的实例?当Device对象被销毁时,Settings对象是否必须自动销毁,还是应该比该对象存活?

在第一种情况下,std::unique_ptr是你需要的,因为它使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.get();
    }
};
int main() {
    std::unique_ptr<Device> device(new Device());
    Settings settings(std::move(device));
    // ...
    Device *myDevice = settings.getDevice();
    // do something with myDevice...
}

[注1:你可能想知道为什么我在这里使用原始指针,因为每个人都在说原始指针是不好的,不安全的和危险的。实际上,这是一个宝贵的警告,但重要的是要将其放在正确的上下文中:原始指针在用于执行手动内存管理(即通过newdelete分配和解除分配对象(时是不好的。当纯粹用作实现引用语义和传递非拥有、观察指针的手段时,原始指针中没有任何本质上的危险,除了应该注意不要取消引用悬空指针的事实。- 尾注1]

[注2:正如注释中出现的那样,在这种特殊情况下,所有权是唯一的并且拥有的对象始终保证存在(即内部数据成员device永远不会nullptr(,函数getDevice()可以(也许应该(返回引用而不是指针。虽然这是真的,但我决定在这里返回一个原始指针,因为我的意思是一个简短的答案,可以推广到可以nullptr device的情况,并表明只要不将它们用于手动内存管理,原始指针就可以了。- 尾注2]


当然,如果您的Settings对象不应该拥有设备的独占所有权,情况就完全不同了。例如,如果Settings物体的销毁不应意味着尖头Device物体的破坏,则可能就是这种情况。

这是只有你作为程序的设计者才能说出的;从你提供的例子中,我很难判断是否是这种情况。

为了帮助你弄清楚,你可以问自己,除了Settings之外,是否还有其他物体有权保持Device物体的活动,只要它们持有指向它的指针,而不仅仅是被动的观察者。如果确实如此,那么您需要一个共享所有权策略,这就是std::shared_ptr提供的内容:

#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...
}

请注意,weak_ptr 是一个观察指针,而不是拥有指针 - 换句话说,如果指向指向指向对象的所有其他拥有指针超出范围,它不会使指向的对象保持活动状态。

与常规原始指针相比,weak_ptr的优点是可以安全地判断weak_ptr是否悬空(即它是否指向有效对象,或者最初指向的对象是否已被销毁(。这可以通过在weak_ptr对象上调用 expired() 成员函数来完成。

class Device {
};
class Settings {
    std::shared_ptr<Device> device;
public:
    Settings(const std::shared_ptr<Device>& device) : device(device) {
    }
    const std::shared_ptr<Device>& getDevice() {
        return device;
    }
};
int main()
{
    std::shared_ptr<Device> device(new Device());
    Settings settings(device);
    // ...
    std::shared_ptr<Device> myDevice(settings.getDevice());
    // do something with myDevice...
    return 0;
}

week_ptr仅用于参考循环。依赖关系图必须是无环图。在共享指针中,有 2 个引用计数:1 表示 shared_ptr s,1 表示所有指针(shared_ptrweak_ptr(。删除所有shared_ptr时,指针将被删除。当需要来自weak_ptr的指针时,应该使用lock来获取指针(如果存在(。