My first question is that the object A(v) that added the the map, it should be deleted automatically when exit the scope?
My second question is what would happen to the object added into the map, when program exits? I believe when I do a_[name] = A(v);, a copy is stored to the map. Also, do I need to provide a copy constructor?
void B::AddA(std::string name, int v) {
a_[name] = A(v);
}
My last question is that I did not create any object with "new", I shouldn't need to delete any.
I don't understand where the leak come from.
I appreciate any help. Thank you.
full code
#include <map>
#include <string>
#include <iostream>
class A {
public:
int vala_;
A();
~A();
A(int v);
};
A::A() {
vala_ = 0;
}
A::~A() {}
A::A(int v) {
vala_ = v;
}
class B {
public:
int valb_;
std::map<std::string, A> a_;
B();
~B();
void AddA(std::string name, int v);
};
B::B() {
valb_ = 0;
}
B::~B() {
}
void B::AddA(std::string name, int v) {
a_[name] = A(v);
}
int main() {
B b;
b.AddA("wewe", 5);
std::cout << b.a_["wewe"].vala_ << std::endl;
exit(0);
}
valgrind
I replaced the number ==????==, to ==xxxx==. I guess it was the process id.
==xxxx== Memcheck, a memory error detector
==xxxx== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==xxxx== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
==xxxx== Command: ./a.out --leak-check=full -s
==xxxx==
5
==xxxx==
==xxxx== HEAP SUMMARY:
==xxxx== in use at exit: 72 bytes in 1 blocks
==xxxx== total heap usage: 3 allocs, 2 frees, 73,800 bytes allocated
==xxxx==
==xxxx== LEAK SUMMARY:
==xxxx== definitely lost: 0 bytes in 0 blocks
==xxxx== indirectly lost: 0 bytes in 0 blocks
==xxxx== possibly lost: 0 bytes in 0 blocks
==xxxx== still reachable: 72 bytes in 1 blocks
==xxxx== suppressed: 0 bytes in 0 blocks
==xxxx== Rerun with --leak-check=full to see details of leaked memory
==xxxx==
==xxxx== For lists of detected and suppressed errors, rerun with: -s
==xxxx== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)