0

I need to do the following:

 std::vector<std::string> A; 
 std::vector<std::string> B;
 
 ==> pointer_to_vector<std::string> ptr;

//Some Code
ptr = A; //ptr points to object A

//Some More Code
ptr = B; // //ptr points to object B

During the program, ptr needs to refer to both A and B at different times. How would it be implemented and considering that std::vector makes reallocations, how to use smart pointers here?

Yatharth
  • 27
  • 5
  • 3
    `std::vector*` ? – GManNickG Nov 04 '20 at 22:05
  • 1
    "how to use smart pointers here?" why do you need a smart pointer here? – Slava Nov 04 '20 at 22:09
  • 1
    There is no need for a smart pointer here, a plain raw pointer will suffice. – Remy Lebeau Nov 04 '20 at 22:44
  • Smart pointers manage [ownership](https://stackoverflow.com/questions/49024982/what-is-ownership-of-resources-or-pointers). In the case of an Automatic variable, ownership is already managed. When the variable goes out of scope, it's taken care of. – user4581301 Nov 04 '20 at 23:08

1 Answers1

1

You define a pointer to a vector the same way you define a pointer to any other type - using * in the pointer declaration, and the & address-of operator to get the memory address of a variable to assign to the pointer, eg:

std::vector<std::string> A; 
std::vector<std::string> B;
 
std::vector<std::string> *ptr;

//Some Code
ptr = &A; //ptr points to object A

//Some More Code
ptr = &B; // //ptr points to object B

Or, use std::addressof(), if any objects overload operator& for their own purposes (which std::vector does not), eg:

//Some Code
ptr = std::addressof(A); //ptr points to object A

//Some More Code
ptr = std::addressof(B); // //ptr points to object B
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770