2015-02-05 5 views
0

누군가 여기서 제게 설명해 주시겠습니까? (나는 C++에 익숙하지 않다.)복사 생성자가 std :: string을 변경합니다.

이진 문자열 스트림을 사용하고 write() 메서드를 호출하여 4 int32_t으로 시작하는 std::string이 있습니다.

index, typetag (4 int32-ts 중 3 개)이 정확합니다. 이 I 값 함수에 currentSocketInfo 전달할 때

SocketInfo currentSocketInfo; 
currentSocketInfo.header.reserve(_headerLength); 
int iResult = recv(socket, &currentSocketInfo.header[0], _headerLength, 0); 

auto headerIntPtr = reinterpret_cast<const int32_t*>(currentSocketInfo.header.c_str()); 

int32_t index = headerIntPtr[1]; 
int32_t type = headerIntPtr[2]; 
int32_t tag = headerIntPtr[3]; 

appendCurrentMessageFromSocket(socket, currentSocketInfo); 

하지만, 다음과 동일한 reinterpret_cat 할당을 수행 값은 다르다. (처음에는 0, 1, 0과 같지만 함수 호출 후에는 -252142 <과 같음 - 정확하지 않은 숫자 임). 여기

void SocketListener::appendCurrentMessageFromSocket(SOCKET socket, SocketInfo socketInfo) { 

    auto headerIntPtr = reinterpret_cast<const int32_t*>(socketInfo->header.c_str()); 

    int32_t index = headerIntPtr[1]; 
    int32_t type = headerIntPtr[2]; 
    int32_t tag = headerIntPtr[3]; 

} 
SocketInfo 클래스의 질문에 관련된 부분은 헤더 필드 :

class SocketInfo { 
public: 
    bool waitingForWholeMessage; 
    std::string header; 
    std::string body; 
    int32_t expectedLength; 
}; 
+0

'SocketInfo'란 무엇입니까? 우리에게 [최소한의 완전한 예] (http://stackoverflow.com/help/mcve)를 주시겠습니까? – Beta

+0

SocketInfo 클래스를 추가했습니다. 죄송합니다. –

+0

"값으로 함수에 currentSocketInfo를 전달한 다음 똑같은 reinterpret_cat 및 할당을 수행합니다."해당 코드를 표시합니다. 또한, 어떤 컴파일러를 사용하고 어떤 버전입니까? –

답변

0

당신은 내부 recv 무엇을 보여주지 않았다,하지만 난 뭔가를했다는 가정 memcpy 일부 charcurrentSocketInfo.header에 입력하십시오. 내가 currentSocketInfo.headerrecv를 실행 한 후 {0,0,0,0, 1,0,0,0, 0,0,0,0} 포함되어 있다고 가정 할 수 있도록

귀하의 설명에 따르면, index, typetag은 각각 0, 10 있습니다.

다음 일은이며, string 년대 만 0 -ended char* 인 "문자열을", 복사 구성 복사, 그래서 그것은 단지 조우 0 때까지 일을 복사합니다. currentSocketInfo.header와 지금

{0,0,0,0, 1,0,0,0, 0,0,0,0}로, SocketListener::appendCurrentMessageFromSocket에서 복사 SocketInfo socketInfo은 빈 문자열입니다 {0} 같은 것을 가지고 있습니다.

따라서 auto headerIntPtr = reinterpret_cast<const int32_t*>(socketInfo->header.c_str());을 입력하면 headerIntPtr은 의미없는 메모리 주소를 가리 킵니다.

이 (PS 단순의 이익을 위해 난 그냥, 1 대 0을 색인을 변경하고 2)

char c[12] = {0,0,0,0, 1,0,0,0, 0,0,0,0}; 
std::string s1; 
s1.resize(12); 
// should be the same effect like `recv` 
char* tos1 = const_cast<char*>(s1.c_str()); 
memcpy(tos1, c, 12); 
// end of `recv` 

auto p = reinterpret_cast<const int*>(s1.c_str()); 
int i1 = p[0]; // 0 
int i2 = p[1]; // 1 
int i3 = p[2]; // 0 

std::string s2 = s1; 
p = reinterpret_cast<const int*>(s2.c_str()); 
i1 = p[0]; // 0xcccccc00 
i2 = p[1]; // 0xcccccccc 
i3 = p[2]; // 0xcccccccc 

I 시험 :

다음과 같은 코드가 당신에게 무슨 일이 있었는지 동일한 효과를해야한다 위의 코드는 VS2012 Ultimate을 사용합니다

관련 문제