返回const std :: string&vs const char * for class member

问题描述 投票:1回答:1

考虑以下类示例:

class AClass
{
    std::string myString;

    public:
    ...
}

使用以下访问者之一:

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

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

考虑到myString初始化一次并且永远不会改变,哪个访问器更好?第一个,还是第二个?在什么情况下,其中一个比其邻居更合适?

c++ string member
1个回答
0
投票

返回const std::string&的版本涵盖了返回const char*的用例的超集(毕竟,它可以通过在返回值上调用.c_str()转换为后者),没有任何附加的弱点。鉴于std::string在其他方面更灵活,我更喜欢两种选择的const std::string&

也就是说,如果所涉及的拥有物不是不朽的话,它们都会很尴尬;即使字符串永远不会更改,如果对象本身消失,对其字符串的引用现在也无效。如果这是可能的,您可能想要:

  1. 按价值返回

要么

  1. 使用std::shared_ptr<std::string>成员并返回该成员(因此字符串的生命周期不再与创建它的对象的生命周期相关联)
© www.soinside.com 2019 - 2024. All rights reserved.