简体   繁体   English

什么是必要的 const 关键字

[英]what is const keyword necessary

My code does not compile.我的代码无法编译。

int foobar()
{
    // code
    return 5;
}

int main()
{
   int &p = foobar(); // error
   // code

   const int& x = foobar(); //compiles
}

Why does adding the keyword const make the code compile?为什么添加关键字const会使代码编译?

In C++ temporaries cannot be bound to non-constant references.在 C++ 中,临时对象不能绑定到非常量引用。

In

 int &p = foobar(); 

The rvalue expression foobar() generates a temporary which cannot be bound to p because it is a non-const reference.右值表达式foobar()生成一个不能绑定到p的临时值,因为它是一个非常量引用。

 const int &x = foobar();

Attaching the temporary to x which is a reference to const prolongs its lifetime.将临时附加到作为对 const 的引用的x可以延长其生命周期。 It is perfectly legal.这是完全合法的。

Because foobar() is returning by value ;因为foobar()按值返回的; this result is a temporary.这个结果是暂时的。 You cannot have a non-constant reference of a temporary.您不能对临时对象进行非常量引用。

If this were not true, what would this code do?如果这不是真的,这段代码会做什么?

int &x = foobar();

x = 1;  // Where are we writing to?

As others have said, you can take a const but not a non-const reference to a temporary.正如其他人所说,您可以对临时对象使用 const 但不能使用非常量引用。

In practice there would be dangers in allowing non-const references to temporaries:在实践中,允许对临时对象进行非常量引用是有危险的:

#include <iostream>
void foo(int &i) {
    i = 5;
}

int main() {
    long l = 4;
    foo(l);
    std::cout << l << "\n";
}

Now, l can be implicitly converted to int , so if a non-const reference to temporary were allowed here, then presumably foo would be passed a reference to the result of that conversion, same as it actually is if foo takes const int & .现在, l可以隐式转换为int ,因此如果此处允许对临时的非常量引用,那么大概foo将传递对该转换结果的引用,就像foo采用const int &时一样。 The assignment would be made to the temporary and then discarded when the temporary is destroyed.分配将被分配给临时对象,然后在临时对象被销毁时被丢弃。 That's much more likely to be a confusing bug than it is to be the intended result.这更可能是一个令人困惑的错误,而不是预期的结果。

I don't know if there's a neat set of rules to allow non-const references to temporaries in some situations but not in the dangerous/annoying ones, but even if so the C++ standard didn't include them.我不知道是否有一套简洁的规则允许在某些情况下对临时对象进行非 const 引用,但在危险/烦人的情况下则不允许,但即使是这样,C++ 标准也不包括它们。 Note that C++0x has rvalue references, which allow you to do some extra things with temporaries that can't be done in C++03.请注意,C++0x 具有右值引用,它允许您使用临时对象做一些在 C++03 中无法完成的额外事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM