簡體   English   中英

const-reference合格的成員函數

[英]const-reference qualified member function

參考限定成員函數的stock示例似乎是這樣的:

#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標准中的一個漏洞嗎? 我在這里錯過了什么嗎?

臨時可以綁定到const& qualified對象,ref-qualifier有效地限定隱式傳遞的對象( *this )。 如果要阻止對臨時值的調用但允許左值,則可以= delete右值引用過載並實現左值版本。 對兩個運算符使用const限定引用限定符只需要一個實現和一個= delete d實現:

class File {
    // ...
    FILE* _file;
public:
    operator FILE*() const&& = delete;
    operator FILE*() const& { return this->_file; }
    // ...
};

凈效應是您只能將轉換用於左值的對象:

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  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM