NSString 弱持有 std::string 的 const char *
NSString 弱包含属于 std::string 的 const char * 最安全的方法是什么?下面的两个示例都适用于日志中的简单测试,并如 NSTableView 中所示,但我担心实际的奇怪行为。可能是 c_str() 的额外空字符被简单地忽略(因为传递了长度参数),并且任何一个都可以正常工作。
鉴于:
std::string const * stdstring = new std::string("Let's see if this works");
那么:
NSString * aStr = [[NSString alloc] initWithBytesNoCopy:
stdstring->data() length: stdstring->length()
encoding:NSUTF8StringEncoding freeWhenDone:NO];
或:
NSString * aStr2 = [[NSString alloc] initWithBytesNoCopy:
stdstring->c_str() length: stdstring->length()
encoding:NSUTF8StringEncoding freeWhenDone:NO];
或者其他什么?
What's the safest way for a NSString to weakly contain a const char * belonging to a std::string? Both examples below work on a simple test, in logs, and as presented in a NSTableView, but I'm concerned about strange behavior down to road. It may be the extra null character of c_str() is simply ignored (because of the length parameter passed) and either will work fine.
Given:
std::string const * stdstring = new std::string("Let's see if this works");
Then:
NSString * aStr = [[NSString alloc] initWithBytesNoCopy:
stdstring->data() length: stdstring->length()
encoding:NSUTF8StringEncoding freeWhenDone:NO];
or:
NSString * aStr2 = [[NSString alloc] initWithBytesNoCopy:
stdstring->c_str() length: stdstring->length()
encoding:NSUTF8StringEncoding freeWhenDone:NO];
or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
initWithBytesNoCopy:length:...
的文档明确指出length
将是使用的字节数,因此空终止字符将始终被忽略。因此,data()
和c_str()
返回的内存内容同样合适。考虑到这一点:
std::string
的data()
和c_str()
函数返回的内存的生命周期保证是相同的- 它们将一直存在,直到您在字符串对象上调用非常量成员函数。这取决于内部数据结构是否已经是空终止字符数组的实现,因此一般来说,data()
会比c_str()
更便宜或复杂度相同>。因此我会选择data()
。The documentation for
initWithBytesNoCopy:length:...
clearly states that thelength
will be the number of bytes used, so the null termination character will always be ignored. Hence the contents of the memory returned bydata()
andc_str()
is equally suitable.With that in mind:
The lifetime guarantees of the memory returned by
std::string
'sdata()
andc_str()
functions are identical - they will survive until you call a non-const member function on the string object. It depends on the implementation whether the internal data structure is already a null-terminated character array, so in general,data()
will be cheaper or identical in complexity toc_str()
. I'd therefore go fordata()
.