简体   繁体   English

共享指针(this)

[英]Shared pointer (this)

I have got an exception throw:0x74AC4192 in main.exe: Microsoft C++ exception: std::bad_weak_ptr at memory location 0x001AF0D0.我在 main.exe 中有一个异常 throw:0x74AC4192:Microsoft C++ 异常:std::bad_weak_ptr 在 memory 位置 0x001AF0D0。

in

Gasstation::Gasstation(int n,int m)
{
    for (int i = 0; i < n; ++i)
    {
        pumps_.push_back(std::make_shared<Pumplace>());
    }
    cashregisters_ = std::make_shared<Cashregister> (shared_from_this(), m);
}

I also used this in the header:我还在 header 中使用了这个:

class Gasstation : public std::enable_shared_from_this<Gasstation>

What could be the problem?可能是什么问题呢?

The issue with your code here, is that you are calling shared_from_this() within the constructor of the class itself, where strictly speaking, it has not been "made shared" yet.您的代码的问题在于您在 class 本身的构造函数中调用 shared_from_this shared_from_this() ,严格来说,它还没有被“共享”。 The constructor is called before a smart pointer to the object exists.在指向 object 的智能指针存在之前调用构造函数。 To follow your example, if creating a shared_ptr to Gasstation :按照您的示例,如果为Gasstation创建shared_ptr

std::shared_ptr<Gasstation> gasStation = std::make_shared<Gasstation>(5,10);
//gasStation is available as a smart pointer, only from this point forward

Its a limitation of enable_shared_from_this that shared_from_this cannot be called in a constructor.它是shared_from_this的一个限制, enable_shared_from_this不能在构造函数中调用。

One solution, though not as elegant, is to have a public method that sets the cashregisters_ variable.一种解决方案虽然不那么优雅,但有一个公共方法来设置 cashregisters_ 变量。 The method can be called after construction:构造后可以调用该方法:

Gasstation::Gasstation(int n, int m)
{
    for (int i = 0; i < n; ++i)
    {
        pumps_.push_back(std::make_shared<Pumplace>());
    }
    cashregisters_ = std::make_shared<Cashregsiter>(m);
}

Gasstation::initialise_cashregisters()
{
    cashregisters_->set_gasstation(shared_from_this());    
}

//driver code
std::shared_ptr<Gasstation> gasStation = std::make_shared<Gasstation>(5, 10);
gasStation->initialise_cashregisters();

This solution will require you to remember to call initialise_cashregisters every time you initialise Gasstation.此解决方案将要求您记住每次初始化 Gasstation 时都调用 initialise_cashregisters。

Short of that, your options are limited, and you may have to rethink your design.除此之外,您的选择是有限的,您可能不得不重新考虑您的设计。 Have you considered using raw pointers-to-Gasstation in Cashregister instead of smart pointers?您是否考虑过在 Cashregister 中使用指向 Gasstation 的原始指针而不是智能指针? If cashregister_ is a private variable and will never exist beyond the lifetime of the Gasstation it is assigned to, using raw pointers may be a safe and elegant alternative.如果 cashregister_ 是一个私有变量,并且在分配给它的 Gasstation 的生命周期之后永远不会存在,那么使用原始指针可能是一种安全而优雅的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM