I'm new to C++ and I have a very hard time understanding relational mechanisms. I come from a PHP background with databases and ORMs and I fail to reproduce a very simple case. The program crashes with a segmentation fault in "atomic.h" line 49 { return __atomic_fetch_add(__mem, __val, __ATOMIC_ACQ_REL); }. The problem comes from the shared_ptr although I don't really understand how to use smart pointers (I've read hundreds of articles and SO questions about them but still very mysterious).
Without being able to make a working pointer on a repository element, my attempts to make one-to-many and many-to-one relationships between classes all failed miserably. I must be missing something, or maybe it's not at all the way we should do it in C++?
Note: I compile with GCC6.3 with C++17 using std only, not boost.
class Car : public enable_shared_from_this<Car> {
//...
}
template <class Type>
class Repository<Type> {
vector<Type> collection;
public:
shared_ptr<Type> getNew() {
Type newType;
collection.push_back(newType);
return shared_ptr<Type>(&collection.back());
// I also tried this but program fails at this line although it compiles fine.
// return collection.back().shared_from_this();
}
}
class MainApp {
Repository<Cars> cars;
shared_ptr<Car> myCar;
public:
MainApp() {
myCar = cars.getNew();
}
}
int main() {
MainApp app; // OK - myCar points to the last car in cars repository
return 0; // SIGEGV Segmentation fault
}