I Have a struct:

struct Handle 
{
public:
    const unsigned long Id;
    const std::type_index Index;
    Handle() : Id(-1), Index(std::type_index(typeid(Event))){}
    Handle(unsigned long id, std::type_index index) : Id(id), Index(index) {}
};

but when I try to assign it to a variable I get

Error 10 error C2582: 'operator =' function is unavailable in 'EventHandler::Handle'

Why ? (I'm using structs because as far as I know they are handled as datatypes and can be returned from functions without being created with new. Is that correct?)

有帮助吗?

解决方案

The default assignment operator is not generated for Handle because it would be ill-formed. What it does is simply assigns member-wise and that obviously isn't allowed on const members.

Instead, don't declare them const. If they're not intended to be modified outside of assignment operator, simply put them in private section and don't provide interface that would allow modification.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top