使用 c++ const 用户输入的数据?
假设我想从 cin 读取一个整数,然后使其不可变。我可以这样做:
int a;
cin >> a;
const int b = a;
然后,我将有一个变量(b),它被初始化为用户数据,但不能更改。但是,我认为我在这里滥用了 const 关键字。这是可以接受的事情吗?编译器似乎对此没问题,但我只是想知道从风格的角度来看它是否正确。
Suppose that I wanted to read an integer from cin and then make it immutable. I can do:
int a;
cin >> a;
const int b = a;
Then, I would have a variable (b) which is initialized to user data, but cannot be changed. However, I think I'm abusing the const keyword here. Is this an acceptable thing to do? The compiler seems to be okay with it, but I'm just wondering if it's right from a stylistic point of view.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
完全没问题。您可以自由地从非常量数据(甚至用户输入的数据)创建常量变量。
您甚至可以编写一个函数,这样之后就不会出现杂散的
a
变量。例如:It's completely fine. You're free to create const variables from non-const data, even user-entered data.
You might even write a function so you don't have the stray
a
variable sitting around afterward. For example:这是一个哲学问题。 :)
在我看来,你并没有做出任何风格上的畸变。您定义了一个从那时起不再改变的变量。该变量值的历史可以忽略不计。 :)
This is a philosophical question. :)
In my opinion you are not doing any stylistic aberration. You are defined a variable that from that point do not change anymore. The history of that variable value is negligible. :)
没关系。您可以放心,在运行程序的上下文中,“b”的值永远不会改变。
It's fine. You are assured that the value of 'b' will never change, within the context of the running program.
虽然我同意罗布和罗布的观点。 David,IMO 最好尽可能使
b
成为引用:尽管在 int 的情况下,您可能不会节省太多,但在较大的对象的情况下,您将节省复制函数调用和内存。
Though I agree with Rob & David, IMO it's better to make
b
a reference when possible:Though in case of int you may not save much, in case of bigger objects you'll save copy c'tor call and the memory.