我正在學習智能指標,使用以下示例 test.cpp
#include<iostream>
#include<vector>
#include<memory>
struct abstractShape
{
virtual void Print() const=0;
};
struct Square: public abstractShape
{
void Print() const override{
std::cout<<"Square\n";
}
};
int main(){
std::vector<std::unique_ptr<abstractShape>> shapes;
shapes.push_back(new Square);
return 0;
}
上述代碼有編譯錯誤“c -std=c 11 test.cpp”:
smart_pointers_2.cpp:19:12: error: no matching member function for call to 'push_back'
shapes.push_back(new Square);
有人可以幫我解釋一下這個錯誤嗎?順便說一句,當我更改push_back為時emplace_back,編譯器只會發出警告。
uj5u.com熱心網友回復:
push_back期望一個std::unique_ptr,當傳遞原始指標 like 時new Square,這被認為是復制初始化,原始指標需要被std::unique_ptr隱式轉換為。隱式轉換失敗,因為std::unique_ptr來自原始指標的轉換建構式被標記為explicit。
emplace_back之所以有效,是因為它將引數轉發給建構式,std::unique_ptr并以直接初始化形式構造元素,它考慮了explicit轉換建構式。
引數 args... 以 . 的形式轉發給建構式
std::forward<Args>(args)...。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455271.html
上一篇:C 類屬性未正確更新
