Reputation: 9
I am under impressions that std::shared_ptr doesn't free memory when it gets out of scope. Below is my test code. Can you please suggest me what I am doing wrong. I use gtest for testing. When I execute this test I can see that memory is constantly consumed. I use Microsoft VC++ 2013.
void ProceedVector() {
std::vector<double> * numbers = new std::vector<double>();
for (int ind = 0; ind != 10000; ind++) {
numbers->push_back(ind);
}
std::shared_ptr<std::vector<double>> numbersPtr = std::make_shared<std::vector<double>>(*numbers);
}
TEST_F(ManagerTypeConvertorTest, ProceedVector) {
for (int ind = 0; ind != 50000; ind++) {
ProceedVector();
}
}
Upvotes: 0
Views: 417
Reputation: 409136
You have two pointers to two different vectors:
One which will be deleted (the shared pointer containing a copy of the contents from the first vector)
And one which will not be deleted (the first vector you create with new
).
Upvotes: 0
Reputation: 171097
Each call to ProceedVector
does two dynamic allocations of std::vector<double>
objects. One here:
std::vector<double> * numbers = new std::vector<double>();
And the other one here:
std::shared_ptr<std::vector<double>> numbersPtr = std::make_shared<std::vector<double>>(*numbers);
make_shared
doesn't mean "assign this object to a shared_ptr
." It means "allocate a new object from these parameters, and manage the newly allocated object using a shared_ptr
."
Depending on what you want the code to achieve, either replace the new
line with the make_shared
one and don't use a raw pointer at all, or replace the make_shared
line with this:
std::shared_ptr<std::vector<double>> numbersPtr{numbers};
That will construct a shared_ptr
which will manage the memory pointed to by numbers
.
Upvotes: 2