C++: How to use new to find store for function return value?

c++

Solution

How do I use new to find store? Am I expected to do something like `std::string* result = new std::string;` or should I be using new to create another C-style string somehow?

The latter; the method takes C-style strings and nothing in the text suggests that it should return anything else. The prototype of the function should thus be `char* cat(char const*, char const*)`. Of course this is not how you’d normally write functions; manual memory management is completely taboo in modern C++ because it’s so error-prone.

Although the problem doesn't mention using delete to free memory, I know I should because I will have used new to allocate. Should I just delete at the end of main, right before returning?

In this exercise, yes. In the real world, no: like I said above, this is completely taboo. In reality you would return a `std::string` and not allocate memory using `new`. If you find yourself manually allocating memory (and assuming it’s for good reason), you’d put that memory not in a raw pointer but a smart pointer – `std::unique_ptr` or `std::shared_ptr`.

Problem

I'm reading the 3rd edition of The C++ Programming Language by Bjarne Stroustrup and attempting to complete all the exercises. I'm not sure how to approach exercise 13 from section 6.6, so I thought I'd turn to Stack Overflow for some insight. Here's the description of the problem: Write a function cat() that takes two C-style string arguments and returns a single string that is the concatenation of the arguments. Use new to find store for the result. Here's my code thus far, with question marks where I'm not sure what to do: ``` ? cat(char first[], char second[]) { char current = ''; int i = 0; while (current != '\0') { current = first[i]; // somehow append current to whatever will eventually be returned i++; } current = ''; i = 0; while (current != '\0') { current = second[i]; // somehow append current to whatever will eventually be returned i++; } return ? } int main(int argc, char* argv[]) { char first[] = "Hello, "; char second[] = "World!"; ? = cat(first, second); return 0; } ``` And here are my questions: - How do I use new to find store? Am I expected to do something like `std::string* result = new std::string;` or should I be using new to create another C-style string somehow? - Related to the previous question, what should I return from cat()? I assume it will need to be a pointer if I must use new. But a pointer to what? - Although the problem doesn't mention using delete to free memory, I know I should because I will have used new to allocate. Should I just delete at the end of main, right before returning?

Original source