Const const saving return value

This is what I am trying to accomplish:

struct test{};

const test returnconst(){
    return test();
}

test returnnonconst(){
    return test();
}

int main(){
          test t1=returnnonconst();
    const test t2=returnnonconst();
          test t3=returnconst();  //I want this to be a compile error
    const test t4=returnconst();
}

The compiler accepts all four calls to return *. I understand that in the third call, a copy of the object is created, but instead I want to force the caller to returnconstsave the value as const. Is there any way around this?

+3
source share
3 answers

You return by value. You create a copy const . Therefore, you basically say that you do not want to make copies const:

  struct test {private: test (const test & other); }; Affairs>

The previous code does not work, you get a lot of other errors. It is simply impossible :)

, const, , const.

+3

. ? ?

0

Your problem is that it returns a const object and calls your assignment or copy constructor to create a copy by the value of the new non const object. You can disable the construction of a copy of the value and force users to use the reference task, but this can be annoying.

0
source

All Articles