n**d 发帖数: 9764 | 1 Could any ppl explain the output from vector code below? |
X****r 发帖数: 3557 | 2 Why don't you also track the constructor and copy constructor? That would
answer your question. |
n**d 发帖数: 9764 | 3 Here it is. Why is it copied twice for each push? And the order looks
strange?
Circle
Circle
Circle
push
Circle(&c)
Circle(&c)
Circle(&c)
~Circle
Circle(&c)
Circle(&c)
Circle(&c)
~Circle
~Circle
iterator
Circle::draw
Circle::draw
Circle::draw
done
~Circle
~Circle
~Circle
~Circle
~Circle
~Circle
【在 X****r 的大作中提到】 : Why don't you also track the constructor and copy constructor? That would : answer your question.
|
X****r 发帖数: 3557 | 4 No, it is not exactly copied twice for each push. Some push are more costly
than others.
More hints:
1. Add tracking statements between the pushes, so you know which push causes
what.
2. Print 'this' in the constructor and both 'this' and the address of the
object being copied from in the copy constructor, so you know which object
is copied to where.
After you have done these,
3. Try adding 'circles.reserve(3);' before the first push_back, see if that
changes anything, and think about why.
Lear
【在 n**d 的大作中提到】 : Here it is. Why is it copied twice for each push? And the order looks : strange? : Circle : Circle : Circle : push : Circle(&c) : Circle(&c) : Circle(&c) : ~Circle
|
n**d 发帖数: 9764 | 5 I may know the answer. vector has to resize the memory for each push and
then move the existing data to new location.
costly
causes
that
【在 X****r 的大作中提到】 : No, it is not exactly copied twice for each push. Some push are more costly : than others. : More hints: : 1. Add tracking statements between the pushes, so you know which push causes : what. : 2. Print 'this' in the constructor and both 'this' and the address of the : object being copied from in the copy constructor, so you know which object : is copied to where. : After you have done these, : 3. Try adding 'circles.reserve(3);' before the first push_back, see if that
|
n**d 发帖数: 9764 | 6 That is. Here is the result.
Circle, this: 0012FF60
Circle, this: 0012FF5C
Circle, this: 0012FF58
push C1
Circle 003707E0 (&c:0012FF60)
push C2
Circle 00370818 (&c:003707E0)
Circle 00370819 (&c:0012FF5C)
~Circle
push C3
Circle 003707E0 (&c:00370818)
Circle 003707E1 (&c:00370819)
Circle 003707E2 (&c:0012FF58)
~Circle
~Circle
iterator
Circle::draw
Circle::draw
Circle::draw
done
~Circle
~Circle
~Circle
~Circle
~Circle
~Circle
【在 n**d 的大作中提到】 : I may know the answer. vector has to resize the memory for each push and : then move the existing data to new location. : : costly : causes : that
|
l**a 发帖数: 423 | 7 我觉得是vector创建了独立的copy,所以当程序退出时候 C1,C2,C3 destructor
called. 但是vector 面也有3个copy.
可以做个测试,你写个constructor。如果同样多出3个constructor 那么就证明是
vector 创建了独立的copy |
d***q 发帖数: 1119 | 8 when your obj was delivered as an argument without using reference type, the
copy construtor would be invoked to duplicate a object. it is costly
sometimes |