The book I'm reading says that when your class contains a member that's a reference or a const, using the compiler-generated copy constructor or assignment operators won't work. For instance,
#include <iostream>
#include <string>
using namespace std;
class TextBlock
{
public:
TextBlock (string str) : s(str) {
cout << "Constructor is being called" << endl;
}
string& s;
};
int main () {
TextBlock p("foo");
TextBlock q(p);
q = p;
cout << "Q's s is " << q.s << endl;
return(0);
}
According to my book, both the lines TextBlock q(p);
and q = p;
should return compiler errors. But using the g++ compiler for Linux, I'm only getting an error for the line q = p;
When I comment that out, this works fine and the code compiles. The correct s is output for Q, so it's apparently being copied by the compiler-generated copy constructor. I get the same results when I change the line string& s;
to const string s
.
Have there been some changes to C++ that now allow the copy constructor to be generated automatically for reference and const objects, but not the assignment operator? Or maybe I'm just not understanding the book correctly? Any thoughts?
TextBlock p("foo");
is undefined behaviour. You end up with a dangling reference. – Loudstring
in the constructor, the reference is bound to that. – Loudstd::string
by value. The usual rule is class types are always passed by reference to const.) – Kileconst string& s
) – Pietismstd::string&
as a member would be when it referred to an lvalue, with astd::string&
argument to the constructor, so"foo"
wouldn't compile. At least if you have a decent compiler.) – Kile