1樓:周劍鋒
原因:這個是容器擴張導致的(容器擴張會呼叫copy construct,在STL原始碼中可以看到).
解決方案:可以定義兩個vector變數來進行測試(或者reserve乙個較大的數字).
2樓:
When we call a push or insert member, we pass objects of the element type and those objects are copied into the container. When we call an emplace member, we pass arguments to a constructor for the element type. The emplace members use those arguments to construct an element directly in space managed by the container.
For example, assuming c holds Sales_data (§ 7.1.4, p. 264) elements:
// construct a Sales_data object at the end of c
// uses the three-argument Sales_data constructor
c.emplace_back("978-0590353403", 25, 15.99);
// error: there is no version of push_back that takes three arguments
c.push_back("978-0590353403", 25, 15.99);
// ok: we create a temporary Sales_data object to pass to push_back
c.push_back(Sales_data("978-0590353403", 25, 15.99));
The call to emplace_back and the second call to push_back both create new Sales_data objects. In the call to emplace_back, that object is created directly in space managed by the container. The call to push_back creates a local temporary object that is pushed onto the container.
The arguments to an emplace function vary depending on the element type. The arguments must match a constructor for the element type:
// iter refers to an element in c, which holds Sales_data elements
c.emplace_back(); // uses the Sales_data default constructor
c.emplace(iter, "999-999999999"); // uses Sales_data(string)
// uses the Sales_data constructor that takes an ISBN, a count, and a price
c.emplace_front("978-0590353403", 25, 15.99);
Note
The emplace functions construct elements in the container. The arguments tothese functions must match a constructor for the element type.
c++ primer Fifth Edition已經寫得很清楚了,emplace_back/emplace_front 直接在容器所管理的空間內構建
3樓:「已登出」
你沒有寫move建構函式,當然也無所謂,因為emplace back不會用它,emplace採用了就地構造,這是它和pushback的區別:
當插入rvalue,它節約了一次move構造。
當插入lvalue,它節約了一次copy構造。理論上emplace back不會發生拷貝。
只有可能是vector底層發生了記憶體分配擴張,你列印capacity比對一下emplace前後,應該是發生變化了。
4樓:Michael wang
Stan Lippman的 inside the c++ object model中對什麼時候會呼叫拷貝建構函式,說的挺清楚的,可以學習一下,10幾年前第一次看到時,有頓悟的感覺
5樓:姚冬
很正常C3(1,"ss")
是構造了乙個main函式棧上的匿名臨時變數,這個自然需要乙個呼叫建構函式
然後 push_back的時候,vector需要把這個匿名變數的值複製到vector的儲存空間上,由於是值copy,所以必須有一次copy constructor
在C++11裡引入了 std::move 可以解決這個問題
參考 關於C++右值及std::move()的疑問? - C++ - 知乎
第二次 Copy Constructor應該是 vector在擴容產生的複製,你可以在開始先把 vector reserve乙個較大的值再試試看
vector容器的begin 返回的const 迭代器和cbegin 有何不同
陸海綿 不是多此一舉。const iterator begin const const iterator cbegin const 這兩個介面的抽象含義不一樣。iterator begin const iterator begin const 這兩個函式抽象含義一樣,分別對應非const物件和con...
c 用find查詢vector中的某個元素位置和用迴圈遍歷查詢哪個更好?
節瓜 用find 寫多錯多,用find寫出問題的概率比自己寫迴圈小 如果你真的手寫迴圈都寫出問題,一般來說這種問題很難找,或者說你很容易忽略這裡也有可能出錯。 紀笑旭 主要看你要找的資料在煉表裡的什麼位置,不過能用find就不用遍歷。畢竟find和find if基本上覆蓋了你能用到的所有資料型別的鍊...
anki倒閉了,vector機械人還能正常運作嗎,對已經買了vector的使用者有什麼影響?
紅黑白 消費級機械人公司Anki被收購未來或將有無限的潛力 http www.Anki的智財權 專利,商標和資料 被位於匹茲堡的教育技術初創公司Digital Dream Labs收購。上周末,Digital Dream Labs首席執行官Jacob Hanchar 在Vector Kickstar...