0

I'm a Java programmer, I'm new to C++ and recently I've been writing some C++ code. I'm a bit confused by C++ objects' lifetime (in Java there is garbage collection and I don't have to worry about this issue).

Here is my question. Suppose I have a function f()

char *f() {

  string a = "Hello";

  return a.c_str();

}

Is this code valid? What confuses me is: what is the lifetime of the string a declared inside of f, will it be garbage-collected when f returns? Can I rely on the returned a.c_str() to be correct outside f?

zanyman
  • 667
  • 2
  • 11
  • 22
  • There is no garbage collection in C++. – Baum mit Augen Feb 14 '17 at 05:12
  • *Can I rely on the returning a.c_str() to be correct outside f?* No. – R Sahu Feb 14 '17 at 05:12
  • There's really no need to use the C-style `char*`. Your problem completely disappears if you simply return `std::string`, which properly manages its contents. If you reaaaally need to pass a `char*` to something, use `c_str` as close to it as possible. And by the way, `c_str` gives you a `const char*`, so trying to ignore the constness of it doesn't work well. – chris Feb 14 '17 at 05:21
  • You can allocate the "Hello" char array on the heap and return a shared_ptr. Or better, return a std::string by value. – Erik Alapää Feb 14 '17 at 12:16

1 Answers1

-2

C++ has not the garbage grabber, like java. If you create an object then you need to destroy it by self. All variables defined in function will destroyed on exit from this function (except objects, which you need to destroy by yourself)

user3811082
  • 218
  • 1
  • 7
  • *"except objects, which you need to destroy by yourself"* That does not make sense and is not right. – Baum mit Augen Feb 14 '17 at 05:23
  • Why? object* o = new object(); should i forget about this object? – user3811082 Feb 14 '17 at 06:12
  • `int i;` Now `i` is an object too. Your terminology is completely off. – Baum mit Augen Feb 14 '17 at 20:15
  • i is a variable, not an object. You should not delete it, but if you write int* i = new int; you should delete i before you exit from function. – user3811082 Feb 16 '17 at 08:59
  • In Java variables like Integer or String or Double are objects, cause they have methods. But if you write Integer i = new Integer(1) you should not delete it like in c++ – user3811082 Feb 16 '17 at 09:09
  • Variables are objects too. Also, the decision between creating an object with `new` (or some equivalent) or as an automatic object is entirely orthogonal to whether it is of class type or some built-in type. C++ is not Java. – Baum mit Augen Feb 16 '17 at 16:39
  • That is what i wrote from the beginning. C++ free the variables when you leave a function. If you want to use variables, objects outside function you should create them by self. And then delete them by yourself. – user3811082 Feb 17 '17 at 13:12