2014-02-18 49 views
0

我有兩個std::unique_ptr成員的課。我想通過構造函數設置這些成員。有沒有辦法用unique_ptr減少詳細實例化?

目前我在做這個:

std::unique_ptr<Assignment> assignment{new Assignment{ 
     std::unique_ptr<Variable>{new Variable{"a"}}, 
     std::unique_ptr<Expression>{new Variable{"b"}} 
}}; 

通過定期的三分球,我只是這樣做:

auto assignment = new Assignment{new Variable{"a"}, new Variable{"b"}}; 
delete assignment; 

我可以讓智能指針版本更簡潔不知何故?我希望像這樣的東西可能工作。

std::unique_ptr<Assignment> assignment{new Variable{"a"},{new Variable{"b"}}; 

但是,unique_ptr的構造函數是顯式的,所以它沒有。

+4

你可以提供你自己的['std :: make_unique']實現(http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique)來使一些事情變得容易一些。 –

+3

如果你正在尋找一種實現'make_unique()'的方法,我會建議:http://stackoverflow.com/questions/7038357/make-unique-and-perfect-forwarding。另外,請注意,在第二個和第三個示例中,如果構建第二個「新變量」失敗,則會泄漏內存。 (這是std :: make_unique和std :: make_shared全部的一部分)。 –

+0

@sharth:第一個例子中的情況也是如此。我不確定,但我相信編譯器可以交錯創建兩個'unique_ptr'參數,首先執行兩個'new',然後構造'unique_ptr',可能會泄漏內存。您需要交錯函數調用('make_unique')以確保沒有內存泄漏。 –

回答

2

是一個完美的轉發構造函數嗎?

// If you aren't using make_unique, you're doing it wrong. 
template <typename T, typename...Args> 
inline std::unique_ptr<T> make_unique(Args&&...args) { 
    return std::unique_ptr<T>{new T(std::forward<Args>(args)...)}; 
} 

struct Variable { 
    std::string name_; 

    Variable(std::string name) : name_{std::move(name)} {} 
}; 

struct Assignment { 
    std::unique_ptr<Variable> a_, b_; 

    template <typename T, typename U> 
    Assignment(T&& a, U&& b) : 
     a_{make_unique<Variable>(std::forward<T>(a))}, 
     b_{make_unique<Variable>(std::forward<U>(b))} {} 
}; 

auto assignment = make_unique<Assignment>("a", "b"); 

IMO簡化了語法。

0

的最簡單的解決辦法可能是

std::unique_ptr<Assignment> assignment { 
    new Assignment{Variable{"a"}, Variable{"b"}}}; 

當然,這需要合適的Assignment(Variable&&, Variable&&)過載。

相關問題