|
-
June 19th, 2008, 02:55 PM
#1
Rule of 3 for a simple class...
I am developing a class. It's a pretty simple one.
The class has one data member which is a std::string.
The purpose of the class is simply to make sure that the string ends up having 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 ?
I'm not sure I'm handling the copy constructors properly.
Code:
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) // Is this method necessary?
{
id = _id;
if (id.size() & 1) // is the length odd?
id.append(" ");
}
uid& operator=(uid& _id)
{
id = _id;
}
~uid(void)
{
// Nothing to do really.
}
int getSize(void)
{
return id.size();
}
const void *getData(void)
{
return id.c_str();
}
};
Last edited by JustSomeGuy; June 19th, 2008 at 03:06 PM.
-
June 19th, 2008, 02:59 PM
#2
Re: Rule of 3 for a simple class...
The rule of three does not apply here since the compiler generated copy constructor, copy assignment operator and destructor will suffice. All you need is a constructor that takes a string argument and applies the check for an even length.
-
June 19th, 2008, 03:10 PM
#3
Re: Rule of 3 for a simple class...
what exactly is the rule of three? I can't google a satisfying explanation ;-)
-
June 19th, 2008, 03:16 PM
#4
Re: Rule of 3 for a simple class...
Yes I guess your right..
As none of the properties are pointers to data....
Right?
-
June 19th, 2008, 03:20 PM
#5
Re: Rule of 3 for a simple class...
what exactly is the rule of three?
If you define the copy constructor, copy assignment operator, or destructor, you probably have to define all three to be correct. Of course, there are exceptions, e.g., if you merely define the destructor so as to declare it virtual for a polymorphic base class.
Yes I guess your right..
As none of the properties are pointers to data....
Right?
Yes, and neither do you have reference or const members.
-
June 19th, 2008, 03:22 PM
#6
Re: Rule of 3 for a simple class...
 Originally Posted by Richard.J
what exactly is the rule of three? I can't google a satisfying explanation ;-)
If any one of the compiler-generated destructor, copy constructor or copy assignment operator are inappropriate for a class, then it is likely that all three will compiler-generated functions will be inappropriate. The writer of the class would then be required to write their own or disable them.
Note that in modern C++ with the use of other classes that manage resources themselves it is less likely that the rule of three will apply to a well-written class.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|