Learning C++: New & Delete Functions

  • C/C++
  • Thread starter Silicon Waffle
  • Start date
  • Tags
    Delete
In summary, the function compiles but throws an exception when you try to delete the object that was created with new.
  • #1
Silicon Waffle
160
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
  • #2
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.)
 
  • #3
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
  • #4
What was your reason for changing the return type to void?
 
  • #5
Integrand said:
What was your reason for changing the return type to void?
I edit my OP, it was typos.
 
  • #6
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 ?
 
  • #7
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

Related to Learning C++: New & Delete Functions

1. What are the new and delete functions in C++?

The new and delete functions in C++ are used for dynamic memory allocation. The new function is used to allocate memory for a single object, while the delete function is used to deallocate memory that was previously allocated with the new function.

2. How do I use the new and delete functions in my code?

To use the new and delete functions, you need to first declare a pointer variable of the desired data type. Then, use the new function to allocate memory for the object and assign the address of the allocated memory to the pointer variable. Finally, use the delete function to deallocate the memory when it is no longer needed.

3. What is the difference between new and malloc in C++?

The new function is used for dynamic memory allocation in C++ while the malloc function is used in C. The new function also calls the constructor for the allocated object, while malloc only allocates memory without calling any constructors.

4. Can I use new and delete to allocate and deallocate arrays?

Yes, the new and delete functions can be used to allocate and deallocate arrays in C++. To allocate an array, use the new[] function and to deallocate, use the delete[] function.

5. Do I need to check for null pointers when using new and delete?

It is always a good practice to check for null pointers when using new and delete functions, especially when allocating memory for large data structures. This can help prevent any potential errors or crashes in your code.

Similar threads

  • Programming and Computer Science
Replies
8
Views
3K
  • Programming and Computer Science
Replies
11
Views
1K
  • Programming and Computer Science
4
Replies
118
Views
7K
  • Programming and Computer Science
Replies
14
Views
2K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
6
Views
1K
  • Programming and Computer Science
Replies
2
Views
998
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Programming and Computer Science
Replies
6
Views
1K
Back
Top