加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:52:49 所属栏目:百科 来源:网络整理
导读:我有一个包含矢量的模板类.我试图在这个类中存储unique_ptrs,它工作正常.但是,当我将void add(const T elem)函数标记为虚拟时,我的编译器(clang)告诉我,我正在为unique_ptr进行“调用隐式删除的复制构造函数”. 我知道unique_ptrs无法复制,因此我创建了void
我有一个包含矢量的模板类.我试图在这个类中存储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();

    cout << *s << endl;
}

解决方法

这里的问题是std :: unique_ptr的拷贝构造函数标记为= delete.这意味着在使用std :: unique_ptr调用时,add(T const&)重载成员函数内的vec.push_back(elem)调用将无法编译.一旦成员函数被实例化,编译器就会意识到这一点.

Standard在14.7.1隐式实例化[temp.inst]中有2个相关引用:

6 If the overload resolution process can determine the correct
function to call without instantiating a class template de?nition,it
is unspeci?ed whether that instantiation actually takes place.

10 […] It is unspeci?ed whether or not an implementation implicitly
instantiates a virtual member function of a class template if the
virtual member function would not otherwise be instantiated. […]

第6条规定 – 没有虚拟关键字 – 允许编译器但不要求实例化add(T const&)和add(T&&)以便解决哪个过载是最佳匹配. gcc 4.7.2和Clang 3.2都不需要实例化,因为它们恰好推断出rvalue引用总是比临时引用更适合临时.

第10条规定 – 即使使用virtual关键字 – 也允许编译器但不需要实例化add(T const&)和add(T&&)以便解决哪个重载是最佳匹配. gcc 4.7.2和Clang 3.2都碰巧实例化了两个成员函数,即使它们都可以推断出左值超载永远不会是更好的匹配.

请注意,如果您使ContainerWrapper成为具有嵌套typedef的常规类unique_ptr< string> T;,然后gcc和Clang都会生成带或不带virtual关键字的错误,因为它们必须为两个成员函数生成代码.这不会是SFINAE,因为在替换推断的参数期间不会发生错误.

结论:这不是一个错误,而是一个实施质量问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读