2017-04-19 18 views
1

爲什麼在調用c_str()後unique_ptr不再指向有效的wstring?unique_ptr在調用c_str()後沒有指向有效值

wstring encrypt = L"hello"; 
LPCWSTR decrypted = DecryptString(&EncryptString(encrypt)[0]).get()->c_str();  

unique_ptr<wstring> DecryptString(LPCWSTR str) 
{ 
    unique_ptr<wstring> decryptedStr = make_unique<wstring>(); 
    decryptedStr.get()->resize(wcslen(str)/sizeof(WCHAR) + 1); 

    wstring key = L"123"; 

    for (int i = 0; i < wcslen(str)/sizeof(WCHAR); i++) 
    { 
     (*decryptedStr.get())[i] = str[i]^key[i % key.size()]; 
    } 

    return decryptedStr; 
} 
+1

順便說一句,你不需要使用'獲得() - >'在'的std :: unique_ptr'。只要' - >'也可以。 – aschepler

+1

你爲什麼在這裏使用'std :: unique_ptr'?爲什麼不只是'std :: wstring'? – Galik

+0

我同意你的說法unique_ptr在這裏沒有用。 – Xor

回答

1

DecryptString(&EncryptString(encrypt)[0])返回臨時std::unique_ptr,這將在statememt後立刻予以銷燬。即

LPCWSTR decrypted = DecryptString(&EncryptString(encrypt)[0]).get()->c_str(); 
// the temporary std::unique_ptr has been destroyed here, 
// the wstring managed by it was destroyed too 
// decrypted is dangled now 

您可以使用一個名爲std::unique_ptr代替:

{ 
    auto p = DecryptString(&EncryptString(encrypt)[0]); 
    LPCWSTR decrypted = p.get()->c_str(); 
    ... 
} 
// p and the wstring managed by it is destroyed here 
相關問題