- 论坛徽章:
- 17
|
这是符合标准的,C++ 标准并没有说Rvalue一定是const的,也就是说rvalue有cv的修饰,2003标准中有如下规定:
"Some rvalue expressions—those of class or cv-qualified class type—also refer to objects"
"Class rvalues can have cv-qualified types;"
而对于rvalue对象调用成员函数有如下说明:
“Expressions such as invocations of constructors and of functions that return a class type refer to objects, and the implementation
can invoke a member function upon such objects, but the expressions are not lvalues.”
上面这句话说可以在作为rvalue(非lvalue既rvalue)表达式的(作为返回对象的函数结果值)情况下调用成员函数。且没有标准要求是const成员函数。
根据上述rvalue与cv的结合性及成员函数的调用说明上来讲g++的行为是合乎标准规定的。
而在VC下 foo( A() )编译没有问题是因为默认启用了Microsoft Extensions to C and C++。其有中这么一项:
Passing a Non-Const Pointer Parameter to a Function that Expects a Reference to a Const Pointer Parameter
因为引用是lvalue所以g++下编译不过是正常的。
可以参考:http://msdn.microsoft.com/en-us/library/34h23df8.aspx
网络上其它的相关说法:
Well, for an non-const rvalue, you can even call the
non-const member function for that object ... That means,
you can even *change* the rvalue if you want. Therefore,
obtaining the "this" pointer is not so strange compared
with these behaviors in my mind...
For non-class types, the const keyword is ignored for rvalues;
an rvalue of a non-class type is never "cv-qualified". (For
class types, it is relevant, since you can call member functions
on an rvalue; if the rvalue is const, you can only call const
member functions on it.) The return value of a function is an
rvalue, so there's really no point in declaring it const. (Note
that except for calling a member function on it, there is no
possible way to modify an rvalue.) |
|