考慮以下h文件:構造與升壓超載:: shared_ptr的
#ifndef COM_H_
#define COM_H_
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <map>
class B;
class A : public boost::enable_shared_from_this<A>{
public:
A(){}
~A(){}
void Init();
boost::shared_ptr<B> b_ptr_;
};
class B : public boost::enable_shared_from_this<B>{
public:
B(){}
B(boost::shared_ptr<A> a_ptr);
B(int j, boost::shared_ptr<A> a_ptr);
~B(){}
void Init();
void Init(boost::shared_ptr<A> a_ptr);
void Init(int j, boost::shared_ptr<A> a_ptr);
std::string b;
boost::shared_ptr<A> a_ptr_;
};
#endif /* COM_H_ */
和.cc文件:
#include "com.h"
void A::Init() {
// Case 1 not working
// boost::shared_ptr<B> b1(new B(shared_from_this()));
// b1->Init();
// Case 2 working
boost::shared_ptr<B> b2(new B());
b2->Init(shared_from_this());
}
B::B(boost::shared_ptr<A> a_ptr) {
B(2, a_ptr);
}
B::B(int j, boost::shared_ptr<A> a_ptr) {
a_ptr_ = a_ptr;
b = "b";
}
void B::Init() {
a_ptr_->b_ptr_ = shared_from_this();
}
void B::Init(boost::shared_ptr<A> a_ptr) {
Init(2, a_ptr);
}
void B::Init(int j, boost::shared_ptr<A> a_ptr) {
a_ptr_ = a_ptr;
b = "b";
a_ptr_->b_ptr_ = shared_from_this();
}
在主:
#include "com.h"
#include <iostream>
int main() {
boost::shared_ptr<A> a(new A());
a->Init();
std::cout << a->b_ptr_->b << std::endl;
return 0;
}
當傳遞boost :: shared_ptr到一個構造函數,然後用同一個指針作爲參數調用另一個(重載)構造函數,shared_ptr指向的對象是丟失和錯誤
投擲 實例終止後,被稱爲 '推動:: exception_detail :: clone_impl
' 什麼():TR1 :: bad_weak_ptr
是拋出。以相同的方式調用兩個重載函數(Init)時不會發生同樣的情況。
任何人都可以請解釋嗎?
好吧,你是對的!我編輯了代碼,以便您提到的構造函數調用未調用shared_from_this()的重載構造函數。現在我得到一個錯誤,斷言失敗:(px!= 0),函數operator->,文件/usr/local/include/boost/smart_ptr/shared_ptr.hpp,行414. – apon
可能需要看到你的新代碼告訴有什麼不對... –
就在那裏,我編輯了原文。構造函數不再調用Init,它調用B(2,a_ptr)。 B(2,a_ptr); B(2),B(B),B(2),B }' – apon