简体   繁体   English

为类成员返回const std :: string&vs const char *

[英]Returning const std::string& vs const char* for class member

Considering the following class example : 考虑下面的类示例:

class AClass
{
    std::string myString;

    public:
    ...
}

With one of the following accessors : 具有以下访问器之一:

const std::string& GetMyString() const
{
    return myString;
}

versus

const char* GetMyString() const
{
    return myString.c_str();
}

Taking into account that myString is initialized once and is never changed, which accessor is better? 考虑到myString初始化一次且永不更改,哪种访问器更好? The first one, or the second one? 第一个还是第二个? In what situation one of them is more suitable than its neighbor? 在哪种情况下,其中一个比邻居更合适?

The version returning const std::string& covers a superset of the use cases for returning const char* (after all, it can be converted to the latter by calling .c_str() on the return value), with no added weaknesses. 返回const std::string&的版本涵盖了返回const char*的用例的超集(毕竟,可以通过在返回值上调用.c_str()将其转换为后者),而没有增加任何弱点。 Given that std::string is more flexible in other ways, I'd prefer const std::string& of the two options. 鉴于std::string在其他方面更灵活,我更喜欢const std::string&这两个选项。

That said, they're both awkward if the owning object in question isn't immortal; 就是说,如果所涉及的物体不是不朽的,他们俩都会感到尴尬。 even if the string is never changed, if the object itself disappears, the reference to its string is now invalid. 即使该字符串从未更改,如果对象本身消失,对其字符串的引用现在也将无效。 If that's a possibility, you might want to either: 如果有这种可能,您可能想要:

  1. Return by value 按价值回报

or 要么

  1. Use a std::shared_ptr<std::string> member and return that (so the lifetime of the string is no longer tied to the lifetime of the object that created it) 使用std::shared_ptr<std::string>成员并返回该成员(因此字符串的生存期不再与创建它的对象的生存期绑定)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM