samedi 16 mai 2015

How to index into C++ shared_ptr/unique_ptr array?

As inspired by Demo of shared ptr array

I got the first two lines to work:

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;

(1) Can someone show me how to access subsequent elements of my array and print them out with a for loop?

My for loop does not print anything with MSVC V19 and and g++ v4.9 prints "john" but not "Paul" and "Mary" and then gives me a segmentation fault.

Now after some more google/bing searching I found some discussions suggesting I should use unique_ptr if I are not sharing it.

So I got to experimenting some more and this works:

  const int len=3;
  std::unique_ptr<string[]> up( new string[len] ); // this will correctly call delete[]
  up[0] = "john";
  up[1] = "paul";
  up[2] = "mary";
  for(int ii = 0; ii < len; ++ii) cout << up[ii] << endl;

(2) Is there a way to print the array up without hard coding the length in a constant? I was hoping that there was a way to make the new C++ for loop syntax work but it appears only work on std::array and std::vector.

(3) Is there is an easier way to initialize this array? Perhaps with an initializer list?

Aucun commentaire:

Enregistrer un commentaire