处理报关单
谁能告诉我这两行代码有什么区别,哪一行更好用?
System::String ^MyStr = gcnew System::String(MyStr);
System::String ^MyStr;
Can anyone tell me what the difference is between these 2 lines of code, which one is better to use?
System::String ^MyStr = gcnew System::String(MyStr);
System::String ^MyStr;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些线并不等价。在第一个中,您将得到一个异常,因为您试图从未初始化的跟踪句柄 (MyStr) 创建一个字符串。在第二个中,MyStr 被声明,而不是定义,它指向垃圾,如果您尝试使用它,将会抛出异常。您应该使用哪一个取决于代码的其余部分
Those lines are not equivalent. In the first one, you will get an exception beacuse you're trying to create a String from an uninitialized tracking handle (MyStr). In the second one, MyStr is declared, not defined, it points to garbage and will throw an exception if you attempt to use it. Which one you should use depends on the rest of the code
第二个创建一个新的句柄变量。如果它是一个局部变量,那么正如 @dario_ramos 所说,它是未初始化的,如果您在分配句柄之前尝试使用该句柄,您的程序可能会崩溃。如果它是成员变量或全局变量,那么它将是
nullptr
。第一个是类似的,尽管它只能用于局部变量或全局变量(成员变量在 C++/CLI 中使用ctor-initializer 语法,就像普通的 C++ 一样),并且完全执行您不执行的操作允许做的事。它读取全新的未初始化句柄并将其传递给
System::String
构造函数。如果构造函数偶然完成,新构造的 String 的句柄将作为初始化的一部分放入变量中。但由于构造函数试图创建随机垃圾(如果是本地)或 nullptr(如果是全局)的副本,因此很可能会崩溃。在其自己的初始值设定项中使用任何变量的值都是一个坏主意(有时您需要使用地址,而不是值)。
The second one creates a new handle variable. If it's a local variable, then as @dario_ramos says, it's uninitialized, and your program will likely crash if you try to use the handle before assigning it. If it's a member variable or global, then it will be
nullptr
.The first one is similar, although it can only be used for locals or globals (member variables use the ctor-initializer syntax in C++/CLI just like plain C++), and does exactly what you're not permitted to do. It reads the brand new uninitialized handle and passes it to the
System::String
constructor. If by chance the constructor finishes, a handle to the newly constructedString
will be placed into the variable as part of initialization. But because the constructor is trying to make a copy of random garbage (if it's a local) ornullptr
(if a global), most likely it will simply crash.It's a bad idea to use the value of any variable in its own initializer (sometimes you need to use the address, never the value).