以下代码(我无法制作更短的 MVCE)
单位.h:
#include <vector>
template<typename T>
struct foo
{
std::vector<T> data;
foo(foo&&) = default; // no assembly generated
foo(std::vector<T>&&v) : data(std::move(v)) {}
};
extern template struct foo<int>; // indicates template instantiation elsewhere
单位.cc:
#include "unit.h"
template struct foo<int>; // forces template intantiation
主.cc:
#include "unit.h"
struct bar
{
foo<int> f;
bar(foo<int>&&x) : f(std::move(x)) {}
};
bar makeBar(int x)
{
std::vector<int> v(x);
foo<int> f(std::move(v));
return {std::move(f)};
}
int main()
{
bar x = makeBar(5);
}
无法在 clang 下编译(Apple LLVM 版本 9.0.0 (clang-900.0.39.2) -哪个 llvm 版本?),结果:
test> clang++ -std=c++11 -c unit.cc
test> clang++ -std=c++11 -c main.cc
test> clang++ -std=c++11 main.o unit.o
Undefined symbols for architecture x86_64:
"foo<int>::foo(foo<int>&&)", referenced from:
bar::bar(foo<int>&&) in main-476e7b.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
gcc(8.2.0)一切正常。经检查,gcc 似乎发出foo<int>::foo(foo<int>&&)
in main.o
,而 clang 未能完全发出它。
正确的行为是什么:移动构造函数应该用ordefault
发出吗?这是一个已知的clang错误吗?unit.o
main.o
有用的链接:https ://en.cppreference.com/w/cpp/language/class_template