为什么不提供std:string + int给出编译错误?
-
12-10-2019 - |
题
我们刚刚发现我们的同事认为他可以为STD :: string添加一个整数,并在他的代码中在这里和那里使用此类操作。
我们没有看到此操作的任何编译器错误,我不明白为什么:没有 operator+ (const string& lhs, int rhs);
. 。 int默默地铸造给char吗? (用GCC红色帽子4.1.2和-Wall开关编译)。
而且,最重要的是,我们如何找到添加到std :: string的所有行?
解决方案
当您的同事仅使用整数文字时,这些将转换为 char
- 但是,如果整数的价值太大,您将看到警告。被调用的操作员是
std::string operator+(const std::string &s, char c); // actually it's basic_string<> with some CharT...
或者 +=
变体;)
关于如何找到所有电话。您可以编译(w/o插入)所有代码, objdump
它, grep
对于所有操作员出现并使用 addr2line
在过滤后的地址:
$ cat string-plus.cpp
#include <string>
int main()
{
std::string a = "moof ";
a += 192371;
}
$ g++ -g string-plus.cpp
string-plus.cpp: In function ‘int main()’:
string-plus.cpp:5: warning: overflow in implicit constant conversion
$ objdump -Cd a.out | \
grep 'call.*std::string::operator+=(char)@plt' | \
tr -d ' ' | \
cut -d: -f1 | \
xargs addr2line -Cfe string-plus
main
??:0
但是,这没有给我行号...至少呼叫网站在那里;)
这 -C
开关启用C ++名称删除。也可以用binutls手动完成 c++filt
.
有趣的是,那里 是 一个定义 operator+
为了 string
和 char
, ,但仅在使用时 operator+=
整数文字被转换为 char
, ,我必须通过 char
文字(或价值) operator+
要使用的。
查找操作员的打磨名称:
$ cat a.cpp
#include <string>
int main()
{
std::string a = "moof ";
a = a + char(1);
}
$ g++ a.cpp
$ objdump -t a.out | c++filt | grep operator+ | cut -d ' ' -f1
08048780
$ objdump -t a.out | grep 0804878
08048780 w F .text 00000067 _ZStplIcSt11char_traitsIcESaIcEESbIT_T0_T1_ERKS6_S3_
最后一个是您要搜索的名称 - 可以用来删除名称。
我真的不知道这样做的更好的方法...:/
不隶属于 StackOverflow