shinzou
shinzou

Reputation: 6192

About passing variables to STL containers and not losing them out of scope

Say we have the following code:

void foo()
{
        Point newpoint(...);
        dq.push_back(newpoint);
        ...
        return dq;
}

Suppose dq is deque, Point is some class.

in C, when foo() ends, then newpoint is gone and if it was passed to an array for example, it would've become garbage, but I see that in c++, dq actually keeps it when it's out of foo()'s scope, did it actually invoke a copy constructor on newpoint? What really happens to newpoint? and is this a feature of STL containers or C++'s constructors?

Upvotes: 0

Views: 68

Answers (2)

shuttle87
shuttle87

Reputation: 15924

As you can see push_back will either copy the element or move the element into the container. This original Point goes out of scope at the end of the function but the container isn't storing a reference to this temporary so it's fine.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119069

did it actually invoke a copy constructor on newpoint?

Yes.

and is this a feature of STL containers or C++'s constructors?

A STL container with element type T always contains T objects, rather than pointer-to-T or reference-to-T. When initializing an object of type T from an expression of type T, a copy or move is performed.

If you used deque<reference_wraper<Point>> instead then the deque would contain references to Point rather than Point objects, and no copies of Point would occur. It is good that you already understand how this would cause problems.

Upvotes: 5

Related Questions