const char * u8_to_bstr(const uint8_t & u8) {
static char s[9]; // space for 8-char string
s[8] = 0; // terminate string
char * sp = s;
for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) {
cout << s << endl;
*(sp ) = ((u8 & xbit) == xbit) ? '1' : '0';
}
return s;
}
我遇到了這段代碼學習將 uint8 轉換為表示其二進制的字串。我的問題是,為什么我們需要靜態字符 s[9] 的靜態限定符?當我洗掉靜態限定符時,我得到了一些非常奇怪的行為,但我不明白為什么。
uj5u.com熱心網友回復:
函式回傳s,它在此函式的堆疊上宣告。如果它不是靜態的,一旦函式回傳,它就會超出范圍,實際上消失,因為一旦函式回傳,堆疊上的所有存盤都可以重用。通過使其成為靜態,它被迫在記憶體中擁有一個持久地址。然而,它仍然是糟糕的設計——如果你從多個執行緒呼叫這個函式,它們會為使用靜態記憶體空間而相互爭斗。
uj5u.com熱心網友回復:
要擴展@VorpalSword 在他們的答案中提供的內容,它不必是靜態的。相反,您可以動態分配陣列。這個動態分配的記憶體在u8_to_bstr退出后將保持有效。
const char * u8_to_bstr(const uint8_t & u8) {
const char *s = new char[9]; // space for 8-char string
s[8] = 0; // terminate string
char *sp = s;
for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) {
cout << s << endl;
*(sp ) = ((u8 & xbit) == xbit) ? '1' : '0';
}
return s;
}
這是對您的代碼的一個非常小的更改,但它確實對您的程式的作業方式有影響,并且您必須稍后記住以釋放這些記憶體。
delete[] variable_holding_results_of_u8_to_bstr;
這是一個簡單的視圖 os 將您的資料存盤在記憶體中,以便它在u8_to_bstr完成作業后仍然可用而不使用static. 這絕不是唯一的方法或最好的方法。
在良好的實踐中,您將使用std::unique_ptrandstd::vector而不是手動分配和洗掉陣列。以下是已翻譯為使用這些工具的代碼的快速視圖。請注意我添加了一個print_vec輔助函式。
#include <iostream>
#include <vector>
#include <memory>
using std::vector;
using std::unique_ptr;
using std::make_unique;
void print_vec(unique_ptr<vector<char>> const& v);
unique_ptr<vector<char>> u8_to_bstr(const uint8_t & u8);
int main() {
auto r = u8_to_bstr(45);
print_vec(r);
}
void print_vec(unique_ptr<vector<char>> const& v) {
for (auto ch : *v) {
std::cout << ch;
}
std::cout << std::endl;
}
unique_ptr<vector<char>> u8_to_bstr(const uint8_t & u8) {
auto s = make_unique<vector<char>>(9, '\0');
auto sp = s->begin();
for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) {
print_vec(s);
*(sp ) = ((u8 & xbit) == xbit) ? '1' : '0';
}
return s;
}
You will almost certainly need to compile this specifying the C 14 or C 17 standards. If you wish to research the types and functions introduced, cppreference.com is a good site, and will tell you what C standards types/fucntions were introduced in.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321229.html
標籤:C
