gpt4 book ai didi

C++11 自动 : what if it gets a constant reference?

转载 作者:IT老高 更新时间:2023-10-28 12:10:21 25 4
gpt4 key购买 nike

请看下面的简单代码:

class Foo
{
public:
Foo(){}
~Foo(){}

Foo(const Foo&){}
Foo& operator=(const Foo&) { return *this; }
};

static Foo g_temp;
const Foo& GetFoo() { return g_temp; }

我尝试像这样使用 auto:

auto my_foo = GetFoo();

我预计 my_foo 将是对 Foo 的常量引用,它是函数的返回类型。但是,auto 的类型是 Foo,而不是引用。此外,my_foo 是通过复制 g_temp 来创建的。这种行为对我来说不是那么明显。

为了获得对Foo的引用,我需要这样写:

const auto& my_foo2 = GetFoo();
auto& my_foo3 = GetFoo();

问题:为什么autoGetFoo的返回类型推导出为对象,而不是引用?

最佳答案

阅读这篇文章:Appearing and Disappearing consts in C++


Type deduction for auto variables in C++0x is essentially the same as for template parameters. (As far as I know, the only difference between the two is that the type of auto variables may be deduced from initializer lists, while the types of template parameters may not be.) Each of the following declarations therefore declare variables of type int (never const int):

auto a1 = i;
auto a2 = ci;
auto a3 = *pci;
auto a4 = pcs->i;

During type deduction for template parameters and auto variables, only top-level consts are removed. Given a function template taking a pointer or reference parameter, the constness of whatever is pointed or referred to is retained:

template<typename T>
void f(T& p);

int i;
const int ci = 0;
const int *pci = &i;

f(i); // as before, calls f<int>, i.e., T is int
f(ci); // now calls f<const int>, i.e., T is const int
f(*pci); // also calls f<const int>, i.e., T is const int

This behavior is old news, applying as it does to both C++98 and C++03. The corresponding behavior for auto variables is, of course, new to C++0x:

auto& a1 = i;       // a1 is of type int&
auto& a2 = ci; // a2 is of type const int&
auto& a3 = *pci; // a3 is also of type const int&
auto& a4 = pcs->i; // a4 is of type const int&, too

如果类型是引用或指针,你可以保留 cv 限定符,你可以这样做:

auto& my_foo2 = GetFoo();

不必将其指定为 const(volatile 也是如此)。

编辑: 至于为什么 autoGetFoo() 的返回类型推断为值而不是引用(这是您的主要问题,对不起),考虑一下:

const Foo my_foo = GetFoo();

上面将创建一个拷贝,因为 my_foo 是一个值。如果 auto 要返回一个左值引用,上面的操作就不可能了。

关于C++11 自动 : what if it gets a constant reference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7138588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com