我有一个包装 vector 的模板类。我试图在这个类中存储 unique_ptrs,它工作正常。但是,当我将 void add(const T& elem)
函数标记为虚拟时,我的编译器 (clang) 告诉我我正在为 unique_ptr 进行“调用隐式删除的复制构造函数”。
我知道无法复制 unique_ptr,所以我创建了 void add(T&& elem)
函数。我只是不知道为什么将另一个 add 函数标记为 virtual 会导致编译器错误。
感谢您的宝贵时间。
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
template <typename T>
class ContainerWrapper {
private:
vector<T> vec;
public:
ContainerWrapper() : vec() {
}
//Marking this as virtual causes a compiler error
void add(const T& elem) {
vec.push_back(elem);
}
void add(T&& elem) {
vec.push_back(std::move(elem));
}
T removeLast() {
T last = std::move(vec.back());
vec.pop_back();
return last;
}
};
int main() {
ContainerWrapper<unique_ptr<string>> w;
w.add(unique_ptr<string>(new string("hello")));
unique_ptr<string> s = w.removeLast();
cout << *s << endl;
}
最佳答案
这很可能是因为 ContainerWrapper 是一个模板。对于模板,只要您不调用成员函数,编译器通常不会检查它们。但是,将其标记为虚拟会强制该函数存在(您甚至可能会收到链接错误)。
你可以看看这篇文章:When the virtual member functions of a template class instantiated? .
关于c++ - 将函数标记为虚拟会导致 unique_ptr 出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554288/