1

It seems commonly thought that C++/CLI's initonly is the equivalent of C#'s readonly keyword. However, the following:

ref class C { 
    C();
    void Method();
    initonly array<int>^ m_array;
};

C::C() {
    m_array = gcnew array<int>(10);
}

void C::Method() {
    m_array[0] = 5; // Fails with C3893
}

The full error is "'C::m_array': l-value use of initonly data member is only allowed in an instance constructor of class 'C'".

The error message seems strange as I'm not using m_array as the target of an assignment, this is the equivalent of writing

m_array->SetValue(5, 0);

which incidentally compiles fine and does the same thing.

Is this bugged in C++/CLI or by design? By the way, is there any performance penalty to using Array::SetValue vs using the accessor?

A similar (but not identical) case was reported and apparently filed as a bug for VS2008: http://bytes.com/topic/net/answers/847520-initonly-but-not-bug-vc-2008-clr . I'm using Visual Studio 2012.

1 Answer 1

2

Yes, that's a bug. It's enforcing something which is not implied by the .NET type system, and the enforcement is ineffective.

But don't use Array::SetValue, which involves boxing and is not type safe. You can just do:

auto array = m_array; // another handle to same array
array[0] = 5;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.