如果您尝试使用进行调用,则永远不会调用第一个代码块中的方法(char *)0
。C ++只会尝试创建一个字符串,它将为您抛出异常。你试过了吗?
#include <cstdlib>
#include <iostream>
void myMethod(std::string s) {
std::cout << "s=" << s << "\n";
}
int main(int argc,char **argv) {
char *s = 0;
myMethod(s);
return(0);
}
$ g++ -g -o x x.cpp
$ lldb x
(lldb) run
Process 2137 launched: '/Users/simsong/x' (x86_64)
Process 2137 stopped
* thread #1: tid = 0x49b8, 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18
libsystem_c.dylib`strlen + 18:
-> 0x7fff99bf9812: pcmpeqb (%rdi), %xmm0
0x7fff99bf9816: pmovmskb %xmm0, %esi
0x7fff99bf981a: andq $15, %rcx
0x7fff99bf981e: orq $-1, %rax
(lldb) bt
* thread #1: tid = 0x49b8, 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18
frame #1: 0x000000010000077a x`main [inlined] std::__1::char_traits<char>::length(__s=0x0000000000000000) + 122 at string:644
frame #2: 0x000000010000075d x`main [inlined] std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(this=0x00007fff5fbff548, __s=0x0000000000000000) + 8 at string:1856
frame #3: 0x0000000100000755 x`main [inlined] std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(this=0x00007fff5fbff548, __s=0x0000000000000000) at string:1857
frame #4: 0x0000000100000755 x`main(argc=1, argv=0x00007fff5fbff5e0) + 85 at x.cpp:10
frame #5: 0x00007fff92ea25fd libdyld.dylib`start + 1
(lldb)
看到?你没有什么可担心的。
现在,如果您想更优雅地捕捉到这一点char *
,则只需不使用,就不会出现问题。
c_str
属性?