force const storing of returned by value value

£可爱£侵袭症+ 提交于 2019-12-24 00:18:41

问题


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:

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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!