TL;博士:如果它是由前template<typename Something>
拷貝構造函數不叫,那Something
在構造函數簽名中使用。g ++不會調用複製構造函數,如果它是模板?
證明的概念(ideone):
#include <cstdio>
template<typename T>
class Test {
private:
T value_;
public:
mutable bool has_copies;
Test(const T& value) : value_(value), has_copies(false) {}
template<typename Related> // remove template here to fix behavior
Test(const Test<Related>& t) {
printf("In copy constructor\n");
value_ = t.value_;
has_copies = true;
t.has_copies = true;
}
};
int main() {
Test<int> t1(42);
printf("Before constructor\n");
Test<int> t2(t1);
printf("After constructor:\n");
printf(" t1 thinks it %s copies\n", t1.has_copies ? "has" : "doesn't have");
printf(" t2 thinks it %s copies\n", t2.has_copies ? "has" : "doesn't have");
}
輸出:
Before constructor
After constructor:
t1 thinks it doesn't have copies
t2 thinks it doesn't have copies
通知如何不打印In copy constructor
。
使複製構造函數非模板化(即在簽名中刪除template<typename Related>
並將Related
更改爲T
)爲我解決了這個問題。
$ g++ --version
g++ (GCC) 6.2.1 20160830
編譯&執行命令:
g++ -Wall -Wextra -pedantic -std=c++11 -O2 -Wshadow -Wformat=2 -Wfloat-equal -Wconversion -Wlogical-op -Wcast-qual -Wcast-align -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC -D_FORTIFY_SOURCE=2 -fsanitize=address -fsanitize=undefined -fno-sanitize-recover -fstack-protector "test.cpp" -o "test" && "test"
這是怎麼回事嗎?