How do I handle temporary variables in C++?

Viewed 88

this is more of a "what is good practice" type of question. Whenever I intialize a temporary variable inside a function, how do I ensure efficient use of memory in cases like these?

For example: I have a function that needs an input from the user via the getline command and I need to convert it to a string to save it the way I want to. To temporarily store the input I have created two char pointer arrays, which are then converted to a string and deleted afterwards.

void Book::FeedData()
{
    std::cin.ignore();

    char* bName = new char[20];
    char* aName = new char[20];

    std::cout << "\nEnter Title Name: "; std::cin.getline(bName,20);
    std::cout << "\nEnter Author Name: "; std::cin.getline(aName,20);

    *book_name = std::string(bName);
    *book_author = std::string(aName); 

    delete[] bName;
    delete[] aName;

}

Is this good practice? If I didn't use pointers, would the memory allocated to these variables be freed once I leave the scope of this function or do I "save" memory by allocating the memory manually and manually deleting it?

And if this isn't good practice, what advice do you have for handling temporary variables like these when they're not needed anymore?

0 Answers
Related