【发布时间】:2022-01-08 22:38:26
【问题描述】:
我的第一个问题是添加地图的对象A(v),退出范围时应该自动删除吗?
我的第二个问题是,当程序退出时,添加到地图中的对象会发生什么?我相信当我执行 a_[name] = A(v); 时,会将副本存储到地图中。 另外,我需要提供一个拷贝构造函数吗?
void B::AddA(std::string name, int v) {
a_[name] = A(v);
}
我的最后一个问题是我没有用“new”创建任何对象,我不应该删除任何对象。
我不明白泄漏是从哪里来的。
感谢您的帮助。谢谢。
完整代码
#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)
【问题讨论】:
-
exit(0)不是可返回函数。b没有被销毁。使用普通的return 0。 -
@273K 或者什么都没有。
标签: c++ object memory-leaks valgrind