问题
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?
回答1:
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
:
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
.
回答2:
There is no way to do that. Why do you want to do it? What are you trying to achieve?
回答3:
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.
来源:https://stackoverflow.com/questions/10522449/force-const-storing-of-returned-by-value-value