小编use*_*625的帖子

如何索引 C++shared_ptr/unique_ptr 数组?

共享 ptr 数组演示的启发

我让前两行起作用:

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)

c++ arrays shared-ptr unique-ptr c++11

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

arrays ×1

c++ ×1

c++11 ×1

shared-ptr ×1

unique-ptr ×1