我知道C/C++LI相当于这个C#代码:
using (SomeClass x = new SomeClass(foo)) { // ... }
这是:
{ SomeClass x(foo); // ... }
但有没有类似简洁和类似RAII的方式来表达这一点:
using (SomeClass x = SomeFunctionThatReturnsThat(foo)) { // ... }
要么:
SomeClass x = SomeFunctionThatReturnsThat(foo); using (x) { // ... }
?我最接近的工作示例是:
SomeClass^ x = SomeFunctionThatReturnsThat(foo); try { // ... } finally { if (x != nullptr) { delete x; } }
但这似乎不太好.
解决方法
msclr::auto_handle<>
是托管类型的智能指针:
#include <msclr/auto_handle.h> { msclr::auto_handle<SomeClass> x(SomeFunctionThatReturnsThat(foo)); // ... } // or SomeClass^ x = SomeFunctionThatReturnsThat(foo); { msclr::auto_handle<SomeClass> y(x); // ... }