gpt4 book ai didi

c++ - 我可以为对象的右值版本删除函数吗?

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:09 25 4
gpt4 key购买 nike

由于遗留原因,在我正在处理的代码中大量使用了 const char*。我试图限制它,并偶然发现了一些我想知道的事情。我有类似的东西:

class AClass {
public:
const char* getValue() { return _value.c_str(); }
private:
std::string _value;
}

但是这个类现在可以通过复制返回,例如。按功能:

AClass getAClass();

我们也可能想把它传递给这样的东西:

void functionFromOtherLibrary(const char* value);

现在想想,这可能会导致错误:

functionFromOtherLibrary(getAClass().getValue());

因为此时中间体有资格被销毁。即使上述一切顺利,因为它是一个声明,这可能不会:

const char* str = getAClass().getValue();
functionFromOtherLibrary(str);

所以我想写这样的东西:

class AClass {
public:
const char* getValue() { return _value.c_str(); }
const char* getValue() && = delete;
}

禁止对右值调用该方法。只是尝试给了我:

error C2560: cannot overload a member function with ref-qualifier with a member function without ref-qualifier

我不确定这是不是:

  1. 是有效的构造并且
  2. 是必要的。我见过很多返回 const char* 的代码,它似乎总是依赖于返回值的对象仍然存在并保存源代码 std::string

如果代码使用 std::string 来保存字符串但仅与 C 字符串通信,我将非常感谢更详细的解释。

如果您想建议删除 C 字符串 - 这就是我现在正在尝试做的事情。不过我还是想要一个答案。

最佳答案

您不能用没有引用限定符的函数重载带有引用限定符的函数。 MSVC 错误文本在这一点上非常清楚。

但是您可以将 ref-qualifier 添加到另一个:

class AClass {
public:
const char* getValue() & { return _value.c_str(); }
const char* getValue() && = delete;
};

这是否是正确的设计是一个单独的问题 - 但如果您认为它是正确的,这就是您的做法。

关于c++ - 我可以为对象的右值版本删除函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com