On Jun 19, 12:51 pm, SpreadTooThin <bjobrie...@gmail.comwrote:
I am developing a class. It's a pretty simple one.
The class has one data member which is a std::string.
If a class consists only of members that know how to take care of
their resources (e.g. std::string), you usually don't need to do
anything yourself.
The purpose of the class it simple to make sure that the string that
is used as a constructor has an even length.
The class is called a uid.
I'm a little confused.. should this just inherit from std::string ie
class uid:public std::string ?
No.
I'm not sure I'm handling the copy constructors properly.
You don't need to provide a copy constructor or a destructor in this
case.
class uid
{
private:
std::string id;
public:
uid(std::string _id)
{
id = _id;
if (id.size() & 1) // is the length odd?
id.append(" "); // yes. Now the length should be even
}
uid& operator=(std::string& _id)
Do you really have to assign a std::string? I don't think so, because
you can always assign from a uid, which is guaranteed to have 'id' of
even length.
{
id = _id;
if (id.size() & 1) // is the length odd?
id.append(" ");
}
uid& operator=(uid& _id)
You don't need to provide that assignment operator, because the
compiler generated one does the same thing:
{
id = _id;
}
Actually, the compiler generated one would do better by assigning even
the bases, if you had any.
On the other hand, the compiler generated one would not be exception
safe, if you had more than one object in this class. Because the C++
standard doesn't define the generated operator= be exception safe. It
is possible that the object is left in a half-assigned state if one of
the member assignments throws. But you don't have a second member
here.
~uid(void)
{
// Nothing to do really.
}
};
Start with the following simple class. I bet that works the way you
need:
#include <string>
class uid
{
std::string id;
public:
explicit uid(const std::string & _id)
:
id(_id)
{
if (id.size() & 1) // is the length odd?
id.append(" "); // yes. Now the length should be even
}
};
int main()
{
uid u("abc");
u = uid("xyz");
// Remove 'explicit' above to be able to compile the following as well
// std::string s("123");
// u = s;
}
Ali