Reputation: 4956
I'm trying to set one of the elements of an array to be a different object. But, the compiler is deleting the =
operator. Why is it doing that here, exactly? And how can I work around it?
Example code:
struct IntContainer
{
IntContainer(const int value) :
value(value)
{
}
IntContainer() :
IntContainer(0)
{
}
const int value;
};
int main(int argc, char** argv)
{
IntContainer intContainers[3];
IntContainer newIntContainer(420);
intContainers[0] = newIntContainer; // <-- Causes compiler error
return 0;
}
The compiler error I'm getting when compiling this snippet is:
main.cpp: In function 'int main(int, char**)':
main.cpp:23:24: error: use of deleted function 'IntContainer& IntContainer::operator=(const IntContainer&)'
intContainers[0] = newIntContainer; // <-- Causes compiler error:
^~~~~~~~~~~~~~~
main.cpp:2:8: note: 'IntContainer& IntContainer::operator=(const IntContainer&)' is implicitly deleted because the default definition would be ill-formed:
struct IntContainer
^~~~~~~~~~~~
main.cpp:2:8: error: non-static const member 'const int IntContainer::value', can't use default assignment operator
Upvotes: 0
Views: 2069
Reputation: 9071
The compiler generally gives you operator=
and the copy constructor for free, but when a class contains a const
member, it makes no sense to generate operator=
because you can't perform an assignment to the const
member.
You could write your own, but you still wouldn't be able to assign values to the const
member.
Upvotes: 10