小编Tor*_*ial的帖子

将函数标记为虚拟会导致编译器错误与unique_ptr

我有一个包含矢量的模板类.我试图在这个类中存储unique_ptrs,它工作正常.但是,当我将void add(const T& elem)函数标记为虚拟时,我的编译器(clang)告诉我,我正在为unique_ptr进行"调用隐式删除的复制构造函数".

我知道unique_ptrs无法复制,所以这就是我创建void add(T&& elem)函数的原因.我只是不知道为什么将其他添加函数标记为虚拟导致编译器错误.

谢谢你的时间.

#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(); …
Run Code Online (Sandbox Code Playgroud)

c++ templates instantiation overload-resolution c++11

7
推荐指数
2
解决办法
459
查看次数