Using constructor in function call?

I have been looking for some time for a good explanation of why / why not the next use of the constructor constructor as a function argument is legal. Can someone provide one?

 // Begin simple illustrative example C++ program #include<vector.h> struct Item { Item(double data, const int lead) : m_grid(data), m_lead(lead) {} double m_grid; int m_lead; }; int main() { double img = 0.0; int steps = 5; std::vector<Item> images; for (int i = 0; i < steps; i++) { img += 2.0; images.push_back(Item(img,i)); } return 0; } 

I got the impression that the constructor has neither a return type nor an operator ...

+7
source share
4 answers

It is legal.

You never call a constructor yourself; you are actually just declaring an unnamed or "temporary" object of type Item . See how the syntax evolves when you make an object unnamed:

 Item a(img,i); // normal Item(img,i); // temporary 

Even if it seems that you are calling the constructor as a function, it is not.

Anyway, you can use a temporary value like "rvalue" (because it is one) in function arguments and the like, what are you doing here.


By the way, do not use the old iostream.h and vector.h . They preceded 1998. In the ISO C ++ standard, you should use iostream and vector respectively. Standard C ++ headers do not end with ".h" (inb4, ignoring the C headers inherited for backward compatibility).

+4
source

This is not a constructor or its return value, which passed before push_back . C ++ actually uses the constructor to create an unnamed temporary object that exists only for the duration of the function call; usually on the stack. Then it is passed to push_back , and push_back copies its contents to your vector.

+8
source

This is legal because push_back takes a const argument by reference, and then creates a copy of the object. A constructor call creates a temporary object, which is an rvalue. A constant reference can bind the value of r. The method cannot change the passed object, but it can create a copy.

+4
source

Although this looks like a function call, the expression Item (img, i) is actually a temporary object creation. The difference is that at runtime, memory will be allocated for the object on the stack, and then the constructor will be called, whereas if it were a normal function call, memory would not be allocated.

+3
source

All Articles