const-reference qualified member function

后端 未结 1 942
予麋鹿
予麋鹿 2021-02-07 08:15

The stock example of a reference-qualified member function seems to be something like this:

#include 
#include 
#include 

        
1条回答
  •  无人共我
    2021-02-07 08:43

    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 = deleted 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  
    }
    

    0 讨论(0)
提交回复
热议问题