2016-10-20 81 views
-4

当我运行下面的代码时,我看到在B析构函数内的sptr指针是NULL。C++意外的析构函数行为

#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即,特征码指针点不是乙desctructor内部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; 
} 

回答

2

在C++阵列的索引从0开始。因此,如果你有尺寸1的阵列,然后访问你需要做b[0]b[1]第一个元素。