2020-04-13

Will delete after return statement in C++ be executed?


I know that in C++ whenever new statement is used, there should be delete after new to release memory.

So look at the following code:


#include <iostream>
#include <string>
bool strcompare(std::string* pstr1);
int main(void) {
        std::string str1("hello");
        std::cout << strcompare(&str1) << std::endl;

        return 0;
}

bool strcompare(std::string* pstr1) {
        std::string* pstr2 = new std::string;
        std::cout << "Please enter a new string:" << std::endl;
        std::cin >> *pstr2;
        return *pstr1 == *pstr2 ? true : false;
        delete pstr2;
}

In strcompare function,  if delete pstr2; is put before return, then it is wrong because when program runs and I enter "hello", return value is 0 (false)

So I put delete after return.

But I am still worried that delete statement will not be executed after return.


Will delete after return statement in C++ be executed?
I am asking because even if no delete is used in accompany with new, programs still compiles and runs OK, which is claimed by many books to be terrible practice.


2 comments:

Keith Thompson said...

No, the `return` statement immediately terminates execution of the function, and anything following it will not be executed. (You're likely to get a warning from your compiler about dead code.)

There's no particular reason to use *pointers* to `std::string`. Just use `std::string` objects and values directly. That eliminates the need to use either `new` or `delete`.

If you did need to use pointers to `std::string`, you'd need to save the result of the comparison, then `delete` the pointer, then return the saved result.

BTW, this:

return condition ? true : false;

is better written as:

return condition;

Mr Z said...

If there was a case where they did need a pointer, std::unique_ptr would handle the cleanup nicely. This particular program is not one of those cases.

As you suggest, I would just use a straight std::string inside the function. I would also pass pstr1 as const std::string&, or std::string_view.

If you do that, you could just return pstr1 == pstr2;

How to Add a Directory to PATH in Linux

 https://linuxize.com/post/how-to-add-directory-to-path-in-linux/ When you type a command on the command line, you’re basically telling the ...