2

I'm having problem with getting the value of class member after assigning like that:

bool ModeData::setPasswd(char* _pass)
{
    return (this->setString(this->passwd_, _pass) ? true : false);
}

bool ModeData::setOutput(char* _out)
{
    return (this->setString(this->output_, _out) ? true : false);
}

where setString is like that:

bool ModeData::setString(char* _toStr, char* _fromStr)
{
    // check if already exists and delete
    this->delIfPresent(_toStr);

    // allocate space for the new string
    _toStr = new char[strlen(_fromStr) + 1];

    // copy new string
    if(strcpy(_toStr, _fromStr))
    {
        return true;
    }

    // if something gone wrong return 'false'
    return false;
}

and then if I want to print the value of this->passwd_, I get nothing. I think the pointers are lost somewhere when passing through methods, but I'm not sure.

4

1 回答 1

3

You should pass your pointers by ref... No, NO! Wait a moment. You should not use pointers, you should use std::string instead! That will make your life so much easier.

This said, if you really want to use pointers, then the problem is that you are passing them by value. The changes done to those pointers (in particular, the assignment in _toStr = new char[strlen(_fromStr) + 1];) won't be visible to the caller once the function returns - and as a side effect, your program is leaking memory.

To fix this, pass your pointers by reference:

    bool ModeData::setString(char*& _toStr, char*& _fromStr)
//                                ^              ^

And don't forget to delete[] arrays allocated with new[], or you will have a memory leak. But let me give you that advice once more: use std::string instead of doing manual memory management through raw pointers.

于 2013-03-30T17:27:52.380 回答