Reputation: 969
I am trying to use a shared pointer that will be shared to different objects throughout my program. I have noticed that when I create the pointer before giving it to the objects that need it, there is no data. It is probably something to do with how I am implementing the pointers. I have added a sample of what I am trying to do, and what is happening
int main() {
// This would be the data I want to share. For simplicity
// using a vector of ints
std::vector<int> data;
// Create the shared pointer
// The objects that are getting access are not allowed to change the
// the data so thats why I put in const (could be wrong on what that is
// actually doing)
std::shared_ptr<const std::vector<int>> pointer_to_vector =
std::make_shared<std::vector<int>>(data);
// Add data to the object wanting to share
data.push_back(1);
data.push_back(2);
data.push_back(3);
data.push_back(4);
// If I look at pointer_to_vector in debu at this point it shows no
// data, size 0
}
If I create the shared pointer (pointer_to_vector) after I add the data (push_back) it works. However if I want to add data to the vector later in the program, the pointer will not be updated, so the objects dont have access to the new data. Is there something I am doing wrong, or fundamentally my understanding is wrong?
Upvotes: 0
Views: 334
Reputation: 30709
This code:
std::vector<int> data;
auto pointer_to_vector = std::make_shared<std::vector<int>>(data);
creates a new object that is a copy of data
and returns a shared pointer to it. You then add elements to data
, but not to the new vector.
However, if you write:
auto pointer_to_vector = std::make_shared<std::vector<int>>();
auto& data = *pointer_to_vector;
then you have a newly-created vector, and data
is a reference to that object. The latter looks closer to what you intended.
Upvotes: 0
Reputation: 1
data
is unrelated to the instance created with std::make_shared<std::vector<int>>(data);
.
What you really want is
std::shared_ptr<const std::vector<int>> pointer_to_vector =
std::make_shared<std::vector<int>>(data);
// Add data to the object wanting to share
pointer_to_vector->push_back(1);
pointer_to_vector->push_back(2);
pointer_to_vector->push_back(3);
pointer_to_vector->push_back(4);
The vector created with the std::make_shared<std::vector<int>>(data)
takes a copy for initialization. The instances are still unrelated though.
Upvotes: 2