Here's what I'm trying to achieve:
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
int main()
{
vector<int> a {3, 7};
int *p = &a.at (0); //assign 3
for (int i = 0; i < 10; ++i) //swap and print (3,7,3...)
{
p = (*p == a.at (0) ? &a.at (1) : &a.at (0));
cout << *p << '\n';
}
}
I'd like to use smart pointers instead of raw pointers, seeing as how they are much better, but can't really figure out how to implement switching back and forth (this is to be used for taking turns in a game; It's a Player *
).
I tried replacing the pointers here with std::unique_ptr
and std::shared_ptr
in two separate tests, using reset
to switch, with both giving random numbers after the first one, as expected.
Next, I tried with std::weak_ptr
as it looks like what I need, although the interface isn't really that similar. From what I've seen, the only way to use it is through lock()
, so I tried prepending lock().
to the calls of reset
and appending it to dereferencing, but that crashed.
How can I use std::weak_ptr
instead of a raw pointer, or can I actually use one of the other ones somehow?
Rather than using raw pointers for this type of indexing operation, I think you should look into using std::vector::iterator
, keeping in mind that any insertion operation into a std::vector
could invalidate the iterator. For instance, you could do the following:
typedef std::vector<int>::iterator iter_t;
vector<int> a {3, 7};
iter_t p = iter_t(&a.at(0)); //assign 3
for (int i = 0; i < 10; ++i) //swap and print (3,7,3...)
{
p = (*p == a.at(0) ? iter_t(&a.at(1)) : iter_t(&a.at(0)));
cout << *p << '\n';
}