Tom*_*ica 2 c++ c-strings stdstring rvalue c++17
由于遗留原因,const char*我正在处理的代码中有很多用法。我试图限制这一点,偶然发现了我想知道的东西。我有类似的东西:
class AClass {
public:
const char* getValue() { return _value.c_str(); }
private:
std::string _value;
}
Run Code Online (Sandbox Code Playgroud)
但是,此类现在可以通过副本返回,例如。按功能:
AClass getAClass();
Run Code Online (Sandbox Code Playgroud)
我们也可能想将其传递给这样的东西:
void functionFromOtherLibrary(const char* value);
Run Code Online (Sandbox Code Playgroud)
现在考虑一下,这可能会导致错误:
functionFromOtherLibrary(getAClass().getValue());
Run Code Online (Sandbox Code Playgroud)
因为该中间体有资格在那时被销毁。即使上面的方法没问题,因为这只是一个陈述,所以这可能不会:
const char* str = getAClass().getValue();
functionFromOtherLibrary(str);
Run Code Online (Sandbox Code Playgroud)
所以我在想写一些类似的东西:
class AClass {
public:
const char* getValue() { return _value.c_str(); }
const char* getValue() && = delete;
}
Run Code Online (Sandbox Code Playgroud)
禁止在右值上调用该方法。只是尝试给了我:
error C2560: cannot overload a member function with ref-qualifier with a member function without ref-qualifier
Run Code Online (Sandbox Code Playgroud)
我不确定这是否:
const char*s 的代码,它似乎总是依赖于这样一个事实,即返回值的对象仍然存在并保存源代码std::string。我非常希望获得更详细的解释,当代码使用std::strings来保存字符串但仅与C字符串通信时会发生什么。
而且,如果您想建议删除C字符串-那就是我现在正在尝试做的事情。我仍然想要一个答案。
You can't overload a function with a ref-qualifier with a function without a ref-qualifier. The MSVC error text is nice and clear on this point.
But you can just add the ref-qualifier to the other one:
class AClass {
public:
const char* getValue() & { return _value.c_str(); }
const char* getValue() && = delete;
};
Run Code Online (Sandbox Code Playgroud)
Whether this is the right design or not is a separate question - but if you decide that it is, this is how you would do it.
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |