Question

This is what I'm 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 of the four return* calls. I understand that in the third call a copy of the object is constructed, but I want instead to force the caller of returnconst to store the value as const. Are there workaround to this?

Était-ce utile?

La solution

You're returning by value. You're creating a copy of a const. So you're basically saying you don't want to be able to make copies of const:

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

The previous code doesn't work, you get tons of other errors. It's just not possible :)

It doesn't work not because you restrict it from creating copies of const objects, but there's no way to enforce that the newly created object is also const.

Autres conseils

There is no way to do that. Why do you want to do it? What are you trying to achieve?

your issue here is that it is returning a const object and invoking your copy assignment or constructor to create a by value copy of a new non const object. You could disable by value copy construction and force users to use a reference assignment but that may be annoying.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top