Search code examples
c++constructortemporary-objects

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?


Solution

  • 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