const引用合格成员函数 [英] const-reference qualified member function
问题描述
具有引用资格的成员函数的原始示例似乎是这样的:
The stock example of a reference-qualified member function seems to be something like this:
#include <stdio.h>
#include <stdexcept>
#include <string>
// Easy access to literals
using namespace std::literals;
// File wrapper
class File {
private:
// The wrapped file
FILE *_file;
public:
File(const char *name) :
_file(fopen(name, "r")) {
// unable to open the file?
if (!_file) throw std::runtime_error{ "Unable to open file: "s + name };
}
~File() {
fclose(_file);
}
// Convert to the underlying wrapped file
operator FILE *() & {
return _file;
}
// TODO: Member functions for working with the file
};
这很好。无法直接从未命名的临时目录检索基础FILE指针。但是,如果我们使强制转换运算符也成为const限定符,那么这似乎就不再起作用。
This works well. It is not possible to retrieve the underlying FILE pointer from an unnamed temporary directly. However, if we make the casting operator also const-qualified, this no longer seems to work.
尽管这是一个非常有用的想法,但不同的编译器却毫不犹豫地吞并了它。以std :: string :: c_str()成员函数为例。您认为它应该是引用限定的(因为否则您的指针无效),但是它不是。
Different compilers simply swallow it without complaint even though it's a terribly useful idea. Take, for example the std::string::c_str() member function. You feel it should be reference-qualified (because otherwise you have an invalid pointer) yet it isn't.
这是C ++ 11标准中的一个漏洞吗?我在这里缺少什么吗?
Is this a hole in the C++11 standard? Am I missing something here?
推荐答案
可以将临时对象绑定到 const&
限定对象,而ref-qualifier有效限定隐式传递的对象( * this
)。如果要阻止对临时变量的调用,但允许使用左值,则可以 = delete
右值引用重载并实现左值版本。对于两个运算符都使用 const
合格的引用限定符,只需要一个实现和一个 = delete
d实现:
A temporary can be bound to a const&
qualified object and the ref-qualifier effectively qualifies the implicitly passed object (*this
). If you want to prevent calls on temporaries but allow lvalues, you can = delete
the rvalue reference overload and implement the lvalue version. Using const
qualified reference qualifiers for both operators requires just one implemented and one = delete
d implementation:
class File {
// ...
FILE* _file;
public:
operator FILE*() const&& = delete;
operator FILE*() const& { return this->_file; }
// ...
};
净效果是,只能将转换用于左值的对象:
The net-effect is that you can use the conversion only for objects to which you go an lvalue:
int main() {
File f;
File const cf{};
FILE* fp = f; // OK
FILE* cfp = cf; // OK
FILE* tfp = File(); // ERROR: conversion is deleted
FILE* mfp = std::move(cf); // ERROR: conversion is deleted
}
这篇关于const引用合格成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!