問題描述
從頭開始設計新系統.我將使用 STL 來存儲某些長期存在的對象的列表和映射.
Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects.
問題:我應該確保我的對象具有復制構造函數并將對象的副本存儲在我的 STL 容器中,還是通常更好地管理生命周期?確定自己的范圍并將指向這些對象的指針存儲在我的 STL 容器中?
Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life & scope myself and just store the pointers to those objects in my STL containers?
我意識到這有點缺乏細節,但我正在尋找理論上"更好的答案(如果存在),因為我知道這兩種解決方案都是可能的.
I realize this is somewhat short on details, but I'm looking for the "theoretical" better answer if it exists, since I know both of these solutions are possible.
玩指針的兩個非常明顯的缺點:1) 我必須自己在 STL 之外的范圍內管理這些對象的分配/解除分配.2) 我無法在堆棧上創建臨時對象并將其添加到我的容器中.
Two very obvious disadvantage to playing with pointers: 1) I must manage allocation/deallocation of these objects myself in a scope beyond the STL. 2) I cannot create a temp object on the stack and add it to my containers.
還有什么我遺漏的嗎?
推薦答案
因為人們對使用指針的效率贊不絕口.
Since people are chiming in on the efficency of using pointers.
如果您正在考慮使用 std::vector 并且如果更新很少并且您經常迭代您的集合并且它是一種非多態類型存儲對象副本"將更有效,因為您將獲得更好的引用位置.
If you're considering using a std::vector and if updates are few and you often iterate over your collection and it's a non polymorphic type storing object "copies" will be more efficent since you'll get better locality of reference.
Otoh,如果更新是常見的,存儲指針將節省復制/重定位成本.
Otoh, if updates are common storing pointers will save the copy/relocation costs.
這篇關于我應該存儲整個對象,還是在容器中存儲指向對象的指針?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!