Reputation: 6592
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;
}
Upvotes: 1
Views: 1218
Reputation: 283793
You're making too many new objects. In main
, you're looking for an int
inside x->reg_vec
, but makeTestFrom
doesn't add anything to x
, it creates a brand-new object and puts the integer inside that.
Besides that, you're abusing shared_ptr
. In C++, avoid dynamic allocation when you can. int
are cheaper to pass by value than with shared_ptr
, so just use vector<int>
. And Test
objects can be created with automatic lifetime also.
Just because some other languages (i.e. Java) make everything a handle doesn't mean that's a good pattern for C++.
Upvotes: 3
Reputation: 51545
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
Upvotes: 4