C++ 中 Objective-c NSString * 的最佳等效项是什么?
我正在将 Objective-C 应用程序移植到 C++,并且对这两种语言都相当陌生。在我现在正在处理的类中,有很多字段是字符串文字 NSString
或指向字符串 NSString *
的指针。 C++ 中这些字段的最佳等效项是什么:std::string
、std::string *
或 const char *
?
最初,我认为 std::string 更像 C++,而 const char * 更像 C,所以我应该使用前者。我的同事说后者是首选,因为它更快、更轻,而且不涉及复制。但是,如果我应该将 std::string 作为构造函数中的引用传递为 const std::string & param 它只会被复制一次。
对于我来说,对于 NSString *
等价物来说,最好的选择是什么?
非常感谢您的回复。
I am porting an objective-c application to C++ and am fairly new in either language. In the class I'm handling right now there are quite many fields that are string literals NSString
or pointers to string NSString *
. What is the best equivalent of those fields in C++: std::string
, std::string *
or const char *
?
Initially, I thought that std::string
is more c++-like and const char *
is more C-like so i should use the former. My colleague says that the latter is preferred because it is faster and lighter and there is no copying involved. However, if I should pass std::string
as a reference in constructor as const std::string & param
it would be copied once only.
What would be the best option for me to choose for an equivalent of NSString *
?
Thanks a lot for your responses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSString 是一个不可变的字符串,因此 const std::string 是正确的选择。如果你到处都用它作为参考,你就不会有副本。
NSString is an immutable string, so
const std::string
is the right choice. If you use it as reference everywhere, you wouldn't have copies.一般答案应该是使用
std::string
。但是,根据您的具体情况,您可以选择const char *
。如果你正确使用前者,你不会遭受太多的复制惩罚,但你会得到各种内存安全。The general answer should be to use a
std::string
. However, depending on your circumstances you might chooseconst char *
. If you use the former correctly, you won't incur too many copying penalties, but you get all sorts of memory safety.