Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Constructor to a Function

I am using an STL vector that is a vector of Parameters.

std::vector<Parameter> foo;

I was trying to find a way to add Parameter objects to the vector without doing this:

Parameter a;
foo.push_back(a);

I came across an implementation that did this:

foo.push_back(Parameter()); //Using the Parameter constructor

I thought that when I created an object the constructor is called not vise versa. Why can I pass a constructor to a function?

like image 490
larrylampco Avatar asked Jun 19 '13 14:06

larrylampco


2 Answers

foo.push_back(Parameter()); is passing a temporarily constructed Parameter object to push_back and not the constructor i.e. Parameter() is a call to create an object of type Parameter on the stack and pass it to the push_back function of vector, where it gets moved/copied. Thus what gets passed is not the constructor itself, but a constructed object only.

It's just a shorthand way of writing Parameter a; foo.push_back(a); when one is sure that a is not used anywhere down the line; instead of declaring a dummy, temporary variable, an anonymous temporary is created and passed.

These might be useful if you want to learn more about temporaries:

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=198

http://msdn.microsoft.com/en-us/library/a8kfxa78%28v=vs.80%29.aspx

like image 89
legends2k Avatar answered Sep 23 '22 21:09

legends2k


That line will create a temporary instance of Parameter and copy it into Foo. Assuming this is pre-C++11 code. The new std::vector<T>::push_back has an overload for rvalues in which case there will be no copies.

like image 35
David G Avatar answered Sep 19 '22 21:09

David G