[英]Are temporary objects in C++ const indeed?
我一直認為C ++中的臨時對象會被編譯器自動視為const。 但最近我經歷了以下代碼示例:
function_returning_object().some_non_const_method();
對C ++編譯器有效。 它讓我想知道 - 是C ++ const中的臨時對象嗎? 如果是,那么為什么編譯器認為上面的代碼是正確的?
不,他們不是。 除非您將返回類型聲明為const。
這取決於。
int f();
const int g();
class C { };
C x();
const C y();
在f()
和g()
的情況下,返回的值不是const,因為沒有非類型的const限定的rvalues。 返回類型g()
的const
是完全無用的(實際上,它比無用更糟,因為它在極少數情況下會導致模板實例化問題)。
在x()
的情況下,返回的值不是const(因為它不是const限定的)。 在y()
的情況下,返回的值是const(因為返回類型是const限定的)。 這里的const
限定符(或缺少限定符)是有意義的,因為返回類型是類類型。
首先回答問題,它們實際上不是常量。 您不能將其綁定到非const引用。 這可能是為了防止在某些情況下出現錯誤,這些錯誤將作為參數傳遞給修改它們的函數,僅用於對臨時對象而不是預期目標進行更改。
當您希望使用局部變量對其進行“交換”時,允許對臨時文件執行非常量操作尤其有用。
std::vector<T> local;
method_that_returns_a_vector().swap( local );
在移動語義的日子之前,這被認為是返回大型數據集並獲取它而不復制所有數據的最有效方法。
臨時對象可以是const,但它們不一定是。
((string const)"hello").append(" world"); // error!
它允許各種各樣的事情。 考慮
struct bitref {
int index;
bitref &operator=(bool value); // non-const!
};
struct bitset {
int flags;
// returns a bitref temporary that's associated with the bit
// at index 'index'.
bitref operator[](int index);
// ...
};
你可以做到
bitset b;
b[1] = true; // change second bit to 1
這是由std::bitset<>
模板完成的。
臨時對象不是const,但它們只能綁定到const lvalue引用。 很容易證明,允許臨時數據綁定到非常量左值引用幾乎在所有情況下都會受到影響。 你也不能拿一個臨時的地址,即使你可以綁定它的引用,還有一些其他非常愚蠢的事情發生在C ++ 03中的臨時性。 很高興C ++ 0x很快就會到來......希望如此。
這一切都取決於函數的返回類型。
//Temporary objects: nameless objects that are only usable in current statement
Object function(); //Return a temporary object by value (using copy constructor)
const Object function(); //Return a const temp object by value
//references, return a reference to an object existing somewhere else in memory
Object & function(); //Return an object reference, non-const behaves as any other non-const
const Object & functon(); //Return const obj reference, behaves as any other const
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.