1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Foo
{
int x_;
public:
Foo( ) x_( 0 ) {} // ctor 1
Foo( int x ) x_( x ) {} // ctor 2
Foo( const Foo & rhs ) x_( rhs.x_ ) {} // ctor 3
void setX( int x ) // setter
{ x_ = x; }
};
// other code
Foo outer;
while ( cond ) {
outer.setX( i );
container.insert( outer ); // i1
Foo inner( i );
container.insert( inner ); // i2
container.insert( Foo( i ) ); // i3
}
// other code
|
'outer' and 'inner' are local stack variables. The lifetime of 'inner' is just one iteration of the loop; each iteration creates a new instance. The 'outer' exists in longer scope, and its state is changed with the setX().
In the 'i3' a Foo object is constructed and then passed to insert(), but the object is an unnamed temporary that exists only during the evaluation of line 26. That is even shorter life than what the 'inner' has.
Line 17 calls the ctor 1, the default constructor. Lines 23 and 26 call the ctor 2.
Which is better, the i1, or one of i2,i3? That depends on how expensive are the constructor and setX(). In Foo they are about as expensive. If the constructor does a lot of work under the hood and the setX merely adjusts values, then the i1 is preferable. One has to also consider
side effects. Constructor, setX, and destructor could do something extra, like
std::cout << x_ << '\n';
, and then it really matters when such things should happen.
Why did I show the ctor 3, the copy constructor? That is where the nature of insert() matters.
If it is
insert( Foo )
, then parameter is passed by value and ctor 3 is called.
If it is
insert( Foo & )
, then parameter is passed by reference and ctor 3 is not called.
What does the insert do? We don't actually need to know. Our code operates with "static" variables, making professor happy, but the container's implementation might still use
new
. Standard containers like std::vector do keep the data in the heap memory, i.e. allocate and deallocate memory dynamically, but in our code they look like "static" objects. It seems quite likely that the edgeHeap does the same. Swept under the carpet. SEP:
http://en.wikipedia.org/wiki/Somebody_Else%27s_Problem