2012-09-20 133 views
4
#define LOG(format,...) Logger::Log(format,__VA_ARGS__) 
#define STRIP(netIp) GeneralUtils::inet_ntop_(netIp) 
string GeneralUtils::inet_ntop_(unsigned int netIp){ 
    char strIP[INET_ADDRSTRLEN]; 
    in_addr sin_addr; 
    sin_addr.s_addr = netIp; 
    inet_ntop(AF_INET, &sin_addr.s_addr, strIP, sizeof strIP); 
    return string(strIP); 
} 

打电话来时:C++传递字符串可变参数

LOG("src %s dst %s" ,STRIP(src_ip_)); 

我得到的编译错误:

cannot pass objects of non-trivially-copyable type ‘std::string {aka struct std::basic_string<char>}’ through ‘...’ 

据我所知,可变参数为c兼容,所以我不能发送字符串给它。 有没有简单的方法来绕过它? 会不会是正确的解决这样的:

#define STRIP(netIp) GeneralUtils::inet_ntop_(netIp).data() 
+1

而不是在'STRIP'宏中使用'data'(或'c_str'),你可以在LOG调用中使用它:LOG(“src%s dst%s”,STRIP(src_ip_))。 '# –

+1

@Joachim Pileborg我preffer修复一个地方,并不是所有的这个调用放到LOG –

回答

4
#define STRIP(netIp) GeneralUtils::inet_ntop_(netIp).data() 

错误,它会调用未定义的行为,因为它不包括终止零。使用

#define STRIP(netIp) GeneralUtils::inet_ntop_(netIp).c_str() 

改为。

+0

你能解释'未定义的行为'吗?当我改变为inet_ntop_(netIp).data() –

+2

@ user1495181时,我没有遇到任何问题'%s'格式说明符预期为零终止的C字符串。 'std :: string.data()'返回一个非零终止的C字符串,***会在某天崩溃,这就是为什么你必须使用'c_str()'。 – 2012-09-20 16:18:33

+0

我的代码充满格式%s和data()作为返回,我从来没有崩溃在此。你能解释一下我会在哪些情况下崩溃。 –

5

您可以通过const char *而不是std::string。你可以把它从std::string通过调用c_str()

+0

这样所有的日志调用都需要一个丑陋的.c_str()。我认为最好在一个地方定义这个 –

相关问题