我让前两行起作用:
std::shared_ptr<string> sp( new string[3], []( string *p ) { delete[] p; } );
*sp = "john";
auto p = &(* sp);
++p = new string("Paul");
++p = new string("Mary");
for(auto q = &(*sp); q <= p; q++) cout << *q << endl;
Run Code Online (Sandbox Code Playgroud)
(1) 有人可以告诉我如何访问数组的后续元素并使用 for 循环将它们打印出来吗?
我的 for 循环不会使用 MSVC V19 打印任何内容,而 g++ v4.9 打印“john”,但不打印“Paul”和“Mary”,然后给我一个分段错误。
现在,经过更多的 google/bing 搜索,我发现了一些讨论,建议unique_ptr如果我不共享它,我应该使用它。
所以我必须进行更多尝试,这很有效:
const int len=3;
std::unique_ptr<string[]> up( new string[len] ); // this will correctly call delete[] …Run Code Online (Sandbox Code Playgroud)