Compiler-created copy / assignment functions for classes with reference and constant members

The book I'm reading says that when your class contains a member that is referenced or const, using the compiler-created copy constructor or assignment operators will not 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 is " << q.s << endl;

    return(0);
}

According to my book, both strings TextBlock q(p);and q = p;must return a compiler error. But, using the g ++ compiler for Linux, I get an error for the line. q = p;When I comment this, it works fine and the code compiles. The correct s is inferred for Q, so it is apparently copied by the copy constructor created by the compiler. I get the same results when I change the string string& s;to const string s.

++, const-, ? , , ? ?

+4
2

. , .

+4

.

- :

  • -, , ( ).

.

int i;
int &ri1 = i;
int &ri2 = ri1;

, , int&, .

(ri2 = ri1; ), .

:

int& ri; // error

, int&, .

, , , , . , , , ... .

+3

Source: https://habr.com/ru/post/1537418/


All Articles