字符串引用未在C ++中的函数调用中更新
我正在写一个arduino库来在网上发布http请求。
我正在使用http://arduino.cc/en/Tutorial/TextString中的String类
当我在函数调用后引用我定义的字符串对象时,我的代码表现得很奇怪。
实际上,我试图获取我的GET请求的主体并从http GET请求的响应中删除http标头。
以下是描述:
方法调用:
String body; if(pinger.Get(host,path,&body)) { Serial.println("Modified String Outside :"); Serial.println(body); Serial.println(); Serial.println("Modified String Outside Address"); Serial.println((int)&body); }
产量
Modified String Outside : HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/html Content-Length: 113 Date: Wed, 13 Jan 2010 14:36:28 GMT Ashish Sharma Wed Jan 13 20:06:28 IST 2010 Modified String Outside Address 2273
方法描述:
bool Pinger::Get(String host, String path, String *response) { bool connection = false; bool status = false; String post1 = "GET "; post1 = post1.append(path); post1 = post1.append(" HTTP/1.1"); String host1 = "Host: "; host1 = host1.append(host); for (int i = 0; i append((char) c); if (c == 0x000A && nlCnt == 0) { nlCnt++; if (response->contains("200")) { status = true; continue; } else { client.stop(); client.flush(); break; } } } if (!client.connected()) { client.stop(); connection = false; } } response = &response->substring(response->indexOf("\n\r\n"),response->length()); Serial.println("Modified String: "); Serial.println(*response); Serial.println(); Serial.print("Modified String Address: "); Serial.println((int)&response); return status; }
输出:
Modified String: Ø Ashish Sharma Wed Jan 13 20:06:28 IST 2010 Modified String Address: 2259
从示例中可以看出,字符串引用对象在Get方法中给出了正确的字符串,但是当Get方法返回时,字符串内容的引用会发生变化。
如果我理解你的代码,你可能会想做这样的事情:
*response = response->substring(response->indexOf("\n\r\n"),response->length());
代替
response = &response->substring(response->indexOf("\n\r\n"),response->length());
也可能没有必要传入指针(引用可能会使代码看起来更好)。
首先,您正在修改字符串的地址 ,而不是字符串本身。 但是字符串的地址是按值传递给函数的 ,因此被复制了。 在函数内部修改它不会在外部修改它。
其次,这里的代码很糟糕:
response = &response->substring(response->indexOf("\n\r\n"),response->length());
因为它创建了一个指向临时对象的指针 – 这意味着:悬空指针,因为临时对象将在计算表达式后被销毁。
你真正想要的是通过引用传递对象( String& response
)并修改它,而不是它的指针:
response = response->substring(response->indexOf("\n\r\n"),response->length());
如果正确使用的String
类重载赋值运算符=
的行为,这应该有效。
这条线
Serial.println((int)&response);
在你的函数内部是错误的响应已经是一个指针(String * response),用&响应你得到指针的指针。
将其更改为
Serial.println((int)response);
你应该得到与之相同的地址
Serial.println((int)&body);
其中body是String,而body是指向字符串的指针