具有不完整類型的std :: unique_ptr將無法編譯我正在使用pimpl-idiom std::unique_ptr:class window {
window(const rectangle& rect);private:
class window_impl; // defined elsewhere
std::unique_ptr<window_impl> impl_; // won't compile};但是,我在第304行的第304行收到有關(guān)使用不完整類型的編譯錯誤<memory>:' sizeof'到不完整類型' uixx::window::window_impl的應(yīng)用無效' '據(jù)我所知,std::unique_ptr應(yīng)該可以使用不完整的類型。這是libc ++中的錯誤還是我在這里做錯了什么?
2 回答

精慕HU
TA貢獻(xiàn)1845條經(jīng)驗 獲得超8個贊
以下是一些std::unique_ptr
不完整類型的示例。問題在于破壞。
如果你使用pimpl unique_ptr
,你需要聲明一個析構(gòu)函數(shù):
class foo{ class impl; std::unique_ptr<impl> impl_;public: foo(); // You may need a def. constructor to be defined elsewhere ~foo(); // Implement (with {}, or with = default;) where impl is complete};
因為否則編譯器會生成一個默認(rèn)值,并且需要完整的聲明foo::impl
。
如果你有模板構(gòu)造函數(shù),那么即使你沒有構(gòu)造impl_
成員,你也搞砸了:
template <typename T>foo::foo(T bar) { // Here the compiler needs to know how to // destroy impl_ in case an exception is // thrown !}
在命名空間范圍內(nèi),使用unique_ptr
將不起作用:
class impl;std::unique_ptr<impl> impl_;
因為編譯器必須知道如何銷毀這個靜態(tài)持續(xù)時間對象。解決方法是:
class impl;struct ptr_impl : std::unique_ptr<impl>{ ~ptr_impl(); // Implement (empty body) elsewhere} impl_;
- 2 回答
- 0 關(guān)注
- 895 瀏覽
添加回答
舉報
0/150
提交
取消