gpt4 book ai didi

c++ - 如何在默认构造函数中初始化引用成员?

转载 作者:太空狗 更新时间:2023-10-29 20:05:08 25 4
gpt4 key购买 nike

问题说明了一切。

如果我要实现默认构造函数,使用 const 指针成员会更好吗?

最佳答案

需要使用成员初始化列表:

struct foo
{
const int& ref;
foo() : ref(some_value()) { }
}

确保 some_value() 不会给你一个临时值。它的生命只会延长到构造函数结束:

A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

关于c++ - 如何在默认构造函数中初始化引用成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094416/

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