[英]unique_ptr array access Segmentation fault
我通過unique_ptr訪問數組元素時,出現segfault,通過vs調試,發現std::unique_ptr<T[]> p的類型和數據很奇怪,我想應該是數組,但是看起來像一個string,不管我push多少個元素,p的數據都指向“to”,其他元素是看不到的。
代碼
#include <memory>
#include <string>
#include <assert.h>
#include<vector>
#include<iostream>
#include <stack>
#include <string>
#include <sstream>
template <typename T>
class FixedCapacityStockOfStrings {
public:
FixedCapacityStockOfStrings(const int cap) {
p = std::make_unique<T[]>(cap);
MAX = cap;
}
bool isEmpty() {
return N == 0;
}
size_t const size() { return N; }
void push(T& item){
//assert(N < MAX - 1);
if (N == MAX-1) resize(2 * MAX);
p[N++] = item;
}
T pop() {
assert(N > 0);
T item = p[--N];
p[N] = nullptr;//Segmentation fault is here
if ( N <= MAX / 4) resize(MAX / 2);
return item;
}
size_t max() const { return MAX; }
void clear() {
N = 0;
}
private:
void resize(int max) {
auto t = std::make_unique<T[]>(max);
for (int i = 0; i < N; i++) {
t[i] = p[i];
}
p.reset();
p = std::move(t);
MAX = max;
}
std::unique_ptr<T[]> p;
size_t N,MAX;
};
int main() {
FixedCapacityStockOfStrings<std::string> s(100);
std::string line,item;
while (std::getline(std::cin, line)) {
std::istringstream items(line);
while (items >> item) {
if (item != "-")
s.push(item);
else if (!s.isEmpty()) std::cout << s.pop() << " ";
}
std::cout << "(" << s.size() << " left on stack)" << " max stack : " << s.max() << std::endl;
s.clear();
}
}
請注意p[N]
的類型為std::string&
對於T
= std::string
,那又如何
p[N] = nullptr;
確實是使用參數nullptr
調用std::string::operator=(const char*)
。 這不是您可以傳遞給此賦值運算符的參數; 它需要一個以 0 結尾的字符串。
編輯:根據@Remy Lebeau 的建議進行了改進
您應該使用 go
p[N] = T{};
反而。
您忘記在構造函數中初始化N
,所以它是一個垃圾值,讀取它是未定義的行為。
p
包含一個 std::string 數組。 當您分配p[N] = nullptr
時,您將 C 字符串分配給 std::string。 C 字符串是指向以 null 結尾的字符數組的指針,而 nullptr 不是有效的 C 字符串。
在語句中p[N] = nullptr;
,您將nullptr
分配給std::string
,即Undefined Behavior 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.