亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有不完整類型的std :: unique_ptr將無法編譯

具有不完整類型的std :: unique_ptr將無法編譯

C++
郎朗坤 2019-08-12 09:58:13
具有不完整類型的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行收到有關使用不完整類型的編譯錯誤<memory>:' sizeof'到不完整類型' uixx::window::window_impl的應用無效' '據我所知,std::unique_ptr應該可以使用不完整的類型。這是libc ++中的錯誤還是我在這里做錯了什么?
查看完整描述

2 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

以下是一些std::unique_ptr不完整類型的示例。問題在于破壞。

如果你使用pimpl unique_ptr,你需要聲明一個析構函數:

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};

因為否則編譯器會生成一個默認值,并且需要完整的聲明foo::impl。

如果你有模板構造函數,那么即使你沒有構造impl_成員,你也搞砸了:

template <typename T>foo::foo(T bar) {
    // Here the compiler needs to know how to
    // destroy impl_ in case an exception is
    // thrown !}

在命名空間范圍內,使用unique_ptr將不起作用:

class impl;std::unique_ptr<impl> impl_;

因為編譯器必須知道如何銷毀這個靜態持續時間對象。解決方法是:

class impl;struct ptr_impl : std::unique_ptr<impl>{
    ~ptr_impl(); // Implement (empty body) elsewhere} impl_;


查看完整回答
反對 回復 2019-08-12
  • 2 回答
  • 0 關注
  • 897 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號