Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have my own class that represents a custom string class. I'm using VS2012RC. I have overloaded some operators of my class CustomString.

Here's some code:

CustomString::CustomString(string setstr)
{           
    str = setstr;
}

CustomString::operator const char *()
{   
    return (this->str.c_str());
}

CustomString &CustomString::operator = (char *setstr)
{
    str = setstr;
    return *this;
}

I can define my object and use it like this:

CustomString str = "Test string";

and i can print the result as:

printf(str);

printf((string)(str).c_str());

printf((string)(str).data());

printf("%s
",(string)(str).c_str());

printf("%s
",(string)(str).data());

And there is not any error.

But if i use it like this:

printf("%s
", str);

There is an exception in msvcr110d.dll (error in memory access)

Why printf(str) is ok, but printf("%s ",str) is not ok?

How can i modify my code to use printf("%s ",str) ?

...

After hours of googling, I found that explict cast (string), static_cast (str) and _str() method are add a null-terminated chars: '';

i've modified my code as:

printf("%s
",str + '');

and it's worked!

Is there any way to modify my custom constructor to add a null-terminated string and pass a correct value with null-terminated chars to get working the following code:

printf("%s
",str);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
689 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can't (at least not in a portable way). printf looks at the object passed as parameter and treats it as a %s, which is a char array. You run into undefined behavior. Also, the parameters passed to printf are, sort of say, type-less.

Why printf(str) is ok?

Because the first parameter is types, and is a const char*. The implicit cast is made via your operator. The rest of the parameters don't behave the same.

I'd use cout instead, and overload operator << (ostream&, const CustomString&).

Don't do this:

I said you can't, in a portable way. For a class like

class CustomString
{
   char* str;
   //...
};

that might work, because of how classes are represented in memory. But, again, it's still undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...