简体   繁体   中英

removing shared pointers from vector or map

I am currently in the process of learning smart pointers and try to avoid using raw pointers.

I have a vector with shared ptrs

std::vector<std::shared_ptr<View>> mChildren;

and an Add and Remove method

void View::AddChild(std::shared_ptr<View> view) {
    mChildren.push_back(view);
}

void View::RemoveChild(std::shared_ptr<View> view) {
    auto removal = std::remove(mChildren.begin(), mChildren.end(), view);
    mChildren.erase(removal, mChildren.end());
}

Now in another part of my code I have a map

std::map<std::weak_ptr<ModelGem>,std::unique_ptr<ViewGem>,std::owner_less<std::weak_ptr<ModelGem>>> mViews;

Now when I try to remove elements from the map like this:

for (auto iterator = mViews.begin(); iterator != mViews.end();) 
{
    if (iterator->first.expired()) 
    {
        RemoveChild(iterator->second.get());
        iterator = mViews.erase(iterator);
    }
    else 
    {
        iterator++;
    }
}

Now the problem lies here : iterator->second.get() It tells me it cannot convert the rvalue of type pointer to shared ptr. However if I use raw pointers instead of shared pointers this is not an issue at at all.

So, I am wondering if in this case it would be better to just use raw pointers or can I work around this with shared pointers?

So, I am wondering if in this case it would be better to just use raw pointers or can I work around this with shared pointers?

In most cases there is only one right pointer type to use. It is not like one is better than the other. There is only one correct way.

The map holds an unique_ptr<ViewGem> . That means it takes complete ownership and is not sharing with any other datastructure. So it is not possible to have the same object in the vector<shared_ptr...> without causing undefined behavior. You have to decide which ds has owner ship,

  1. If the map has complete ownership, use unique_ptr in map and raw ptr in vector
  2. If vector has ownership, use unique_ptr in vector and raw ptr in map.
  3. If the ownership is like both ds owns and the object should be destroyed only when it is removed from both map and vector, then use a shared_ptr in both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM