I'm not yet an expert but I'm just wondering what is an extra cost of creating and using object during RUNTIME?
for example what is the difference between
int i;
and
class Foo {
int i;
};
Let just assume that Foo is NOT created using new here.
Printable View
I'm not yet an expert but I'm just wondering what is an extra cost of creating and using object during RUNTIME?
for example what is the difference between
int i;
and
class Foo {
int i;
};
Let just assume that Foo is NOT created using new here.
I would suppose there is zero hidden cost here. Of course, Foo could have a constructor that contains an infinite loop, so the cost would be infinite :)
The difference about would be that the first defines an integer (cost: 4 bytes of space, minimal cost during application load) whereas the second defines a type (cost: 0 bytes of space, no cost during application load).
I presume you meant to instantiate Foo, too.
No - but the Foo type itself doesn't need any storage. Only objects of it.
Ah yes,that made sense :)
Why not just make a program to test out the things that make you curious? If you are asking about the general cost of instanciating a class then you could say the cost would be similar to the cost of initializing a set of variables. Of course, ctors can be inlined or not. So the only additional cost would present itself in the form of the cost of branching to another function. I would say that you could safely call the cost "minimal" without any arguments from anyone.
I already use sizeof,so I know the answer.
I just want certainty as not to be surprised later on.....
beside posting in this forum,I got my got answer in 5 minutes :p
Yeah I agree with your point that if you are curious,you should try out and see for yourselves...
I would also like to point out that the exact behaviour here depends on the compiler. One can make assumptions and be reasonably sure to be right, but compilers are written by people, and people do things differently if they work in different groups. So what one compiler does with the code may not be what another compiler does.
That being said, I would say that there is little reason to believe that instantiation of an object that contains an integer, and "instantiation" of a basic integer would be different in any way.
--
Mats
But couldn't a dumb compiler (or maybe one with no optimizations enabled) create & call an empty constructor?
That's the purpose of my comment, yes - any decent compiler will realize that the constructor is comletely empty and thus not call it. But a really stupid compiler may not.
And of course, with optimization turned off, it is likely that such optimizations are not done (if you say no to optimization, then it would be WRONG by the compiler to optimize your code - however, it doesn't mean that the compiler will necessarily PESSIMISE your code - so if it may not generate an empty function as a constructor and call it if the constructor isn't even declared).
--
Mats