简体   繁体   中英

Initialize smart pointer with rvalue

I'd like to understand if the problem I have while creating new_class2 is because std::make_shared returns an rvalue . And if so, what are the other ways to initialize the object, despite the one that I already made in 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;
}

I do get the compilation error:

error: invalid initialization of non-const reference of type 'std::shared_ptr<int>&' from an rvalue of type 'std::shared_ptr<int>' Foo new_class2(std::make_shared<int>(1));'

As @Elijay and @underscore_d proposed in the comments, passing by value and then using move() would be the recommended approach

Foo(std::shared_ptr<std::vector<int>> integer_vec) : common_number(std::move(integer_vec))
    {
        for (auto &v : *integer_vec)
        {
            std::cout << v << std::endl;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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