草庐IT

c++ - 将 std::unique_ptr 传递给类时出错

coder 2024-02-20 原文

我必须创建从抽象类继承的类的实例。我的代码非常简单。它应该基于抽象类创建对象类的实例。抽象类也是模板类。然后我需要将这个对象放入保存指向该对象的指针的存储类中。传递指针时出现错误:

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. std::unique_ptr 不可复制赋值。虽然它是可移动分配的。因此,在 setPTR 中对参数和 std::move 使用按值传递。

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

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

关于c++ - 将 std::unique_ptr 传递给类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398060/

有关c++ - 将 std::unique_ptr 传递给类时出错的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  3. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  4. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  5. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. ruby - 安装libv8(3.11.8.13)出错,Bundler无法继续 - 2

    运行bundleinstall后出现此错误:Gem::Package::FormatError:nometadatafoundin/Users/jeanosorio/.rvm/gems/ruby-1.9.3-p286/cache/libv8-3.11.8.13-x86_64-darwin-12.gemAnerroroccurredwhileinstallinglibv8(3.11.8.13),andBundlercannotcontinue.Makesurethat`geminstalllibv8-v'3.11.8.13'`succeedsbeforebundling.我试试gemin

  8. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  9. ruby - 如何将 Puma::Configuration 传递给 Sinatra? - 2

    这是我的网络应用:classFront我是这样开始的(请不要建议使用Rack):Front.start!这是我的Puma配置对象,我不知道如何传递给它:require'puma/configuration'Puma::Configuration.new({log_requests:true,debug:true})说真的,怎么样? 最佳答案 配置与您运行的方式紧密相关puma服务器。运行的标准方式puma-pumaCLI命令。为了配置puma配置文件config/puma.rb或config/puma/.rb应该提供(参见examp

  10. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

随机推荐