k**l 发帖数: 2966 | 1 I have a question of c++ programing habit,
I sometimes use list, map or other container to store user defined classes,
and use it later in member functions--say
std::list m_list;
When inserting a new element, I always have to fully create an element, then
call push_back or insert.
MyElement elem(1,2,"something"...);
m_list.push_back(elem);
And push_back would call copy constructor (I defined in MyElement class) to
duplicate the object.
After inserting, the elem itself is never used anymore, only elements in m_
list got used again and again.
I think this is a bit waste of time to always create the MyElement class
twice for this insertion---considering MyElement has some char (or other
type of) arrays. How should I improve the efficiency? Should I always use
pointer containers in this case or there are some neater coding habit?
Thanks | k**l 发帖数: 2966 | 2 更不爽的是list 的 push 比其他的更复杂些,其他的是copy, list 是copy or move
?
,
then
to
【在 k**l 的大作中提到】 : I have a question of c++ programing habit, : I sometimes use list, map or other container to store user defined classes, : and use it later in member functions--say : std::list m_list; : When inserting a new element, I always have to fully create an element, then : call push_back or insert. : MyElement elem(1,2,"something"...); : m_list.push_back(elem); : And push_back would call copy constructor (I defined in MyElement class) to : duplicate the object.
| l*********s 发帖数: 5409 | 3 no sure what you mean by move, I don't know list container does that.
for optimization, you could do
(1) copy smart pointer than object,
(2) design your class such that copy op is really cheap
(3) move semantics in c++11, or maybe unnamed variable hoping the compiler
could optimize it away |
|