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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With