0

I have a class containing a vector of unique_ptr as attribute:

class C1 {
public:
    void addInVec(unique_ptr<T> elem) {
        vec.push_back(std::move(elem));
    }
    void manipulate() {
        for (auto i = vec.begin(); i != vec.end(); ++i) {
            auto res = (*i)->method(); // ERROR: why?
        }
    }
private:
    vector<unique_ptr<T>> vec;
}

I call addInVec as follows:

c1.addInVec(make_unique<T>());

Output when running the code in clion:

Process finished with exit code -1073741819 (0xC0000005)

I followed this link for insersion: Why can I not push_back a unique_ptr into a vector?

I followed this link for access: Access elements of vector<std::unique_ptr<T> > using an iterator?

I also tried various version of manipulate, all failed:

    void manipulate() {
        for (const auto & elem : vec) {
            auto res = elem->method(); // ERROR: why?
        }
    }
    void manipulate() {
        for (int i = 0; i < vec.size(); ++i) {
            auto res = vec[i]->method(); // ERROR: why?
        }
    }
    int res = std::count_if(vec.begin(), vec.end(), [](const std::unique_ptr<T> & elem) {
        return (elem->method() == 1); // ERROR: why?
    });

What did I miss?

Theophile Champion
  • 453
  • 1
  • 4
  • 20
  • 2
    The code you have shown looks fine, so the problem is likely in code you have not shown. For instance, if you are calling `manipulate()` on an invalid `C1` object. Please provide a [mcve] that demonstrates the error in action. – Remy Lebeau Dec 03 '20 at 22:49
  • Ok, I am stupid. The function manipulate was all right I call it on an invalid C1 as proposed by Remy. This came from a silly mistake in a constructor not presented here (swapping two lines of this constructor solved the issue, i.e. initialising the C1 before using it...) – Theophile Champion Dec 03 '20 at 23:12

0 Answers0