托管代码中使用的STL向量

Kou*_*tty 2 c++ managed-c++ stl visual-c++

操作系统:xp
IDE:VS 2008
在我正在使用Visual C++进行的项目中,我已经声明了一个std::vector内部托管类

std::vector<pts> dataPoints;//this gives error c4368 : mixed type not allowed 
Run Code Online (Sandbox Code Playgroud)

但这很有效

std::vector<pts> * dataPoints;//a pointer to the vector  
Run Code Online (Sandbox Code Playgroud)

然后我在免费商店中创建了这个向量,就像在托管类的构造函数中一样

dataPoints = new std::vector<pts>(noOfElements,pts());//which is not so attractive.
Run Code Online (Sandbox Code Playgroud)

我需要矢量的原因是因为有文件我正在阅读ifstream并将这些值存储在矢量中.
Q1)为什么我能够声明指向本机类型的对象(我猜)而不是对象?此外,在尝试向量之前,我尝试了托管数组

cli::array<Point> dataPoints //and i defined it later.
Run Code Online (Sandbox Code Playgroud)

但是当我这样做的时候

ifile >> dataPoints[i].X;   
Run Code Online (Sandbox Code Playgroud)

它给出了一个错误c2678:operator =没有超载int!!
Q2)为什么我不能在这里使用托管代码.起初我认为它可能是一个包装类Int,但随后autounboxing(转换运算符)应该处理它?还是Point :: X是合格的property,因此不被认为是正常的int?我错过了什么?这就是我选择vectorpts 解决的原因.
pts如下

 struct pts
{
  int X, int Y;
  pts() : X(0),Y(0){}
  pts(int x,int y) : X(x),Y(y){}
};//this i created to store the data from the file.
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 5

托管类对象的一个​​重要属性是它们被垃圾收集器移动.这会在压缩堆时发生.这会对本机C++对象造成严重破坏,指向其成员的指针将变为无效.因此,作为规则,编译器禁止在托管的对象中嵌入本机非POD对象.指针不是问题.

您使用>>运算符时存在完全相同的问题.通过引用operator >>()传递int.如果垃圾收集器在引用int并调用操作符的代码之间正好进行,则会发生灾难.一个简单的解决方法是通过局部变量的中间步骤:

int x;
ifile >> x;
dataPoint[i].X = x;
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为局部变量是稳定的,不受垃圾收集.

这些都不是本机代码中的问题.请记住,您的ref类可以轻松调用本机函数.因此将两者分开可能是有用的和/或必要的.