we are using push_back on an rvalue
No, that’s not the problem. any
stores a copy of what it is given. It doesn’t reference some other object. It creates an object from what it is given. So even if you get a reference to the object in the any
, it wouldn’t be a reference to vec
itself.
If you want to store a reference to an object in an any
, you need to do so explicitly by storing either a pointer or a reference_wrapper
to that object:
using ref_type = decltype(std::ref(vec));
std::any anything = std::ref(vec);
std::any_cast<ref_type>(anything).get().push_back(4);
Note that having an any
which references an object is dangerous. If the any
outlives the lifetime of the referenced object, you’ll get bad things when you try to access the referenced object. This is part of why any
stores copies by default.
solved How to Add Element into a std::vector using std::any