Fun with std::string::operator(char c)

I

itroot

Hello,
how can i make g++ show me warning when such implicit casting occurs?

#include <iostream>
#include <string>

int main() {
int x=10;
std::string s;
s=x; // int implicitly assigned to char, then called
std::string::eek:perator=(char)
}

This piece of code really surprise me, and i'cant found how i can make
g++ warn me.
I want warning on each "narrowing" conversion as char c=(int)(2), etc.
Thanks.
 
F

Francesco

Hello,
how can i make g++ show me warning when such implicit casting occurs?

#include <iostream>
#include <string>

int main() {
int x=10;
std::string s;
s=x; // int implicitly assigned to char, then called
std::string::eek:perator=(char)

}

This piece of code really surprise me, and i'cant found how i can make
g++ warn me.
I want warning on each "narrowing" conversion as char c=(int)(2), etc.
Thanks.

I've stomped on the same issue - and it surprised me just in the same
way.

I think you'll have to live with it, that's a standard, legal
conversion which is explicitly allowed to lose data, I don't think
there is any way to force a compiler warning - somebody else will
eventually correct this statement of mine, shall it be false.

Cheers,
Francesco
 
A

Alan Woodland

Francesco said:
I've stomped on the same issue - and it surprised me just in the same
way.

I think you'll have to live with it, that's a standard, legal
conversion which is explicitly allowed to lose data, I don't think
there is any way to force a compiler warning - somebody else will
eventually correct this statement of mine, shall it be false.

If it's for code that you're writing rather than STL or other 3rd party
code you can always do:

void f1(char c);
void f2(char& c);

int main() {
int x=10;
f1(x);
f2(x); // Will fail

return 0;
}

I can't think of a conforming way to make your example emit either an
error or warning though.

Alan
 
F

Francesco

Use -Wconversion:

    $ g++ -Wconversion test.cpp
    test.cpp: In function ‘int main()’:
    test.cpp:7: warning: conversion to ‘char’ from ‘int’ may
      alter its value

Seehttp://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

Heck, I've checked my compiler options before posting, and I didn't
find this option (checkboxes in the IDE). Actually, also typing it as
an additional option doesn't activate those warnings. Maybe it's due
to the fact that my gcc version is old - and minimal :-/

I shall recall good ol' Google, the next time.

Thanks for posting it.

Francesco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,270
Latest member
TopCryptoTwitterChannels_

Latest Threads

Top