A
Axel Bock
Hi all,
I am trying to get my head around what happens if I return a class
object from a function.
It seems C++ (MinGW) does not invoke the copy constructor if I do
something like this:
SomeObj foo()
{
SomeObj X;
// ....
return X;
}
BUT it does create a new object every time the function is invoked, and
it does seem like these objects are usable (I created a little test
program checking this .
So basically I can go in main:
int main()
{
// ....
SomeObj bar = foo();
SomeObj bar2 = foo();
// for some strange reason the next thing will fail, though:
SomeObj &bar3 = foo();
}
and I will get two different objects back, both valid. (As commented,
the third will fail with some obscure warning about temporary objects -
but there's no copying taking place, so there's no temp object, AFAIK).
Hm.
So I checked something else:
void foobar()
{
SomeObj IamUseless;
}
That object is actually constructed, but destroyed after the function.
Now I am a bit unsure how the C++ compiler can determine EACH TIME
which object gets returned (maybe in the depth of an STL container of
whatever), and which one does NOT, so this has to be destroyed.
Usually I use new() for factories, but I wondered, and I checked. And I
don't get it . So maybe there's a guru in here who can help me out
with some background information?
Cheers & thanks,
Axel.
I am trying to get my head around what happens if I return a class
object from a function.
It seems C++ (MinGW) does not invoke the copy constructor if I do
something like this:
SomeObj foo()
{
SomeObj X;
// ....
return X;
}
BUT it does create a new object every time the function is invoked, and
it does seem like these objects are usable (I created a little test
program checking this .
So basically I can go in main:
int main()
{
// ....
SomeObj bar = foo();
SomeObj bar2 = foo();
// for some strange reason the next thing will fail, though:
SomeObj &bar3 = foo();
}
and I will get two different objects back, both valid. (As commented,
the third will fail with some obscure warning about temporary objects -
but there's no copying taking place, so there's no temp object, AFAIK).
Hm.
So I checked something else:
void foobar()
{
SomeObj IamUseless;
}
That object is actually constructed, but destroyed after the function.
Now I am a bit unsure how the C++ compiler can determine EACH TIME
which object gets returned (maybe in the depth of an STL container of
whatever), and which one does NOT, so this has to be destroyed.
Usually I use new() for factories, but I wondered, and I checked. And I
don't get it . So maybe there's a guru in here who can help me out
with some background information?
Cheers & thanks,
Axel.