I have a template List class, which overrides copy-constructor and the assignment operator:
template <typename T>
class List {
public:
...
List() :
_first(0),
_last(0),
_size(0) {
std::cout << "[Constructor called]" << std::endl;
}
List(const List& rhs) :
_first(0),
_last(0),
_size(0) {
std::cout << "[Copy constructor called]" << std::endl;
copyFrom(rhs);
}
~List() {
clear();
}
inline List& operator=(const List& rhs) {
std::cout << "[Assignment operator called]" << std::endl;
clear();
copyFrom(rhs);
return *this;
}
...
}
Now, I am executing the following simple test code. I assumed that when calling the get() method there are copies of the List created - but this is not the case, only my normal constructor is called:
#include <iostream>
#include <string>
#include "List.hpp"
using namespace std;
List<string> get() {
List<string> l;
l.addBack("this");
l.addBack("is");
l.addBack("a");
return l;
}
int main(int argc, char **argv) {
List<string> listA = get();
List<string> listB = get();
listA.addBack("test");
std::cout << std::endl;
for (auto element : listA) {
std::cout << element << std::endl;
}
std::cout << std::endl;
for (auto element : listB) {
std::cout << element << std::endl;
}
}
And the output is:
[Constructor called]
[Constructor called]
this
is
a
test
this
is
a
How does this work, and why does it not call the copy constructor?