我有一个模板List类,它覆盖了copy-constructor和赋值运算符:
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;
}
...
}
现在,我正在执行以下简单的测试代码。我假设在调用get()方法时会创建List的副本 - 但事实并非如此,只调用我的普通构造函数:
#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;
}
}
输出是:
[Constructor called]
[Constructor called]
this
is
a
test
this
is
a
这是如何工作的,为什么不调用复制构造函数?