Shared_ptr of casted object becomes empty after casting

145 views Asked by At

I'm learning to use std::any and std::any_cast, it's not working as I expected: after casting, the internal shared_ptr of casted object becomes empty.

Here is the simplified code to show the issue, it's hard for me to reason about why after inserting the pointer into the map, the pointed object has changed: shared_ptr no longer points to the original value and becomes empty. I'd love to learn why this behavior happens!

Note I am casting to pointer AA* and store the pointer in an unsorted map, since in real world case I cannot copy AA object, it's a workaround.

Thanks a lot!

struct AA {
  std::shared_ptr<int> m_ptr = std::make_shared<int>(22);
  int get() {
    return *m_ptr;
  }
};

struct Cache {
  std::unordered_map<std::string, std::any> map;

  void insert(std::string str) {
    auto a_ptr = std::make_unique<AA>();
    map[str] = std::make_any<AA*>(a_ptr.get());

    // this casting works as expected, output is 22
    auto casted = std::any_cast<AA*>(map[str]);
    std::cout <<"inside insert: " << casted->get() << std::endl;
    }
};

int main(int argc, char** argv) {
    Cache cache;
    cache.insert("aa");
    auto data = std::any_cast<AA*>(cache.map["aa"]);
    // this won't work, output is 0, why?
    std::cout << "in main: " << data->get() << std::endl;
}

godbolt demo

0

There are 0 answers