【问题标题】:C++ unexpected destructor behavior [closed]C ++意外的析构函数行为[关闭]
【发布时间】:2017-03-03 01:03:57
【问题描述】:

当我运行以下代码时,我看到 B 析构函数中的 sptr 指针为 NULL。

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>

using namespace std;
class B
{
public:
    ~B()
    {
        std::cout<< "B Dtor ";
        // Access sptr
    }

    void RunB()
    {
        sptr.reset(new int(2));
    }

private:
   boost::shared_ptr<int> sptr;
};

class A
{
public:
    void RunA()
    {
        b[1].RunB();
    }
private:
    B b[1];
};

int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;
    A a;
    a.RunA();
    return 0;
}

但是,当我将 B b[1] 更改为 B b 时,即从数组到常规对象,在 B 析构函数中 sptr 点不是 NULL。为什么?有人可以帮忙吗?我在这里完全一无所知。

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>

using namespace std;

class B
{
public:
    ~B()
    {
        std::cout<< "B Dtor ";
        // Access sptr
    }

    void RunB()
    {
        sptr.reset(new int(2));
    }

private:
   boost::shared_ptr<int> sptr;
};

class A
{
public:
    void RunA()
    {
        b.RunB();
    }
private:
    B b;
};

int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;
    A a;
    a.RunA();
    return 0;
}

【问题讨论】:

    标签: c++ boost destructor


    【解决方案1】:

    在 C++ 中,数组的索引从 0 开始。因此,如果您有一个大小为 1 的数组,那么要访问第一个元素,您需要执行 b[0] 而不是 b[1]

    【讨论】:

      猜你喜欢
      • 2014-03-20
      • 1970-01-01
      • 2022-11-20
      • 2017-06-10
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多