Why do primitive and user-defined types act differently when returned as 'const' from a function?

前端 未结 4 1587
无人共我
无人共我 2021-02-02 06:53
#include 

using namespace std;

template
void f(T&&) { cout << \"f(T&&)\" << endl; }

template

        
4条回答
  •  眼角桃花
    2021-02-02 06:58

    The previous answers are perfectly valid. I just want to add a potential motivation why it may sometimes be useful to return const objects. In the following example, class A gives a view on internal data from class C, which in some cases shall not be modifyable (Disclaimer, for brevity some essential parts are left out -- also there are likely easier ways to implement this behavior):

    class A {
        int *data;
        friend class C; // allow C to call private constructor
        A(int* x) : data(x) {}
        static int* clone(int*) {
            return 0; /* should actually clone data, with reference counting, etc */
        }
    public:
        // copy constructor of A clones the data
        A(const A& other) : data(clone(other.data)) {}
        // accessor operators:
        const int& operator[](int idx) const { return data[idx]; }
        // allows modifying data
        int& operator[](int idx) { return data[idx]; }
    };
    
    class C {
        int* internal_data;
    public:
        C() : internal_data(new int[4]) {} // actually, requires proper implementation of destructor, copy-constructor and operator=
        // Making A const prohibits callers of this method to modify internal data of C:
        const A getData() const { return A(internal_data); }
        // returning a non-const A allows modifying internal data:
        A getData() { return A(internal_data); }
    };
    
    int main()
    {
        C c1;
        const C c2;
    
        c1.getData()[0] = 1; // ok, modifies value in c1
        int x = c2.getData()[0]; // ok, reads value from c2
        // c2.getData()[0] = 2;  // fails, tries to modify data from c2
        A a = c2.getData(); // ok, calls copy constructor of A
        a[0] = 2; // ok, works on a copy of c2's data
    }
    

提交回复
热议问题