我在代码中发现了类似的东西:
void foo(IList<int>^ const & list ) { ... }
Run Code Online (Sandbox Code Playgroud)
这^ const&
是什么意思?我查看了C++/CLI规范,但没有发现关于制作常量跟踪引用的评论,也没有发现^&
组合.
这合法吗?
此代码可能是由C++程序员编写的,该程序员使用常见的C++习惯用法编写C++/CLI.这是非常错误的,只有当句柄存储在堆栈上时,才能传递对跟踪句柄的引用.如果传递的List <>引用存储在堆上的对象的字段中,则它无法工作,垃圾收集器可以移动它并使指针无效.编译器将捕获它并生成错误.^已经是参考,不需要额外的参考.
没有引用,const关键字也不再有意义.不是以前做过的,CLR无法强制执行.这并不重要,这个代码无法从任何其他.NET语言调用.它们不会生成指向跟踪句柄的指针.
只需修复它,保持这样的坏代码是没有意义的:
void foo(IList<int>^ list ) { ... }
Run Code Online (Sandbox Code Playgroud)
显示引用无法工作的代码示例:
using namespace System;
using namespace System::Collections::Generic;
ref class Test {
public:
IList<int>^ lst;
void foo(IList<int> const &list) {}
void wontcompile() {
foo(lst); // C3699
IList<int>^ okay;
foo(okay);
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2146 次 |
最近记录: |