From b6f32a3ed0e46272b0a9943d671f5fa692cc3393 Mon Sep 17 00:00:00 2001 From: Robert Osfield Date: Thu, 13 Dec 2007 12:30:31 +0000 Subject: [PATCH] Added copy operator to ShapeAttribute to prevent problems when assigned them or use within a vector --- include/osgSim/ShapeAttribute | 9 ++++++- src/osgSim/ShapeAttribute.cpp | 45 +++++++++++++++++++++++++---------- 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/include/osgSim/ShapeAttribute b/include/osgSim/ShapeAttribute index 6bceb4ae1..231fcd2af 100644 --- a/include/osgSim/ShapeAttribute +++ b/include/osgSim/ShapeAttribute @@ -41,11 +41,15 @@ class OSGSIM_EXPORT ShapeAttribute ShapeAttribute(const char * name); ShapeAttribute(const char * name, int value); ShapeAttribute(const char * name, double value); + + /** Note, ShapeAttribute takes a copy of both name and value, the calling code should manage its own clean up of the original strings.*/ ShapeAttribute(const char * name, const char * value); + ShapeAttribute(const ShapeAttribute & sa); ~ShapeAttribute(); + ShapeAttribute& operator = (const ShapeAttribute& sa); const std::string & getName() const { return _name; } const Type getType() const { return _type; } @@ -59,6 +63,9 @@ class OSGSIM_EXPORT ShapeAttribute private: + + void free(); + void copy(const ShapeAttribute& sa); std::string _name; Type _type; @@ -67,7 +74,7 @@ class OSGSIM_EXPORT ShapeAttribute { int _integer; double _double; - char * _string; + char* _string; }; diff --git a/src/osgSim/ShapeAttribute.cpp b/src/osgSim/ShapeAttribute.cpp index 6cda0b1cc..9a21c6aca 100644 --- a/src/osgSim/ShapeAttribute.cpp +++ b/src/osgSim/ShapeAttribute.cpp @@ -50,10 +50,31 @@ ShapeAttribute::ShapeAttribute(const char * name, const char * value) : _string[str.size()] = 0; } -ShapeAttribute::ShapeAttribute(const ShapeAttribute & sa) : - _name(sa._name), - _type(sa._type) +ShapeAttribute::ShapeAttribute(const ShapeAttribute & sa) { + copy(sa); +} + + +ShapeAttribute::~ShapeAttribute() +{ + free(); +} + +void ShapeAttribute::free() +{ + if ((_type == STRING) && (_string)) + { + delete [] _string; + _string = 0; + } +} + +void ShapeAttribute::copy(const ShapeAttribute& sa) +{ + _name = sa._name; + _type = sa._type; + switch (_type) { case INTEGER: @@ -82,13 +103,16 @@ ShapeAttribute::ShapeAttribute(const ShapeAttribute & sa) : } } } - - -ShapeAttribute::~ShapeAttribute() -{ - if ((_type == STRING) && (_string)) delete [] _string; -} +ShapeAttribute& ShapeAttribute::operator = (const ShapeAttribute& sa) +{ + if (&sa == this) return *this; + + free(); + copy(sa); + + return *this; +} int ShapeAttribute::compare(const osgSim::ShapeAttribute& sa) const @@ -122,11 +146,8 @@ int ShapeAttribute::compare(const osgSim::ShapeAttribute& sa) const if (sa._integer<_integer) return 1; } } - return 0; } - - /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/