Search code examples
c++scopeshared-ptr

Why does this shared_ptr code segfault? When do shared_ptr's free?


I've made a SSCE as best I can. My suspicion is that the shared pointers deconstruct (free) my objects before I ask for them in main. How can I prevent this without circumventing shared pointers altogether? This is in isolated problem in a program that otherwise is greatly helped by the use of shared_ptrs.

Test.h:

#ifndef TEST_H
#define TEST_H
#include <memory>
#include <iostream>
#include <vector>

class Test
{
    public:
        Test();
        virtual ~Test();
        static std::shared_ptr<Test> makeTestFrom(std::string l);
        std::vector<std::shared_ptr<int>> reg_vec;
    protected:
    private:

};

#endif // TEST_H

Test.cpp

#include <memory>
#include <iostream>
#include <vector>
Test::Test():
reg_vec()
{
    //ctor
}

Test::~Test()
{
    //dtor
}
std::shared_ptr<Test> Test::makeTestFrom(std::string l)
{
    std::shared_ptr<Test> sp(new Test());
    std::shared_ptr<int> i(new int(3));
    sp->reg_vec.push_back(i);
    return sp;
}

main.cpp:

#include <memory>
#include <iostream>
#include <vector>
#include "include/Test.h"
using namespace std;

 int main()
{
    std::unique_ptr<Test> x(new Test());
    x->makeTestFrom("loldoesntmatter");
    std::cout << x->reg_vec[0] << std::endl;
    return 0;

}

Solution

  •  int main() {
        std::unique_ptr<Test> x(new Test());
        x->makeTestFrom("loldoesntmatter"); // you discarded the return
        std::cout << x->reg_vec[0] << std::endl; // x->reg_vec is empty
        return 0;
    
    }
    

    Also, too many shared pointers