如果临时隐含不可修改,这是如何工作的? [英] If temporaries are implicitly non-modifiable, how does this work?
问题描述
我是告诉,在C ++ 03中,临时
I'm told that, in C++03, temporaries are implicitly non-modifiable.
但是,以下在GCC 4.3上编译了我。 4 (在C ++ 03模式下):
However, the following compiles for me on GCC 4.3.4 (in C++03 mode):
cout << static_cast<stringstream&>(stringstream() << 3).str();
如何编译?
推荐答案
(不
有人告诉我,在C ++ 03中,暂时是不可修改的。
I'm told that, in C++03, temporaries are implicitly non-modifiable.
这不正确。在其他情况下,通过计算右值创建临时值,并且有非常量值和常量值。表达式的值类别和它表示的对象的常数大多数是正交的 1 。观察:
That is not correct. Temporaries are created, among other circumstances, by evaluating rvalues, and there are both non-const rvalues and const rvalues. The value category of an expression and the constness of the object it denotes are mostly orthogonal 1. Observe:
std::string foo();
const std::string bar();
给定上述函数声明,表达式 foo()
是一个非常量的值,它的求值创建一个非常量的临时值, bar()
是一个常量值,创建一个常量临时值。
Given the above function declarations, the expression foo()
is a non-const rvalue whose evaluation creates a non-const temporary, and bar()
is a const rvalue that creates a const temporary.
请注意,您可以在非常量值上调用任何成员函数,允许您修改对象:
Note that you can call any member function on a non-const rvalue, allowing you to modify the object:
foo().append(" was created by foo") // okay, modifying a non-const temporary
bar().append(" was created by bar") // error, modifying a const temporary
/ code>是一个成员函数,你甚至可以分配到非const的值:
Since operator=
is a member function, you can even assign to non-const rvalues:
std::string("hello") = "world";
这应该足以证明你说临时是不是 。
This should be enough evidence to convince you that temporaries are not implicitly const.
1:例外是标量右值,例如42. 总是非常数。
这篇关于如果临时隐含不可修改,这是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!