【问题标题】:Base class should be explicitly initialized in the copy constructor基类应在复制构造函数中显式初始化
【发布时间】:2016-06-03 21:39:22
【问题描述】:

我已经在 Stack Overflow 上的其他主题中看到了这个问题的答案,但我不确定在我的情况下该怎么做。我是模板的新手,这是我/曾经/使用从该网站找到的示例创建的第一个模板。无论如何,这是下面的代码和相关的错误:

warning: base class 'class std::allocator<char>' should be explicitly initialized in the copy constructor [-Wextra] SecureString(const SecureString &) throw() {}

    template<class T> class SecureString : public std::allocator<T> {
    public:
    template<class U> struct rebind { typedef SecureString<U> other; };
    SecureString() throw() {}
    SecureString(const SecureString &) throw() {}
    template <class U> SecureString(const SecureString<U>&) throw() {}
    void deallocate(T *p, size_t n) {
        #ifdef _WIN32
        SecureZeroMemory((void *)p, n);
        #elif __linux__
        std::fill_n((volatile char *)p, (n * sizeof(T)), 0);
        #endif
        std::allocator<T>::deallocate(p, n);
    }
};

还有更多错误,但这是主要错误。我从示例中学到了最好的东西,所以任何帮助都将不胜感激,谢谢。

【问题讨论】:

    标签: c++ templates c++11 allocation stdstring


    【解决方案1】:

    这是我从警告消息中得到的(也复制构建基础):

    SecureString(SecureString const& other) throw() : std::allocator<T>(other) {}
    

    如果你不打算在那里做任何有用的事情,最好不要做default

    SecureString(SecureString const&) throw() = default;
    

    还有consider dumping the throw() exception specification

    【讨论】:

    • 谢谢,我昨天确实添加了std::allocator&lt;T&gt;(that),但直到现在我才知道为什么它修复了错误。该链接也很有帮助:)
    【解决方案2】:

    您的复制构造函数没有复制任何东西——特别是没有复制基类。

    最简单的解决方法是省略它(以及默认构造函数),因为编译器生成的版本会做正确的事情。

    无法显式复制基础:

    SecureString(const SecureString &other) throw() : allocator(other) {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 2019-12-24
      • 2014-07-02
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多