2016-06-24 37 views
1

我有這樣的代碼:enable_shared_from_this在使用從unique_ptr到基類的shared_ptr時未初始化。爲什麼?

#include <iostream> 
#include <memory> 
#include <string> 

class base { 
public: 
    virtual void method() = 0; 
    virtual ~base() = default; 
}; 

class test: public base, public std::enable_shared_from_this<test> { 
private: 
    std::string text; 
public: 
    test(std::string text): text(std::move(text)) {} 
    ~test() = default; 
    virtual void method() override { 
    std::cout << "text: " << text; 
    std::cout << " this: " << this->shared_from_this().get() << std::endl; 
    } 
    static std::unique_ptr<base> create(std::string text) { 
    return std::unique_ptr<base>(new test(std::move(text))); 
    } 
}; 

static auto create_test(std::string text) { 
    return test::create(std::move(text)); 
} 

int main(int argc, char* argv[]) { 
    std::shared_ptr<base> shared = create_test("some text"); 
    shared->method(); 
    return 0; 
} 

當我運行這個程序,我得到異常「bad_weak_ptr」。 您能否解釋爲什麼「enable_shared_from_this」未初始化?

當我將unique_ptr<base>的實例更改爲unique_ptr<test>時,它有效。

$ ./test 
terminate called after throwing an instance of 'std::bad_weak_ptr' 
    what(): bad_weak_ptr 
text: some textAborted (core dumped) 
+0

儘管我以前曾經說過工廠函數應該返回一個'unique_ptr',這確實需要指針在工廠返回時尚未共享。如果你的類繼承'shared_from_this',那麼當工廠返回時已經有兩個指針了。事實上,[我在我原來的評論中明確指出了這種情況](https://stackoverflow.com/questions/35953783/c11-make-shared-instancing#comment59565062_35953783)所以聯繫誰建議你使用'unique_ptr'和' shared_from_this'在一起,並告訴他們有一個例外。 –

回答

1

你還指望了什麼?您正在使用shared_ptr<base>。基地沒有從enable_shared_from_this開始,因此它的共享指針無法初始化shared_from_this使用的弱基準。

完全按照設計工作。

0

您可以使用此功能create投建了test到一個共享的指針base

static std::shared_ptr<base> create(std::string text) { 
    return std::shared_ptr<test>(new test(std::move(text))); 
} 

,否則將無法正常工作。
enable_shared_from_this按預期工作,但考慮this

的std :: enable_shared_from_this允許當前被命名爲PT一個std :: shared_ptr的管理,以安全地產生額外的std :: shared_ptr實例PT1對象T,PT2, ......所有人都與p分享t的所有權。

在您的代碼中,您沒有在test之外創建任何shared_pointer
上面的create函數完成這項工作。

相關問題