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

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

如何在只有受保護或私有構造函數的類上調用:std:make_Shared?

如何在只有受保護或私有構造函數的類上調用:std:make_Shared?

C++
紅顏莎娜 2019-08-03 03:03:33
如何在只有受保護或私有構造函數的類上調用:std:make_Shared?我的代碼不起作用,但我認為其意圖是明確的:testmakeshared.cpp#include <memory>class A {  public:    static ::std::shared_ptr<A> create() {       return ::std::make_shared<A>();    }  protected:    A() {}    A(const A &) = delete;    const A &operator =(const A &) = delete;};::std::shared_ptr<A> foo(){    return A::create();}但是,當我編譯它時,我會得到這個錯誤:g++ -std=c++0x -march=native -mtune=native -O3 -Wall testmakeshared.cppIn file included from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../i nclude/c++/4.6.1/bits/shared_ptr.h:52:0,                  from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/memory:86,++/4.6.1/bits/shared_ptr_base.h:                  400:2: error: within this contextCompilation exited abnormally with code 1 at Tue Nov 15 07:32:58這條消息基本上是說,模板實例化堆棧中的一些隨機方法從::std::make_shared無法訪問構造函數,因為它是受保護的。但我真的想用這兩種方法::std::make_shared并防止任何人創建這個類的對象,而該對象不是::std::shared_ptr..有辦法做到這一點嗎?
查看完整描述

3 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

考慮到對.的要求std::make_shared在20.7.2.2.6 Shared_PTR創建[util.Smart ptr.shared.create]中,第1段:

要求:表達::new (pv) T(std::forward<Args>(args)...),在哪里pv有型void*并指向適合保存類型對象的存儲。T,應形成良好的結構。A應為分配器(17.6.3.5)。的復制構造函數和析構函數。A不得拋出異常。

因為這個要求是無條件地用這個表達方式來指定的,而且像范圍這樣的東西也沒有被考慮在內,我認為像友誼這樣的技巧是正確的。

一個簡單的解決方案是從A..這不需要A接口,甚至多態類型。

// interface in headerstd::shared_ptr<A> make_a();// implementation in sourcenamespace {struct concrete_A: public A {};} 
// namespacestd::shared_ptr<A>make_a(){
    return std::make_shared<concrete_A>();}




查看完整回答
反對 回復 2019-08-04
  • 3 回答
  • 0 關注
  • 417 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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