2017-09-19 77 views
0

我有一個函數,返回std::string。我將它傳遞給printf,並創建了一個幫助函數,該函數使用通用參數調用該函數,並返回std::string中的c字符串指針。每次通話都會收到相同的指針。我認爲這與臨時性的生活有關。如果可能的話,我想解決這個問題並使其安全。多個std ::字符串臨時導致相同的c_str指針

#include <stdio.h> 
#include <string> 

std::string intToString(int num) { 
    char buf[100]; 
    snprintf(buf, sizeof(buf), "%d", num); 
    return buf; 
} 

const char *helper(int num, int increment) { 
    return intToString((num + increment) * 10).c_str(); 
} 

int main() { 
    for (int i=1; i < 5; i++) { 
    printf("- %d: %3s %3s %3s %3s\n", i, 
      intToString((i + 0) * 10).c_str(), 
      intToString((i + 1) * 10).c_str(), 
      intToString((i + 2) * 10).c_str(), 
      intToString((i + 3) * 10).c_str() 
      ); 
    printf("+ %d: %3s %3s %3s %3s\n", i, 
      helper(i, 0), 
      helper(i, 1), 
      helper(i, 2), 
      helper(i, 3) 
      ); 
    } 
    return 0; 
} 

輸出:

- 1: 10 20 30 40 
+ 1: 10 10 10 10 
- 2: 20 30 40 50 
+ 2: 20 20 20 20 
- 3: 30 40 50 60 
+ 3: 30 30 30 30 
- 4: 40 50 60 70 
+ 4: 40 40 40 40 
+2

'返回intToString((NUM +增量)* 10 ).c_str();' - std :: string'支持該指針在調用者獲取地址時消失。你的程序調用未定義的行爲。第一種情況下的臨時使用期限延長。在第二個中,唯一臨時保留的是一個懸掛指針。 – WhozCraig

回答

4

c_str()返回值是唯一有效,只要該字符串對象存在並且沒有被修改。像helper那樣從暫時返回它是不正確的。改爲返回std::string,並且僅在實際需要將其用作c字符串的站點上使用c_str()

參考:http://www.cplusplus.com/reference/string/string/c_str/

0

下面是僅使用C++的對象和流中的等效代碼:

#include <iostream> 
#include <string> 
#include <iomanip> 

std::string helper(int num, int increment) { 
    return std::to_string((num + increment) * 10); 
} 

int main() { 
    for (int i=1; i < 5; i++) { 
     std::cout << "- " << i 
     << ": " << std::setw(3) << std::to_string((i + 0) * 10) 
     << " " << std::setw(3) << std::to_string((i + 1) * 10) 
     << " " << std::setw(3) << std::to_string((i + 2) * 10) 
     << " " << std::setw(3) << std::to_string((i + 3) * 10) 
     << '\n'; 

     std::cout << "+ " << i 
     << ": " << std::setw(3) << helper(i, 0) 
     << " " << std::setw(3) << helper(i, 1) 
     << " " << std::setw(3) << helper(i, 2) 
     << " " << std::setw(3) << helper(i, 3) 
     << '\n'; 
    } 
    return 0; 
} 

預期輸出:

- 1: 10 20 30 40 
+ 1: 10 20 30 40 
- 2: 20 30 40 50 
+ 2: 20 30 40 50 
- 3: 30 40 50 60 
+ 3: 30 40 50 60 
- 4: 40 50 60 70 
+ 4: 40 50 60 70 
相關問題