2016-10-20 10 views
-4

次のコードを実行すると、sptrポインタがBデストラクタ内でNULLであることがわかります。私はB Bを変更したとき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; 
} 

ただし、[1]通常のオブジェクトへの配列から、すなわちbをBに、SPTR点は、B desctructor内部NULLではありません。どうして?誰かが助けてくれますか?私はここで完全に無知だ。あなたはサイズ1の配列を持っている場合、配列の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.RunB(); 
    } 
private: 
    B b; 
}; 

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

答えて

2

あなたがb[0]ないb[1]を行う必要がある最初の要素にアクセスするには、その後、だから、0から始まります。

関連する問題