C++ const 左值引用

发布于 2024-10-02 03:39:54 字数 343 浏览 4 评论 0原文

假设我有:

  • A 类是不可复制的
  • B 类,其成员为 const A& a(并在其构造函数中采用 A 并将其设置在其初始化列表中)
  • 函数 AGenerateA();

这是否意味着它应该有效执行: B(生成A()) ?

即,const ref 是否意味着generateA() 返回的A 的副本尚未完成?这是否意味着只要 B 存在,返回的临时值的范围就会扩展?

编辑:评论中的附加问题: 返回 A& 是否可以接受?从GenerateA()到本地A,如果左值是const A&?

谢谢!

Assuming I have:

  • class A which is non-copyable
  • class B which has as a member, const A& a (and takes an A in its constructer and sets it in its initialization list)
  • a function A GenerateA();

Does this mean that it should be valid to do:
B(GenerateA())
?

i.e, does the const ref mean that no copy of the A that generateA() returns is done? And does that mean that the scope of the returned temporary is extended for as long as B exists?

EDIT: Addon question from the comments:
Is it acceptable to return a A& from GenerateA() to a local A, if the lvalue is a const A&?

Thanks!

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

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

发布评论

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

评论(4

抹茶夏天i‖ 2024-10-09 03:39:55

如果A是不可复制的,则函数AGenerateA()无效,因为按值返回需要创建副本。

如果函数返回一个引用(即 A &GenerateA()),并且该引用指向本地创建的 A 对象,则一旦函数退出,该引用就会失效。 C++ 没有任何形式的垃圾收集,因此只要对象正在使用,就没有办法“延长”它的生命周期。

If A is non-copyable, then the function A GenerateA() is invalid since returning by value requires creating a copy.

If the function returns a reference instead (i.e. A &GenerateA()) and the reference is to a locally created A object, it becomes invalid as soon as the function exits. C++ doesn't have any form of garbage collection, so there is no way to "extend" the lifetime of an object as long as it is in use.

错々过的事 2024-10-09 03:39:55

正如其他人已经指出的那样,如果 A 不可复制,则 AGenerateA() 无法编译。

关于 const ref :不,临时的生命周期不会延长到 B 的生命周期。标准 [12.2.5] 规定:

构造函数构造函数初始化程序 (12.6.2) 中引用成员的临时绑定将持续存在,直到构造函数退出。 [...] 函数返回语句 (6.6.3) 中返回值的临时绑定一直持续到函数退出为止。

所以,是的,在某些情况下存在临时生命周期的延长(有时确实有用:请参阅这篇文章),但不在您介绍的文章中。

关于您的最后一个问题,从 GenerateA() 返回对局部变量的引用是不合法的(并且将结果绑定到 const 引用不会有任何帮助)。

As it has already been stated by others, A GenerateA() cannot compile if A is not copyable.

Regarding the const ref : no, the lifetime of the temporary will not be extended to the lifetime of B. The standard [12.2.5] states :

A temporary bound to a reference member in a constructor's ctor-initializer (12.6.2) persists until the constructor exits. [...] A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits.

So yes, extension of the lifetime of a temporary exists in some contexts (and is sometime truly useful : see this article), but not in the one you presented.

Regarding your last question, it's not legal to return a reference to a local variable from GenerateA() (and binding the result to a const reference won't be of any help).

软的没边 2024-10-09 03:39:55

是和否。

是的,const 引用将绑定到临时变量。不,作为类成员的 const 引用不会像具有自动持续时间的 const 引用那样延长生命周期。

Yes and No.

Yes, the const reference will bind to the temporary variable. No, const references which are class members do not extend lifetime the way const references with automatic duration do.

马蹄踏│碎落叶 2024-10-09 03:39:55

这是一个示例

#include <iostream>
using namespace std;

int& GenX(bool reset)
{
    static int* x = new int;
    *x = 100;
    if (reset)
    {
        delete x;
        x = new int;
        *x = 200;
    }
    return *x;
}

class YStore
{
public:
    YStore(int& x);
    int& getX() { return my_x; }
private:
    int& my_x;
};

YStore::YStore(int& x)
 : my_x(x)
{
}

int main()
{
    YStore Y(GenX(false));
    cout << "X: " << Y.getX() << endl;
    GenX(true); // side-effect in Y
    cout << "X: " << Y.getX() << endl;
    return 0;
}

输出:

X: 100
X: 200

Here's an example:

#include <iostream>
using namespace std;

int& GenX(bool reset)
{
    static int* x = new int;
    *x = 100;
    if (reset)
    {
        delete x;
        x = new int;
        *x = 200;
    }
    return *x;
}

class YStore
{
public:
    YStore(int& x);
    int& getX() { return my_x; }
private:
    int& my_x;
};

YStore::YStore(int& x)
 : my_x(x)
{
}

int main()
{
    YStore Y(GenX(false));
    cout << "X: " << Y.getX() << endl;
    GenX(true); // side-effect in Y
    cout << "X: " << Y.getX() << endl;
    return 0;
}

Output:

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