我一直相信 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();
在 and 的情况下f()
,g()
返回的值不是 const,因为没有非类类型的 const 限定右值。const
返回类型的 in完全g()
没用(事实上,它比无用更糟糕,因为它在极少数情况下会导致模板实例化问题)。
在 的情况下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 左值引用。很容易证明,允许临时对象绑定到非 const 左值引用几乎在所有情况下都是错误的。即使您可以绑定对它的引用,您也不能获取临时地址,并且在 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