将std :: unique_ptr传递给类时出错

时间:2018-01-23 09:19:25

标签: c++ templates inheritance smart-pointers

我必须创建继承自抽象类的类实例。我的代码非常简单。它应该基于抽象类创建对象类的实例。抽象类也是模板类。然后我需要将此对象放入存储类,该类存放指向该对象的指针。在传递指针时我遇到错误:

templates.cpp: In member function ‘void storage::setPTR(std::unique_ptr<child>&)’:
templates.cpp:39:28: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = child; _Dp = std::default_delete<child>]’
             this->childPTR = pointer;
                            ^
In file included from /usr/include/c++/5/memory:81:0,
                 from templates.cpp:3:
/usr/include/c++/5/bits/unique_ptr.h:357:19: note: declared here
       unique_ptr& operator=(const unique_ptr&) = delete;
                   ^
templates.cpp: In function ‘int main()’:
templates.cpp:45:30: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp, class _Dp> class std::unique_ptr’
     std::unique_ptr<INTERFACE> p = std::make_unique<child>("xxx");
                              ^
templates.cpp:45:30: note:   expected a type, got ‘INTERFACE’
templates.cpp:45:30: error: template argument 2 is invalid
templates.cpp:45:65: error: cannot convert ‘std::_MakeUniq<child>::__single_object {aka std::unique_ptr<child>}’ to ‘int’ in initialization
     std::unique_ptr<INTERFACE> p = std::make_unique<child>("xxx");
                                                                 ^
templates.cpp:48:24: error: ‘newChild’ was not declared in this scope
     testStorage.setPTR(newChild);
                        ^

我的代码:

#include <iostream>
#include <string>
#include <memory>

// using namespace std;

template<typename type1, typename type2, typename type3> class INTERFACE {
    protected:
        type1 x;
        type2 y;
        type3 name;

    public:
        virtual type1 setX(type1 x) = 0;
        virtual type2 setY(type2 y) = 0;
};

class child : public INTERFACE<int, float, std::string> {
    public:
        child(std::string z) {
            this->name = z;
        }

        virtual int setX(int x) override {
            this->x = x;
        } 

        virtual float setY(float y) override {
            this->y = y;
        }
};

class storage {
    private:
        std::unique_ptr<child> childPTR;

    public:
        void setPTR(std::unique_ptr<child> & pointer) {
            this->childPTR = pointer;
        }
};

int main(){
    // std::unique_ptr<INTERFACE> newChild(new child("xxx"));
    std::unique_ptr<INTERFACE> p = std::make_unique<child>("xxx");

    storage testStorage;
    testStorage.setPTR(newChild);

    return 0;
}

我做错了什么?

1 个答案:

答案 0 :(得分:4)

  1. std::unique_ptr不可复制。虽然它是可移动的。因此,请在std::move中使用参数的传值和setPTR

  2. 您需要提供具体类型,而不是模板:

    std::unique_ptr<INTERFACE<int, float, std::string>> p =
        std::make_unique<child>("xxx");
    
  3. 声明newChild,在这种情况下,您再次需要std::move进入函数或发出该变量。