Is this possible? According to what I’m trying to accomplish, it appears not so.
The function
static std::string str_repeat(std::string * str, int num_times) {
std::string * str_rep = new std::string;
for (int n = 1; n <= num_times; n++) {
str_rep = str_rep + str;
}
std::string ret = *str_rep; //error
delete str;
delete str_rep;
return ret;
}
Update
Sorry, I didn’t post the error in the first place because I thought it was a universal C++ issue that I was doing wrong. Here it is.
error: invalid operands of types ‘std::string* {aka std::basic_string<char>*}’ and ‘std::string* {aka std::basic_string<char>*}’ to binary ‘operator+’
You are trying to add two pointers together, which is why it wont compile. Don’t forget that a pointer is a memory address, the +operator wont be called in your example – you would have to dereference the pointer, but I wouldn’t recommend that pattern in this case. I’d suggest you read up a little more about pointers and references 🙂
Be very careful about when you delete memory. It’s bad practice to delete memory away from the context in which it was allocated – that’s a recipe for bugs. Also, if you allocated on the stack before calling ‘delete str’, your application would likely crash.
For string manipulation I would really recommend passing by const reference. Thus will will deal with memory allocation for you, as you can pass std::string by value, and it will internally perform memory allocation as needed…
Another couple of points.
In C, languages, we usually count from ‘0’, so I would change your for loop
In a proper application, I would have some debug assert on your input parameters: i.e. you should assert that num_times is ‘>0’
The following code compiles and executes with result “barbarbar”…
Cheers and good luck,
Jon