Pass a readonly field from C# as a const double&

103 Views Asked by At

In our project we have a readonly struct for a 3-dimensional vector (x,y,z) defined in C# like this:

public readonly struct Vec3
{
   public readonly double X, Y, Z;
   ...
}

and we want to, in C++/CLI code, call what is essentially the following:

auto myVector = Vec3(1, 2, 3);
coordinates.push_back(myVector.X); //"coordinates" is a std::vector<double>

But doing so results in the following error:

C3893: l-value use of initonly data member is only allowed in an instance constructor of class ....Vec3.

We are fairly certain this is because the push_back() method has the following signature:

void push_back(const _Ty& _Val)

But we haven't figured out how to pass that readonly field to push_back. We've tried various casts, and the only thing that has worked so far is to do the following:

double x = vert.X;
coords.push_back(x);

Any ideas on how to do this "properly"? Thanks for the help!

1

There are 1 best solutions below

0
On

I'll repost Hans' comment above and mark it as an answer so it's clearly shown as such:

Hans Passant says: "There are two problems with the statement, unfortunately the compiler picked the harder-to-understand one. Use

double copy = myVector.X;
coords.push_back(copy);

to ensure that the compiler knows that a garbage collection can't invalidate the double&. Well, you already discovered that, it is the proper workaround."