Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"operator char*" issue

Tags:

c++

Below code expected to print "kevin" But, it's printing garbage value. I have checked in debugger. The pointer returned by "operator char*" call is invalid. Any idea?

class Wrapper
{
private:
    char* _data;

public:

    Wrapper(const char* input)
    {
        int length = strlen(input) + 1;
        _data = new char[length];
        strcpy_s(_data, length, input);
    }

    ~Wrapper()
    {
        delete[] _data;
    }

    operator char*()
    {
        return _data;
    }
};

int main()
{
    char* username = Wrapper("kevin");
    printf(username);
    return 0;
}
like image 908
Nepz Solutions Avatar asked Aug 11 '10 19:08

Nepz Solutions


1 Answers

The problem is that your Wrapper object is being constructed as a temporary and immediately destroyed. Through the operator char* you're returning a pointer to memory that has been deleted by the Wrapper object when it was destroyed.

To make it work:

Wrapper wrapper("Kevin");
char* username = wrapper;
like image 79
bshields Avatar answered Nov 08 '22 10:11

bshields