Coming from a C# background, I am used to the practice of making structs immutable.
So when I started programming in C++, I tried to do the same with the types that I would usually pass around by value.
I had a simple struct which represents a custom index and simply wraps an integer. Because in C++ the const
keyword is somewhat similar to readonly
in C#, it seemed reasonable to implement my struct like this:
struct MyIndex
{
MyIndex(int value) :
Value(value)
{
}
const int Value;
};
The problem with this approach is that this struct behaves quite differently than an immutable struct in C#. Not just that the Value field of a MyIndex
variable can not be modified, but also any existing MyIndex
variable (local variable or field variable) can't even be replaced with another MyIndex
-instance.
So the following code samples do not compile:
a) Using index as a loop variable.
MyIndex index(0);
while(someCondition)
{
DoWork();
index = MyIndex(index.Value + 1); // This does not compile!
}
b) Modifying a member field of type MyIndex
class MyClass
{
MyIndex Index;
void SetMyIndex(MyIndex index)
{
Index = index; // This does not compile!
}
};
These two samples do not compile, the build error is the same:
error C2582: 'operator =' function is unavailable in 'MyIndex'
What is the reason for this? Why can't the variables be replaced with another instance, despite that they are not const
? And what does the build error mean exaclty? What is that operator =
function?
std::shared_ptr
? In fact javapractices.com/topic/TopicAction.do?Id=29 mentions "no need for a copy constructor" – Mooing Duck Jun 12 '13 at 19:48