c++ - 具有 unique_ptr 作为成员的 C++ 模板的构造函数失败

标签 c++

当类模板包含指向另一个类的 unique_ptr 时,该类的构造函数不会将 unique_ptr 移动到新对象中。 使用相同的类,但没有模板,构造函数按预期生成对象。

#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;
}

最佳答案

这只是一个错字:

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

这一行应该是

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

us 已经从 main 的第一部分移出,因此倒数第二行的访问无效:

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

修复 program run fine .

关于c++ - 具有 unique_ptr 作为成员的 C++ 模板的构造函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27190665/

相关文章:

c++ - 打印作业时,最后的作业状态是 JOB_STATUS_RETAINED,而不是 JOB_STATUS_PRINTED

c++ - C++ 的优化技术

C++ #include <[filename]> 但#include <string> 不是文件名

c++ - 此哈希仅适用于枚举类型

c++ - VS2005(或VS2010)从VS2005升级时出现LNK2001和LNK2019错误

c++ - VS2013 - 多次包含同一 header 时出错

c++ - 将多边形坐标从 Double 转换为 Long 以用于 Clipper 库

c++ - 释放指针时出现段错误

c++ - OpenCV flann.h 断言错误

c# - while(true)/while(1) 与 for(;;)