c++ - Why is this object considered an rvalue? -


why object i'm passing classa's constructor considered rvalue (temporary)? i'm aware setting parameter const make error go away want understand what's going on.

this behavior works fine function call not constructor?

#include <iostream>  using namespace std;  class classa { public:    classa() {}    classa(classa&) {} };  void f(classa&) {}  int main() {    classa a;     // invalid initialization of non-const reference of type 'classa&'    // rvalue of type 'classa'    classa b = classa(a);      // works fine    f(a);     return 0; } 

the rvalue here classa(a) expression.

classa b = classa(a); 

that copy-initialization, attempt call copy constructor of classa result of classa(a), rvalue. have declared copy constructor take classa&, can't bind rvalues, error.

the best fix is, point out, add const copy constructor can bind rvalues, use direct-initialization, or copy-initialization without type conversion:

classa b (a); classa b {a}; //c++11 classa b = a; 

note although classa b = classa(a); requires valid copy-constructor, copy elided. optional, may made mandatory @ point.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -