提问者:小点点

用rvalue初始化智能指针


我想了解创建new_class2'时出现的问题是否是因为std::make_shared返回了一个rvalue。 如果是的话,还有什么其他方法可以初始化对象,尽管我已经在new_class中创建了这个方法。

#include <iostream>
#include <memory>
#include <vector>

class Foo
{
private:
    std::shared_ptr<std::vector<int>> common_number;

public:
    Foo(std::shared_ptr<std::vector<int>> &integer_vec) : common_number(integer_vec)
    {
        for (auto &v : *integer_vec)
        {
            std::cout << v << std::endl;
        }
    }
    ~Foo()
    {
    }
    void addTerm(int integer)
    {
        common_number->push_back(integer);
    }
    void print()
    {
        for (auto &v : *common_number)
        {
            std::cout << v << std::endl;
        }
    }
};

int main()
{
    std::vector<int> vec = {};
    std::shared_ptr<std::vector<int>> int_ptr = std::make_shared<std::vector<int>>(vec);

    Foo new_class(int_ptr);
    Foo new_class1(int_ptr);

    new_class1.addTerm(5);
    new_class.print();

    new_class.addTerm(1);
    new_class1.print();

    Foo new_class2(std::make_shared<std::vector<int>>(vec));

    return 0;
}

我确实得到了编译错误:

错误:从类型为“std::shared_ptr>”foonew_class2'(std::make_shared(1));“的r值初始化类型为”std::shared_ptr>“的非常量引用无效


共1个答案

匿名用户

只需将其作为const传递

class Foo
{
public:
    Foo(const std::shared_ptr<int> &integer_)
    {
        std::cout << *integer_ << std::endl;
    }
};