【发布时间】:2015-11-26 14:24:25
【问题描述】:
引用限定成员函数的股票示例似乎是这样的:
#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 限定,这似乎不再有效。
即使这是一个非常有用的想法,不同的编译器也会毫无怨言地接受它。以 std::string::c_str() 成员函数为例。你觉得它应该是引用限定的(因为否则你有一个无效的指针)但它不是。
这是 C++11 标准中的一个漏洞吗?我在这里遗漏了什么吗?
【问题讨论】:
-
你不能让代码更密集一点吗?它不仅仅是 2 种方法的页面
-
c_str()在参数中很有用,即使它是临时的。在f(g().c_str());中,有限的生命周期是可以的。 -
旁白:并非所有的右值引用都是临时的。