Quick A: Delete the r-value reference overload of the function.
Recently on SO:
const-reference qualified member function
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 }
Add a Comment
Comments are closed.