我正在學習使用智能增強指針,但我對某些情況有點困惑。我們假設我正在實現一個狀態機,每個狀態通過一個更新方法來實現。 每個國家可以返回其自身或創建一個新的狀態對象:使用智能指針與「這個」
struct state
{
virtual state* update() = 0; // The point: I want to return a smart pointer here
};
struct stateA : public state
{
virtual state* update() { return this; }
};
struct stateB : public state
{
virtual state* update() { if(some condition) return new stateA() else return this; }
};
狀態機循環應該是這樣的:
while(true)
current_state = current_state->update();
你能翻譯這段代碼使用boost智能指針?當涉及到「返回這個」部分時,我有點困惑,因爲我不知道該怎麼做。 基本上我覺得返回類似「return boost :: shared_ptr(this)」的東西是沒用的,因爲它不安全。 我該怎麼辦?