是 C++ 中的临时对象确实是常量吗?

发布于 2024-10-12 01:52:30 字数 203 浏览 8 评论 0原文

我一直认为C++中的临时对象会被编译器自动视为const。但最近我经历了以下代码示例:

function_returning_object().some_non_const_method();

对 C++ 编译器有效。这让我想知道 - C++ 中的临时对象确实是 const 吗?如果是,那么为什么编译器认为上面的代码是正确的?

I always believed that temporary objects in C++ are automatically considered as const by the compiler. But recently I experienced that the following example of code:


function_returning_object().some_non_const_method();

is valid for C++ compiler. And it makes me wonder - are temporary objects in C++ const indeed? If yes, then why the code above is considered correct by the compiler?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

初雪 2024-10-19 01:52:30

不,他们不是。除非您将返回类型声明为 const,否则不会。

No, they're not. Not unless you declare the return type as const.

如果没有 2024-10-19 01:52:30

这取决于。

int f();
const int g();

class C { };
C x();
const C y();

在使用 f()g() 的情况下,返回值都不是 const,因为不存在非类类型的 const 限定右值。 g() 返回类型中的 const 完全无用(事实上,它比无用更糟糕,因为它在极少数情况下会导致模板实例化问题)。

对于x(),返回值不是const(因为它不是const 限定的)。对于y(),返回值是const(因为返回类型是const 限定的)。这里的 const 限定符(或缺少它)是有意义的,因为返回类型是类类型。

It depends.

int f();
const int g();

class C { };
C x();
const C y();

In the case of both f() and g(), the returned value is not const because there are no const-qualified rvalues of non-class type. The const in the return type of g() is completely useless (in fact, it's worse than useless, since it can in rare circumstances cause issues with template instantiation).

In the case of x(), the returned value is not const (because it isn't const-qualified). In the case of y(), the returned value is const (because the return type is const-qualified). The const qualifier here (or lack thereof) is meaningful because the return type is a class type.

渔村楼浪 2024-10-19 01:52:30

首先回答问题,它们实际上并不是 const。您不能将一个绑定到非常量引用。这样做可能是为了防止在某些情况下出现错误,在这些情况下,它们将作为参数传递给修改它们的函数,仅对临时对象而不是预期目标进行更改。

当您希望使用局部变量对临时变量调用“交换”时,允许对临时变量进行非常量操作特别有用。

std::vector<T> local;
method_that_returns_a_vector().swap( local );

在移动语义出现之前,这被认为是返回大型数据集并获取它而无需复制所有数据的最有效方法。

Answering the question first, they are not actually const. You may not bind one to a non-const reference. This was probably done to prevent errors in certain situations where they would be passed as a parameter to a function that modifies them, only for the changes to be made to a temporary object and not the intended target.

Allowing non-const operations on a temporary is especially useful when you wish to call "swap" on it with a local variable.

std::vector<T> local;
method_that_returns_a_vector().swap( local );

Before the days of move semantics, this was considered the most efficient way to return a large data set and acquire it without copying all the data.

も让我眼熟你 2024-10-19 01:52:30

临时对象可以是 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 模板所做的事情。

Temporary objects can be const, but they don't have to be.

((string const)"hello").append(" world"); // error!

It allows for various things. Consider

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); 
  // ...
};

You could do

bitset b;
b[1] = true; // change second bit to 1

This is what's done by the std::bitset<> template.

凉城凉梦凉人心 2024-10-19 01:52:30

临时对象不是 const,但它们只能绑定到 const 左值引用。很容易证明,允许临时变量绑定到非常量左值引用几乎在所有情况下都是不好的。即使您可以绑定对临时变量的引用,您也无法获取临时变量的地址,并且关于 C++03 中的临时变量,还会发生许多其他非常愚蠢的事情。很高兴 C++0x 很快就会到来......希望如此。

Temporary objects aren't const, but they can only bind to const lvalue references. It's easy to demonstrate that allowing temporaries to bind to non-const lvalue references would be bade in virtually all scenarios. You also can't take the address of a temporary, even though you can bind a reference to it, and a number of other very silly things happen with regards to temporaries in C++03. Just be glad that C++0x will be here soon... hopefully.

醉南桥 2024-10-19 01:52:30

这完全取决于函数的返回类型。

//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

It all depends on the return type of the function.

//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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文