Learning C++: New & Delete Functions

  • Context: C/C++ 
  • Thread starter Thread starter Silicon Waffle
  • Start date Start date
  • Tags Tags
    Delete
Click For Summary

Discussion Overview

The discussion revolves around the use of new and delete functions in C++, focusing on memory management, exceptions, and the implications of using these keywords in modern programming practices. Participants explore various implementations of a function that utilizes dynamic memory allocation and the resulting behaviors, including exceptions and memory leaks.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Conceptual clarification

Main Points Raised

  • One participant describes a function that allocates memory using new and encounters exceptions when attempting to delete the allocated memory.
  • Another participant questions the definition of the type sometype and suggests that the destructor may throw an exception, indicating a potential issue with memory management.
  • Some participants express concerns about teaching new and delete as basic topics, arguing they should be considered advanced due to the complexities involved in memory management and exception safety.
  • A participant mentions that using "using namespace std;" can lead to name collisions and is generally discouraged, particularly in header files.
  • There is a discussion about the behavior of standard library classes managing memory automatically, which contrasts with manual memory management using new and delete.
  • One participant reflects on a code example provided by a teacher that does not include a delete statement after new, speculating that the standard library may handle memory cleanup internally.

Areas of Agreement / Disagreement

Participants express differing views on the appropriateness of teaching new and delete as basic topics, with some advocating for their classification as advanced due to the complexities involved. There is no consensus on the best practices for memory management in C++ or the implications of using certain coding conventions.

Contextual Notes

Some participants highlight the importance of understanding RAII (Resource Acquisition Is Initialization) and exception safety, which may not be familiar to introductory level students. The discussion also touches on the potential for undefined behavior when dealing with memory that has been deleted.

Silicon Waffle
Messages
160
Reaction score
202
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   Reactions: 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");
    count.imbue(locale(count.getloc(), facet));
    count << 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::count << 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");
    count.imbue(locale(count.getloc(), facet));
    count << 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   Reactions: Silicon Waffle

Similar threads

  • · Replies 8 ·
Replies
8
Views
4K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 118 ·
4
Replies
118
Views
10K
  • · Replies 14 ·
Replies
14
Views
3K
  • · Replies 8 ·
Replies
8
Views
5K
  • · Replies 6 ·
Replies
6
Views
1K
Replies
89
Views
7K
Replies
6
Views
2K
Replies
2
Views
1K
  • · Replies 31 ·
2
Replies
31
Views
3K