简体   繁体   English

使用unique_ptr作为成员的C ++模板的构造函数失败

[英]Constructor of C++ Template with unique_ptr as member fails

When a class template contains an unique_ptr to another class the constructor of the class does not move the unique_ptr into the new Object. 当类模板包含另一个类的unique_ptr时,该类的构造函数不会将unique_ptr移动到新的Object中。 Using the same class, but without a template the constructor generates the object as expected. 使用相同的类,但没有模板,构造函数按预期生成对象。

#include <iostream>
class test1{
public:
    std::string s_;
    test1(std::string s):s_(s){};
};
class testu{
public:
    std::unique_ptr<test1> us_;
    testu(std::unique_ptr<test1> us):us_(std::move(us)){};
};

template <int i>
class testt {
public:
    std::unique_ptr<test1> us_;
    testt<i>(std::unique_ptr<test1> us):us_(std::move(us)){};
};

template class testt<0>;

int main(int argc, const char * argv[]) {
    //without template
    std::unique_ptr<test1> us(new test1("test"));
    testu* t1=new testu(move(us));
    std::cout<<t1->us_->s_<<"\n";

    //with template the constructor fails!
    std::unique_ptr<test1> ust(new test1("test"));
    testt<0>* t2=new testt<0>(std::move(us));
    std::cout<<t2->us_->s_<<"\n";  //crash!
    return 0;
}

It's just a typo: 这只是一个错字:

testt<0>* t2 = new testt<0>(std::move(us));

This line should be 这条线应该是

testt<0>* t2 = new testt<0>(std::move(ust));

us was already moved from in the first section of main , therefore the access in the penultimate line is invalid: us已经从main的第一部分移开,因此倒数第二行的访问无效:

std::cout<<t2->us_->s_<<"\n"; 
//             ^^^
//              | Was already moved from, access causes UB

Fixing that makes the program run fine . 修复使程序运行正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM