M
Marcin Vorbrodt
Hello dear fellows C++ coders!
I saw a discussion here before about static memebr functions and doing
singelton pattern. It was sugested that method like this was unsave (example
from my code):
class Vector {
Vector(float, float, float);
...
static const Vector UNIT_X(void);
};
const Vector Vector::UNIT_X(void) {
static const Vector unitX(1.0, 0.0, 0.0);
return unitX;
}
Instead, it was recomende by someone to do this:
const Vector Vector::UNIT_X(void) {
static const Vector *unitX = new Vector(1.0, 0.0, 0.0);
return *unitX;
}
Could some please explain exactly why that might be? Also, if the static
object is const, could I return by reference to the static object, like
this:
const Vector& Vector::UNIT_X(void) {
static const Vector *unitX = new Vector(1.0, 0.0, 0.0);
return *unitX;
}
This would be faster (no need for a temporary), but would it be safe to
return a reference? Or should I stick with returning a new copy each time?
Thanks a bunch!
Marcin
I saw a discussion here before about static memebr functions and doing
singelton pattern. It was sugested that method like this was unsave (example
from my code):
class Vector {
Vector(float, float, float);
...
static const Vector UNIT_X(void);
};
const Vector Vector::UNIT_X(void) {
static const Vector unitX(1.0, 0.0, 0.0);
return unitX;
}
Instead, it was recomende by someone to do this:
const Vector Vector::UNIT_X(void) {
static const Vector *unitX = new Vector(1.0, 0.0, 0.0);
return *unitX;
}
Could some please explain exactly why that might be? Also, if the static
object is const, could I return by reference to the static object, like
this:
const Vector& Vector::UNIT_X(void) {
static const Vector *unitX = new Vector(1.0, 0.0, 0.0);
return *unitX;
}
This would be faster (no need for a temporary), but would it be safe to
return a reference? Or should I stick with returning a new copy each time?
Thanks a bunch!
Marcin