force const存储由值返回的值 [英] force const storing of returned by value value

查看:135
本文介绍了force const存储由值返回的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要完成的:

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();
}

编译器接受所有四个return *调用。我理解,在第三次调用一个对象的副本被构造,但我想要而不是强制调用 returnconst 将值存储为 const 。是否有解决方法?

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?

推荐答案

您按值返回。您正在创建副本 const 。所以你基本上是说你不想复制 const

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 :)

它不工作不是因为你限制它创建 const 对象的副本,但是没有办法强制新创建的对象也是 const

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.

这篇关于force const存储由值返回的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆