- 論壇徽章:
- 17
|
這是符合標(biāo)準(zhǔn)的,C++ 標(biāo)準(zhǔn)并沒有說Rvalue一定是const的,也就是說rvalue有cv的修飾,2003標(biāo)準(zhǔn)中有如下規(guī)定:
"Some rvalue expressions—those of class or cv-qualified class type—also refer to objects"
"Class rvalues can have cv-qualified types;"
而對(duì)于rvalue對(duì)象調(diào)用成員函數(shù)有如下說明:
“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)表達(dá)式的(作為返回對(duì)象的函數(shù)結(jié)果值)情況下調(diào)用成員函數(shù)。且沒有標(biāo)準(zhǔn)要求是const成員函數(shù)。
根據(jù)上述rvalue與cv的結(jié)合性及成員函數(shù)的調(diào)用說明上來講g++的行為是合乎標(biāo)準(zhǔn)規(guī)定的。
而在VC下 foo( A() )編譯沒有問題是因?yàn)槟J(rèn)啟用了Microsoft Extensions to C and C++。其有中這么一項(xiàng):
Passing a Non-Const Pointer Parameter to a Function that Expects a Reference to a Const Pointer Parameter
因?yàn)橐檬莑value所以g++下編譯不過是正常的。
可以參考:http://msdn.microsoft.com/en-us/library/34h23df8.aspx
網(wǎng)絡(luò)上其它的相關(guān)說法:
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.) |
|