简体   繁体   中英

How to feed a shared_ptr to a template function that shall add various data types to a vector?

In this question it was suggested to use std::shared_ptr instead of std::unique_ptr . However I am not able to make this work when feeding this shared pointer to my function:

 std::vector<std::unique_ptr<segment>> v3;

    //VERSION 5:
    auto myLine2 = std::make_shared<Line>(start, end);
    add_segment(v3, myLine2);

Here's the new implementation of the function:

template<typename T1, typename T2>
inline void add_segment(T1 & v, T2& line_or_circle)
{
    v.emplace_back(std::move(line_or_circle));
}

What am I doing wrong here?

You can't "move" the thing inside a shared_ptr into an instance of a unique_ptr . If you could, all kinds of problems would occur as a result of two different smart pointers trying to delete the thing inside it when they get released.

Instead, just delcare your vector as:

std::vector<std::shared_ptr<segment>> v3;

And then, you really don't need move semantics after that:

template<typename T1, typename T2>
inline void add_segment(T1 & v, T2& line_or_circle)
{
    v.emplace_back(line_or_circle);
}

I am not sure you willing to share the ownership of the Line or not. But I expect you would like to have a vector holding unique pointers. So when your vector is destroyed it cleans up everything. If your vector, again, if your vector is responsible for the life cycle of lines. Check this:

template <typename T1, typename T2>
inline void add_segment(T1 &v, std::unique_ptr<T2> line_or_circle)
{
    v.emplace_back(std::move(line_or_circle));
}

struct Line
{
    Line(int s, int e)
    {
        start = s;
        end = e;
    }
    int start;
    int end;
};

int main()
{
    std::vector<std::unique_ptr<Line>> v3;

    auto myLine2 = std::make_unique<Line>(1, 5);
    add_segment(v3, std::move(myLine2));
}

Can you post an error message at least? Or produce enough code so that this is easily reproducible.

From what I can tell, I don't believe you are using std::vector::emplace_back correctly. emplace_back forwards parameters to the constructor of type std::unique_ptr<segment> . But line type does not match std::unique_ptr<segment> type.

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