I'm a beginner and I am working to understand memory leaks.
Does the code below have any leaks? Does it make sense to use unique_ptr
for the vector
and map
?
My purpose is mostly for performance and minimal tolerance in my code. If this code is wrong, please tell me where I made a mistake.
typedef struct MyStruct
{
std::string name;
int age;
} tMyStruct;
typedef std::map<std::unique_ptr<MyStruct>, std::unique_ptr<MyStruct>> den_mp;
typedef std::vector< std::unique_ptr<MyStruct> > den_vec;
den_mp m_mp;
den_vec m_vec;
void doit(auto& mp)
{
for (auto it = mp.begin(); it != mp.end(); it++)
{
std::cout << it->first->name << std::endl;
}
}
void doit2(auto& mp)
{
for (auto it = mp.begin(); it != mp.end(); it++)
{
std::cout << it->get()->name << std::endl;
}
}
void addvec(std::string name, int age)
{
std::unique_ptr<MyStruct> strt(new MyStruct);
strt->age = age;
strt->name = name;
m_mp.emplace(std::move(strt), std::move(strt));
}
void addvec2(std::string name, int age)
{
std::unique_ptr<MyStruct> strt(new MyStruct);
strt->age = age;
strt->name = name;
m_vec.emplace_back(std::move(strt));
}
int main()
{
addvec("ads", 10);
addvec2("asdfg", 10);
doit(m_mp);
doit2(m_vec);
std::cin.get();
}