Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[C++] new and delete

  1. Jun 16, 2015 #1
    Yesterday I learned about new and delete in my teacher lecture.

    I have a function that looks like this
    PHP:

    string func()
    {
        //...
        sometype * boot=new sometype();
        // do something with boot
        string s=boot->getStr();
        return s;
    }
    The function works

    but if I rewrite it as
    PHP:
    string func()
    {
        //...
        sometype * boot=new sometype();
        // do something with boot
        string s=boot->getStr();
        delete boot;
        return s;
    }
    then I have an exception. And if I use a reference like this
    PHP:

    string func()
    {
        //...
        sometype  boot;
        // do something with t
        string s=boot.getStr();
        return s;
    }
    I also have an exception as boot is empty.:nb)
     
    Last edited: Jun 16, 2015
  2. jcsd
  3. Jun 16, 2015 #2

    wle

    User Avatar

    How is "sometype" defined? What the second and third versions of your function have in common is that sometype's destructor is called (when you use delete in version 2 and when func returns in version 3), which can throw an exception.

    (The first version of your function looks like it has a different bug -- a memory leak -- since you allocate memory but never release it. Run for (;;) { func(); } and watch your computer grind to a halt as its memory fills up.)
     
  4. Jun 16, 2015 #3

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    <begin gripe>
    This is 2015, four years after C++11 (and one year after C++14) was officially released. Why are teachers still teaching that arcane stuff? There are free compilers for C++98/03, C++11, and C++14. Nowadays, the keywords new and delete should be taught as advanced topics.
    <end gripe>

    That depends entirely on how string is defined, which you haven't shown. If you are using a modern (C++98/03 or later) compiler and if you are using using namespace std; (aside: never do that), there is no problem.

    On the other hand, if your string is something very different from std::string, you potentially have much worse than an "exception". You might well have "undefined behavior". Referring to memory that has been deleted is quintessential undefined behavior.


    You haven't shown us what sometype is. Since it has a member function getStr, it is not a primitive type. Therefore sometype boot; is not "empty". Instead, boot is initialized with the default constructor for class sometype.
     
  5. Jun 16, 2015 #4
    What was your reason for changing the return type to void?
     
  6. Jun 16, 2015 #5
    I edit my OP, it was typos.
     
  7. Jun 16, 2015 #6
    I think it has only one rule, use new then use delete, why should they be in advanced topics ?

    I actually have *using namespace std;* at the top of the program source code.
    Why do coders should never use that line in code ?

    For example, my teacher yesterdays showed us this code piece and I wonder why there isn't any delete after new.
    PHP:

    usingnamespace std;
    int main(int argc,char**argv){
        time_facet *facet =new time_facet("%d-%b-%Y %H:%M:%S");
        cout.imbue(locale(cout.getloc(), facet));
        cout << second_clock::local_time()<< endl; return 0;
    }
    I now think the locale() ate it up. After that, it frees facet internally and secretly. but things like this are good to learn at all ?
     
  8. Jun 16, 2015 #7

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    In modern C++, the only place you should be using new and delete in your own code is if you are creating a low-level RAII class. Knowing how to do that correctly can be non-trivial. Knowing how to do that correctly and to provide some minimal level of exception safety can be highly non-trivial. Introductory level students don't know what RAII and exception safety mean, nor should they need to know that stuff.

    Behind the scenes, there's a good amount of allocated memory with many of the standard library classes. The nice thing: You as a user of those classes don't need to know about that. Just declare a variable as a type of one of those standard library classes and the behind-the-scences memory is automagically deleted when the variable goes out of scope.

    For example,
    Code (C):

        #include <list>
        #include <iostream>
        int main ()
        {
           std::list<int> integer_list;
           integer_list.push_back (42);
           integer_list.push_front (0);
           for (auto elem : integer_list)
           {
              std::cout << elem << "\n";
           }
        }
     

    It's extremely bad in a header file. In a source file, it's just bad (but not extremely bad).

    The primary purpose of having namespaces is to protect against the name collision problem that plagues the C language. Using using namespace xxx; undermines that protection. Using using namespace std; is particularly bad because there are so very many common names in namespace std.


    Things like this are things you should learn well after you learn the basics. You need to understand reference-counted pointers to understand how facets work. That's advanced stuff.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook