Reputation: 303
Given the following:
#include<iostream>
#include<list>
class test{
public:
int t = 34;
};
std::list<test> list;
void func(){
test t;
list.push_back(t);
}
int main(){
func();
std::cout<<list.front().t<<std::endl;
}
It prints 34
. Given that list.push_back(test &ref)
is called (so the parameter is not copied), why does the object remains even after the exit of the function?
Upvotes: 0
Views: 180
Reputation: 6326
list.push_back(test &ref)
doesn't mean that the reference is stored. For containers, all elements are copied/moved, or construct in place.
Why does the object remain even after the exit of the function? The remained value is a copy.
See the reference:
void push_back( const T& value ); (1) void push_back( T&& value );(2) (since C++11)
Appends the given element value to the end of the container.
- The new element is initialized as a copy of value.
- value is moved into the new element. No iterators or references are invalidated.
Upvotes: 1