我尝试使用shared_ptr的2D数组。如果我手动填写所有工作按预期。但是如果我使用两个for循环而不是在位置0/0上使用SIGSEV崩溃。
我尝试了boost和std shared_ptr,没有任何区别。
#include <stdio.h>
#include <memory>
using namespace std;
int main(){
int x = 3;
int y = 3;
shared_ptr<shared_ptr<string>> bar = shared_ptr<shared_ptr<string>>(new shared_ptr<string>[x]);
for(int i=0; i<x; i++)
bar.get()[i] = shared_ptr<string>(new string[y]);
//Crashes: SIGSEGV on 0/0
// for(int i=0; i<x; i++)
// for(int j=0; j<y; j++)
// bar.get()[i].get()[j] = "x";
//works
// for(int i=0; i<x; i++){
// bar.get()[i].get()[i] = "0";
// bar.get()[i].get()[i] = "1";
// bar.get()[i].get()[i] = "2";
// }
//works
// for(int i=0; i<x; i++){
// bar.get()[i].get()[0] = "0";
// bar.get()[i].get()[1] = "1";
// bar.get()[i].get()[2] = "2";
// }
//works
// for(int i=0; i<x; i++){
// bar.get()[0].get()[i] = "0";
// bar.get()[1].get()[i] = "1";
// bar.get()[2].get()[i] = "2";
// }
//works
bar.get()[0].get()[0] = "00";
bar.get()[0].get()[1] = "01";
bar.get()[0].get()[2] = "02";
bar.get()[1].get()[0] = "10";
bar.get()[1].get()[1] = "11";
bar.get()[1].get()[2] = "12";
bar.get()[2].get()[0] = "20";
bar.get()[2].get()[1] = "21";
bar.get()[2].get()[2] = "22";
for(int i=0; i<3; i++){
for(int j=0; j<3; j++)
printf("%s ", bar.get()[i].get()[j].c_str());
printf("\n");
}
return 0;
}