C/C++ Learning C++: New & Delete Functions

  • Thread starter Thread starter Silicon Waffle
  • Start date Start date
  • Tags Tags
    Delete
AI Thread Summary
The discussion centers on the use of new and delete in C++, highlighting issues related to memory management and exceptions. A user experiences exceptions when modifying a function that utilizes dynamic memory allocation, indicating potential problems with destructors and object initialization. There is a critique of teaching practices, suggesting that the concepts of new and delete should be considered advanced topics due to their complexity and the existence of safer alternatives in modern C++. The conversation also touches on the importance of understanding memory management in the context of standard library classes, which handle memory automatically. Overall, the thread emphasizes the need for a deeper understanding of C++ memory management practices, especially for beginners.
Silicon Waffle
Messages
160
Reaction score
203
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:
Technology news on Phys.org
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.)
 
Silicon Waffle said:
Yesterday I learned about new and delete in my teacher lecture.
<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>

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:
void func()
{
    //...
    sometype * boot=new sometype();
    // do something with boot
    string s=boot->getStr();
    delete boot;
    return s;
}
then I have an exception.
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.
And if I use a reference like this
PHP:
void func()
{
    //...
    sometype  boot;
    // do something with t
    string s=boot.getStr();
    return s;
}

I also have an exception as boot is empty.:nb)
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.
 
  • Like
Likes Silicon Waffle
What was your reason for changing the return type to void?
 
Integrand said:
What was your reason for changing the return type to void?
I edit my OP, it was typos.
 
D H said:
<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>
I think it has only one rule, use new then use delete, why should they be in advanced topics ?

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.

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

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.


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 ?
 
Silicon Waffle said:
I think it has only one rule, use new then use delete, why should they be in advanced topics ?
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:
    #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";
       } 
    }
I actually have *using namespace std;* at the top of the program source code.
Why do coders should never use that line in code ?
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.
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 ?

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.
 
  • Like
Likes Silicon Waffle
Back
Top