c++ - Is Const important for Copy Constructor? -
this question has answer here:
i'm running program on dev c++ , it's showing error of const.. in visual studio working fine. const important copy constructor?
#include<iostream> using namespace std; class test { /* class data members */ public: test(test &t) { /* copy data members t*/} test() { /* initialize data members */ } }; test fun() { cout << "fun() called\n"; test t; return t; } int main() { test t1; test t2 = fun(); return 0; }
the copy constructor traditionally declared as
foo(const foo&);
since assumed copy doesn't change object on right hand side (at least copier shouldn't change it, right?)
in standard c++, cannot bind temporary non-const
reference. visual studio uses non-standard extension, , that's why code compiles, should not rely on non-standard extensions.
it not absolutely necessary have copy constructor taking rhs const
reference, ok take reference. in case, won't able perform copy initialization rvalue (a temporary basically).
Comments
Post a Comment