【问题标题】:Does Platform::String^ bind directly to a const char[]?Platform::String^ 是否直接绑定到 const char[]?
【发布时间】:2015-06-28 09:01:40
【问题描述】:

const char[] 字符串创建Platform::String^ 时;即

auto platformString = ref new Platform::String("MyString");

它是直接绑定到编译时const char[N] 字符串还是分配一个副本来引用?

【问题讨论】:

  • @EdChum 这不是 C++/CLI,而是 C++/CX。是的,想想他们为什么要创造另一种语法......
  • @LucasTrzesniewski 天哪,我以为他们停在了 C++/CLI 上!对不起,如果这很愚蠢,这里的线索是在命名空间和/或使用 auto 吗?
  • @EdChum 有两条线索:使用ref new 而不是gcnew(我猜gcnew 不合适,因为C++/CX 不是垃圾收集而是参考-而是计算在内),并且在 C++/CLI 中使用 Platform::String^ 而不是 System::String^。 C++/CLI 也支持auto
  • @LucasTrzesniewski 呵呵,好像 C++ 还不够复杂,感谢您的快速教程,将来重新标记时会注意这一点

标签: win-universal-app c++-cx


【解决方案1】:

它需要一个副本——它必须这样做,因为Platform::String^ 的生命周期是由引用计数决定的,而不是由正常的 C++ 生命周期规则决定的。

auto greeting = std::make_unique<wchar_t[]>(20);
wcscpy_s(greeting.get(), 20, L"Hello, World");
auto s = ref new Platform::String(greeting.get());
greeting.reset();

// Still works, even though the original string is gone
OutputDebugString(s->Data());

如果您查看 VC 包含目录中的文件 vccorlib.h(例如 C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include ) 然后你会看到接受const ::default::char16* __strArg 的构造函数最终调用WindowsCreateString 接受一个副本。

【讨论】:

  • 我更新了问题以明确我在谈论编译时间字符串。
  • 那是const char*;您不能根据字符串的文字性重载。 void foo(const char* s);无效 foo(const char s[]);错误 C2535: 'void foo(const char *)' : 成员函数已定义或声明
猜你喜欢
  • 2012-11-12
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多