Search code examples
c++c++17stdany

mutable object referred by std::any


Is only the way to modify, not replace, an object stored as std::any is to declare changeable data mutable? E.g. to avoid creation and copy of class S instances:

#include <iostream>
#include <vector>
#include <any>
#include <string>
    
struct S {
    mutable std::string str;
    
    S(S&& arg) : str(std::move(arg.str)) { std::cout << ">> S moved" << std::endl; }
    S(const S& arg) : str(arg.str) { std::cout << ">> S copied" << std::endl; }
    S(const char *s) : str(s) { std::cout << ">> S created" << std::endl; }
    
    S& operator= (const S& arg) { str = arg.str; return *this; }
    S& operator= (S&& arg) { str = std::move(arg.str); return *this; }
    virtual ~S() { std::cout << "<< S destroyed" << std::endl; }
};


int main() {
    std::vector<std::any> container;

    container.emplace_back(S("Test 1"));
    
    std::any_cast<const S&>(container[0]).str = "Test 2";
    
    for (const auto& a : container) {
        std::cout << a.type().name() << ", " 
                  << std::any_cast<const S&>(a).str << std::endl;
    }
}

Solution

  • You can any_cast with non-const reference:

    std::any_cast<S&>(container[0]).str = "Test 2";
    

    Demo

    or

    std::any a = 40;
    
    std::any_cast<int&>(a) += 2;
    std::cout << std::any_cast<int>(a) <<std::endl;
    

    Demo