static objects or class attributes

N

newbix

Hi!

I have a class with a method that uses a container (vector). To avoid
frequent initialization of this container each time the method is
called I've declared this container as a class attribute.
Alternatively I could have declared this container as a static object
inside the method. What do you think, which solution is better:
attribute or static object?

Thank you in advance!

Example:
// attribute:
class A
{
std::vector v;

void do_something ()
{
// use v here
};
};

// static object:
class A
{
void do_something ()
{
static std::vector v;
// use v here
};
};
 
E

Erik Wikström

Hi!

I have a class with a method that uses a container (vector). To avoid
frequent initialization of this container each time the method is
called I've declared this container as a class attribute.
Alternatively I could have declared this container as a static object
inside the method. What do you think, which solution is better:
attribute or static object?

Unless there is some value in keeping the vector between calls of the
function you should not use either of them. This seems to be another
case of premature optimisation. Make the vector a local variable in the
function, if you then think your code is running to slow use a profiler
to see what needs to be changed.
 
M

Martin Vuille

(e-mail address removed) wrote in
ps.com:
Example:
// attribute:
class A
{
std::vector v;

void do_something ()
{
// use v here
};
};

Each instance of A gets its own v.
// static object:
class A
{
void do_something ()
{
static std::vector v;
// use v here
};
};

If I'm not mistaken, all instances of A share
the same v.

These are not equivalent.

MV
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,520
Latest member
KrisMacono

Latest Threads

Top