Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

String manipulation and operator!

vishwadevvishwadev Member Posts: 4
Hello!,
I am a little stuck with this piece of code, can anyone help me please?
Actually I dont know how to implement the assignment operator and the overloaded operator.I am doing some basic string manipulation. Can you give me some tips and ideas please.

//file myString.h
#include
class myString
{
private:
char* theString;
int length;

public:
myString();
myString(char*);

~myString();


myString(const myString&);
myString(const char*);

//the assignment operator
myString& operator=(const myString&);
myString& operator=(const char*);

int getLength();

const char* GetString();

// == operator overloaded for string comparison
friend int operator==(const myString&, const myString&);
friend int operator==(const myString&, const char*);
};

Comments

  • stoberstober Member Posts: 9,765 ✭✭✭
    [b][red]This message was edited by stober at 2002-10-27 2:59:14[/red][/b][hr]
    This is how I would implement the assignment operator. It should give you some hints on how to implement the == operator.
    [code]
    myString& myString::operator =(const myString& string)
    {
    if(theString != NULL)
    {
    delete[] theString;
    theString = NULL;
    length = 0;
    }
    if(string.theString != NULL)
    {
    length = string.length;
    theString = new char[length+1];
    strcpy(theString,string.theString);
    }
    return *this;
    }
    [/code]




  • whoiewhoie Member Posts: 672
    : This is how I would implement the assignment operator. It should give you some hints on how to implement the == operator.
    : [code]
    : myString& myString::operator =(const myString& string)
    : {
    : if(theString != NULL)
    : {
    : delete[] theString;
    : theString = NULL;
    : length = 0;
    : }
    : if(string.theString != NULL)
    : {
    : length = string.length;
    : theString = new char[length+1];
    : strcpy(theString,string.theString);
    : }
    : return *this;
    : }
    : [/code]

    Yes, this is quite common, but it is also unsafe. If new throws std::bad_alloc, then you have effectively destroyed the initial object with no chance at recovery. Secondly, there is no check for self-assignment, and that is a Bad Thing. You have already deleted it before the copy...ouch!!

    The best approach utilizes an exception-safe and exception-neutral copy constructor for the assignment operator. That way, it's awfully simple:
    [code=ffffff]
    myString& myString::operator=(const myString& other)
    {
    myString temp(other); // invoke copy constructor
    swap(temp); // must have throw() specification
    return *this;
    }
    [/code]
    Note that this method does not need to worry about self-assignment. Another pleasant side-effect, is that the destructor for 'temp' takes care of cleaning up our old data. :)

    We are exception safe here, because we don't modify our current state until 'temp' has been constructed successfully. If not, the exception propagates back to the caller for handling, but we keep our old data. More on this later.

    Here is the basic framework for writing myString::swap():
    [code=ffffff]
    #include

    void myString::swap(myString& other) throw()
    {
    std::swap(length, other.length);
    std::swap(theString, other.theString);
    }
    [/code]
    By using std::swap, we guarantee that we aren't going to throw any exceptions, because std::swap can't. We are simply swapping a pointer, and an int.

    All that is left, is our copy constructor. The important parts here are that:

    1) It must be exception-safe, IOW it will work properly in the presence of exceptions.
    2) It must be exception-neutral, IOW it will propagate all exceptions back to the caller for handling.

    So here we go:
    [code=ffffff]
    #include

    myString::myString(const myString& other)
    : length(other.length),
    theString(new char[other.length])
    {
    copy(other.theString, other.theString + length, theString);
    }
    [/code]

    We are exception safe, because even if new throws std::bad_alloc, our object was never constructed and memory never allocated. Even if the default constructor for 'char' could throw, it would still be okay, because delete[] would have been called, and we have no leaks.

    We are exception neutral, because we don't catch anything (copy is only copying chars), so all exceptions are propagated up through the call chain.

    For more, check the C++ FAQ, third link in my signature. Or, try Herb Sutter's book [italic]Exceptional C++[/italic].


    HTH,
    Will
    --
    http://www.tuxedo.org/~esr/faqs/smart-questions.html
    http://www.eskimo.com/~scs/C-faq/top.html
    http://www.parashift.com/c++-faq-lite/
    http://www.accu.org/


  • stoberstober Member Posts: 9,765 ✭✭✭
    I think that goes way beyond the original poster's question, knowledge and experience. Since he does not mention std::string and exception handling, I imagine he is just learning about char pointers, so std::string is out of the question here, even though it would be a better choice in the real world.
  • whoiewhoie Member Posts: 672
    : I think that goes way beyond the original poster's question, knowledge and experience.

    It might very well be. However, it isn't too hard to figure out what 'swap' and 'copy' means. Likewise, learning anything new is beyond knowledge and experience, but that doesn't mean it shouldn't be taught and learned. That's the whole freakin' point. Part of the OP's question was about writing the assignment operator for his string class, so I think it was well within the question. It isn't like I left the OP hanging, that was the entire reason for pointing out the FAQ, and another reference.


    : Since he does not mention std::string and exception handling, I imagine he is just learning about char pointers, so std::string is out of the question here, even though it would be a better choice in the real world.

    Okay, let's count the occurences of std::string in my post...0(zero). Exception handling comes in everytime you have the possibility for an exception, i.e. operator new. If you ask me, those 3 functions are much simpler than your implementation, and don't have landmines waiting to blow you apart. I have never understood this line of thinking, if you are going to learn something, learn it the right way first. Don't learn bad habits just to unlearn them when you get to the "real world". Is C++ hard? Absolutely. Does that mean babysit and protect newcomers from "dirty exceptions"? IMO, no. Face it up front, and learn how to deal with them. It really isn't too hard, but it is new (pun not intended).

    I have been accused of repeatedly, and I am sure that it is probably quite correct. I don't think that is an excuse for not pointing it out. I would much prefer it if we could all agree to direct questions like these to the FAQ's. That's what they are for.


    Will
    --
    http://www.tuxedo.org/~esr/faqs/smart-questions.html
    http://www.eskimo.com/~scs/C-faq/top.html
    http://www.parashift.com/c++-faq-lite/
    http://www.accu.org/


  • stoberstober Member Posts: 9,765 ✭✭✭
    Re-reading your post I see you are correct, you did not mention std::string, but STL instead. Well, unless you are a college professor or current student, neither you nor I know what is being taught in his class nor whether or not he even knows what STL is. I do not doubt you presented a much better implementation. My only concern is that it is beyond his current understanding of the language. For example, when you were learning algebra did your teacher or tutors throw in a bunch of calculas? If he wanted and STL implementation then he would surely have put that in his question.
  • whoiewhoie Member Posts: 672
    : Re-reading your post I see you are correct, you did not mention std::string, but STL instead. Well, unless you are a college professor or current student, neither you nor I know what is being taught in his class nor whether or not he even knows what STL is.

    True, I don't know what is being taught in his class, and I really don't care either. Even an intellectually challenged individual should be able to figure out what 'swap' and 'copy' do. Give them some credit.


    : I do not doubt you presented a much better implementation. My only concern is that it is beyond his current understanding of the language. For example, when you were learning algebra did your teacher or tutors throw in a bunch of calculas? If he wanted and STL implementation then he would surely have put that in his question.

    Perhaps the reasons for writing the code that way are a little beyond their grasp, but that is fine with me. They can always post their questions here after checking out the sources I posted, and reading their text. This is an issue that every C++ programmer needs to be aware of, and what better place to introduce it than here? These boards aren't just for students to get help with homework, it's for everyone to learn a little more. I'm sorry that no one had pointed these things out to you before, but now you know. That's win-win! :)


    HTH,
    Will
    --
    http://www.tuxedo.org/~esr/faqs/smart-questions.html
    http://www.eskimo.com/~scs/C-faq/top.html
    http://www.parashift.com/c++-faq-lite/
    http://www.accu.org/


  • vishwadevvishwadev Member Posts: 4
    Hi

    I would like to thank you all for your help. i would very much like to be a good C++ programmer so we are already learning about most of what has been posted here but there some parts that made me check in my books.

    Thanks again!
  • Justin BibJustin Bib USAMember Posts: 0

    __ | http://forcoder.org | free video tutorials and ebooks about // C++ C# Assembly R Visual Basic JavaScript PHP Java MATLAB Visual Basic .NET Perl C PL/SQL Ruby Scratch Delphi Swift Go Python Objective-C FoxPro VBScript Lisp Transact-SQL F# Rust ML Hack Kotlin Bash Crystal COBOL Scala Prolog ABAP Scheme Logo Fortran Awk SAS Alice Ada Erlang D Lua Dart Julia Clojure LabVIEW Apex // ___________

Sign In or Register to comment.