I have the following problem in a c++-project at my university:
I want to store some objects of Class1 by using a map.
Because of the design of my project the class that holds the map as a member variable does not create the objects to store in the map. My research on this forum tells me to use unique_ptr to pass those objects.
When combining those two ideas in a test projects for experiments:
#include <iostream>
#include <memory>
#include <unordered_map>
typedef std::unique_ptr<std::string> string_ptr;
class Class1 {
public:
std::unordered_map<std::string, string_ptr> my_unordered_map;
Class1() : my_unordered_map(){
}
void addTo(string_ptr ptr) {
std::string string = *ptr;
std::cout << string << std::endl;
my_unordered_map[0] = std::move(ptr);
}
};
int main() {
std::cout << "Process started!"<< std::endl;
string_ptr ptr;
ptr = std::make_unique<std::string>("text");
Class1 cont;
cont.addTo(std::move(ptr));
}
it compiles, but throws a
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
at runntime.
I also tried changing void addTo(string_ptr ptr) to addTo(string_ptr &ptr) as suggested in other posts, but the problem remained the same.
Now, whats the problem? Is it:
a) A design mistake to not let Class1 create the objects by itself. C++ inserting unique_ptr in map would answer my question in this case.
-- or --
b) Something else my small knowledge of c++ lets me miss?
Sidenote: ofc the objects i want to store in those pointers are not strings.