在这种情况下如何修复此错误? &#34;无效的参数&#39;候选人是:void FreeMemory(std :: vector <element *,std :: allocator <element =“”* =“”>&gt;&amp;)&#39;&#34;?

时间:2018-06-17 19:41:09

标签: c++ class c++11 const

如何删除矢量中的所有指针,然后才能复制到我的矢量新指针(如果是const个对象)?

class Element {
    int val;
public:
    Element(int val) :
            val(val) {
    }
};

class MyClass {
    vector<Element*> v;

    static void FreeMemory(vector<Element*>& vec) {
        for (unsigned int i = 0; i < vec.size(); i++) {
            delete vec[i];
        }
    }

public:
    MyClass() = default;
    MyClass(const MyClass& mc) {
        //...
    }
    MyClass& operator=(const MyClass& mc) {
        if (this == &mc) {
            return *this;
        }
        //...
        FreeMemory(mc.v); //**error** - how can I delete the memory of any Element?
        //...
        return *this;
    }
    // ....
    // ....
};   
  

绑定&#39; const std :: vector&#39;引用类型&#39; std :: vector&amp;&#39;丢弃限定符

我可以使用smart_poin修复它吗?

1 个答案:

答案 0 :(得分:1)

以下是拥有由std::vector管理的Element std::unique_ptrclass Element { int val; public: explicit Element(int val) : val(val) {} virtual ~Element() = default; /* Subclasses must implement this method: */ virtual std::unique_ptr<Element> clone() const = 0; }; class ExclusivelyOwning { private: std::vector<std::unique_ptr<Element>> v; public: ExclusivelyOwning() = default; ExclusivelyOwning(const ExclusivelyOwning& other) { v.reserve(other.v.size()); for (const auto& element : other.v) v.push_back(element->clone()); } ExclusivelyOwning& operator=(const ExclusivelyOwning& rhs) { /* Use copy-swap idiom, not shown here. */ return *this; } ExclusivelyOwning(ExclusivelyOwning&&) = default; ExclusivelyOwning& operator = (ExclusivelyOwning&&) = default; ~ExclusivelyOwning() = default; }; 个对象的类的草图。没有完全解决,但它可能作为一个起点。

Element

请注意,复制一个对象引用抽象类(在上面的代码中为clone)需要进一步的技术来使复制有意义。在这里,我使用了“虚拟构造函数” - mult_table = [ [1, 2, 3], [2, 4, 6], [3, 6, 9] ] for row in mult_table: print(" | ".join(map(str, row))) 方法。