2

When a you declare a struct in a class method, how is the memory for that struct allocated? For example:

void Foo::Bar(void)
{
    struct timeval a;

    a.tv_sec = 1;
    a.tv_usec = 0;

    ...
}

Is a allocated on the stack like any other local data (int, double, etc.), or is a default constructor called and the memory allocated on the heap?

What about if the struct initialized as so: struct timeval a = {0, 0};?

Trying to decide if it is better to make the structure a class member or have it as a method local since the method gets called quite often and needs to be as fast as possible.

LordOphidian
  • 178
  • 9

2 Answers2

4

Is a allocated on the stack like any other local data (int, double, etc.), or is a default constructor called and the memory allocated on the heap?

It is allocated on local storage(stack).
An object will be created on Freestore(heap) only when any of the new versions of the operators(except maybe placement new) are used while creating it.
Also, your structure object does not persist beyond the scope of the function enclosing it. An Freestore(Heap) object would persist till you call delete on it explicitly.

Whenever you create an object of structure/class, an appropriate constructor(by matching parameter types) will be called for that structure/class. In your case you do not pass any arguments while creating the object hence the Default constructor will be called.

What about if the struct initialized as so: struct timeval a = {0, 0};

It is still allocated as an object with local storage.

Trying to decide if it is better to make the structure a class member or have it as a method local since the method gets called quite often and needs to be as fast as possible.

Creating Objects on local storage(stack) is faster than creating them on Freestore(Heap). Though,In your case you are not using the heap at all.

Actual profiling a sample code shall tell you which one(a local structure or a class Member) better suits your performance requirements.

However,Consider how the structure is related to your class before making it a member. Does it have an has a relationship to your class or it is just an utility structure. You should consider that design aspect too.

Also, there are several restrictions in what can be accessed inside an local structure or class so do bear that in mind too.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • The object is a utility structure, which is why I would like to make it a local. There isn't a `has a` relationship. Unfortunately, this is for an embedded platform, for which profiling tools are, for all intents and purposes, not available, so I can't run this through a profiler on my target. – LordOphidian Oct 25 '11 at 20:36
  • @LordOphidian: It makes to have it as an Local structure then. – Alok Save Oct 25 '11 at 20:37
1

In your example, the object is allocated on the stack and the default constructor is called.

Michael Price
  • 8,088
  • 1
  • 17
  • 24