Reputation: 162
I am new in C++ and now I am learning how cin and cout works. The case is, as you can see in the code below I create a string
, and a char *
in order to compare the C way to read a string and the C++ way. In C++, it makes sense that if I create a string then I worry about to set this string to NULL?
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#define SIZE 10
using namespace std;
int main () {
cout << "Write Something: \n";
string f1;
char *p;
p = (char *) malloc(SIZE); // This is how I will use it in c
getline(cin, f1);
cout << "Write Something else: \n";
scanf("%s", p);
cout << f1 << "1\t";
printf("%s2\n", p);
free(p);
p = NULL; // After the pointer has been freed, we set it to NULL
cout << "p freed\t";
f1.clear();
cout << "f1 deleted\t";
return 0;
}
Upvotes: 0
Views: 223
Reputation: 3583
No, you don't have to even clear f1, as the RAII will automatically cleanup, when the function returns.
Upvotes: 1
Reputation: 597941
You don't have to worry about setting a std::string
object to NULL.
And you don't have to clear()
it if it is just going to go out of scope right afterwards. Its destructor will handle freeing any memory used for the character data for you.
Upvotes: 2