Prevent L value creation in C ++ 14

C ++ 14 methods can determine if they are caused by an L-value or an R-value:

struct A{ A() { puts("Ctor"); } void m() const & { puts("L-value"); } void m() const && { puts("R-value"); } }; int main(){ A a; //Ctor am() //L-value A().m(); //Ctor; R-value } 

Can ctor indicate what type it is building? Can I completely disable building L-values ​​from my class?

I have a proxy class (several, actually) that should always convert to something else. Using it without conversion is a mistake. I can detect this error at runtime, for example by adding the member bool used_ = 0; #ifndef NDEBUG; and setting it to your user composition and then running assert(used_) in the Dtor proxy class, however it would be much better if I could get a compiler to prevent the initialization of L-value instances of this proxy server in the first place:

  auto x = Proxy().method1().method2(); // no Proxy p; // no Target x = Proxy(); //yes Target x = Proxy().method1().method2(); //yes 

Is it possible to do something similar with C ++ 14?

+8
c ++ c ++ 14
source share
2 answers

Why, of course:

 #include <iostream> using namespace std; class B; class A { public: A(B&& b) {} A(const B&) = delete; }; class B {}; int main() { B b; // A a1; <- error // A a2 = b; // <- error A a3 = move(b); // <- fine return 0; } 
+2
source share
 struct temporary_only { static temporary_only make() { return {}; } temporary_only(temporary_only&&)=delete; int get()&& { return 3; } private: temporary_only() {} }; int main() { //temporary_only x; // illegal std::cout << temporary_only::make().get() << '\n'; // legal } 

living example .

We will disable all public ctors (including copy / move), so no one can create temporary_only except temporary_only::make (rvalue).

note that

 temporary_only&& a = temporary_only::make(); 

still working. Here we have an rvalue associated with an rvalue reference, and that the rvalue reference itself is an lvalue with a multi-line lifetime (lifetime). It is impossible to stop.

+3
source share

All Articles