Does this function leak memory?

D

dbpokorny

Hi,

I am new to C++, and I am wondering if the following function leaks
memory:

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/join.hpp>

string format_iv(vector<int> my_ints) {
vector<string> my_strings(my_ints.size());
transform(my_ints.begin(), my_ints.end(), my_strings.begin(),
boost::lexical_cast<string, int>);
return "[" + boost::algorithm::join(my_strings, ", ") + "]";
}

In particular, are the following objects deallocated upon function
exit, or do they leak?

1. my_strings
2. the temporary returned by boost::algorithm::join

Any help much appreciated,
--David
 
B

Bart van Ingen Schenau

Hi,

I am new to C++, and I am wondering if the following function leaks
memory:

No, it does not.
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/join.hpp>

string format_iv(vector<int> my_ints) {
        vector<string> my_strings(my_ints.size());
        transform(my_ints.begin(), my_ints.end(), my_strings.begin(),
boost::lexical_cast<string, int>);
        return "[" + boost::algorithm::join(my_strings, ", ") + "]";

}

In particular, are the following objects deallocated upon function
exit, or do they leak?

   1. my_strings

Cleaned up correctly
   2. the temporary returned by boost::algorithm::join

Unless boost::algorithm::join explicitly documents that you (the user)
are responsible for cleaning up the result, it will be automatically
cleaned up.
Any help much appreciated,
--David

Bart v Ingen Schenau
 
J

Juha Nieminen

dbpokorny said:
Hi,

I am new to C++, and I am wondering if the following function leaks
memory:

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/join.hpp>

string format_iv(vector<int> my_ints) {
vector<string> my_strings(my_ints.size());
transform(my_ints.begin(), my_ints.end(), my_strings.begin(),
boost::lexical_cast<string, int>);
return "[" + boost::algorithm::join(my_strings, ", ") + "]";
}

Basic rule of thumb: You didn't write a single 'new', thus the
function cannot leak memory (as far as your function is concerned; we
assume that those libraries don't leak memory, which can be a fair
assumption when it's a boost library).

Of course there may be some intricated ways of breaking this rule of
thumb, but in general it works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top