Reputation: 13
i'm new to c++ (coming from java) and i'm actually struggeling with the following: Let foo be a class
int bar[10] = {};
Foo::Foo()
{
bar[1] = 42;
}
and doSmth() a method in the main class:
Foo doSmth(){
Foo f;
f.bar[0] = 10;
return f;
}
the main will be something like:
int main(int argc, char *argv[])
{
Foo f = doSmth();
cout << f.bar[1] << endl;
cout << f.bar[0] << endl;
return 0;
}
Is this the right way to return the foo
-object in doSmth()
?
I want to create the object on stack, but I'm worried about the array (bar)
from the foo object, when will it be deleted from stack?
Upvotes: 0
Views: 63
Reputation: 38919
foo
object in doSmth()
?Yes, objects created locally must be returned by value. Typically the compiler will create the object in place and the copy will be optimized out. You can read more about returning local objects here: https://isocpp.org/wiki/faq/ctors#return-local-var-by-value-optimization
bar
from the foo
object, when will it be deleted from stack?As mentioned above, because of return value optimization the compiler will typically not even create this object within doSmith
's stack frame. Furthermore, even if it was created in doSmith
's stack frame, the behavior of the default copy constructor and the default assignment operator is such that:
If the subobject is an array, each element is assigned, in the manner appropriate to the element type
See 15.8.1[class.copy.ctor]14.1 and 15.8.2[class.copy.assign]12.2
Upvotes: 0
Reputation: 238311
Is this the right way to return the foo object in doSmth()?
It sure is.
I want to create the object on stack
You have.
but i'm worried about the array (bar) from the foo object
bar
is not "from foo
". bar
is a global static object.
f.bar[1]
This is ill formed, since bar
is not a member of Foo
. To declare a member, it has to be inside the definition of the class:
struct Foo {
int bar[10] = {};
};
when will it be deleted from stack?
If bar
has static storage, such as in your code, then it is destroyed at the end of the program. If it is a (non static) member, then it is destroyed when its complete object is destroyed i.e. the instance of Foo
that contains it.
Upvotes: 2
Reputation: 35154
If bar
is a non-static data member of your class Foo
, then the bar
-content of a foo
-object will be part of the foo
-object; it will reside where foo
resides (on the stack, on the heap, ...) and it will be created and destroyed once foo
gets created or destroyed.
If bar
is a static data member, then it will exist once in your complete program and will "live" until the program finishes.
Upvotes: 0