我有一个内存分配问题,其中std::shared_ptr
被分配了两次:
#include <memory>
#include <vector>
std::vector<std::shared_ptr<int>> list;
std::shared_ptr<int> test (int i) {
list.push_back(std::make_shared<int>(i));
return list.back();
}
int main() {
std::shared_ptr<int> a = test(5);
}
Valgrind输出:
==28524== HEAP SUMMARY:
==28524== in use at exit: 0 bytes in 0 blocks
==28524== total heap usage: 2 allocs, 2 frees, 48 bytes allocated
==28524==
几乎所有std
容器都会发生这种情况。我只打电话std::make_shared
一次。
为什么我只运行一次std::make_shared
时会获得2个分配?如果可能,我如何只有1个分配?这是正确的编码还是我可以提高效率?
答案 0 :(得分:5)
valgrind唯一告诉你的是有两个分配。它没有告诉你分配了什么类型的对象。
值得测试一个基本案例:
#include <vector>
std::vector<int> list;
int test (int i) {
list.push_back(i);
return list.back();
}
int main() {
int a = test(5);
}
在这里,我们将看到分配了一个区域:std::vector
:
==10570== HEAP SUMMARY:
==10570== in use at exit: 0 bytes in 0 blocks
==10570== total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==10570==
==10570== All heap blocks were freed -- no leaks are possible
同样,如果你只使用shared_ptr,你最终也会得到一个分配:
#include <memory>
std::shared_ptr<int> test (int i) {
return std::make_shared<int>(i);
}
int main() {
std::shared_ptr<int> a = test(5);
}
==10601== HEAP SUMMARY:
==10601== in use at exit: 0 bytes in 0 blocks
==10601== total heap usage: 1 allocs, 1 frees, 32 bytes allocated
==10601==
==10601== All heap blocks were freed -- no leaks are possible
当然,当你同时拥有一个shared_ptr和一个容器时,你最终会得到两个分配,就像valgrind报告一样。 (容器分配比shared_ptrs容器大,而不是int容器,因为shared_ptr大于int。)