gpt4 book ai didi

c++ - 将 const 引用/指针传递给类进行存储的首选方法,而不是复制引用的对象

转载 作者:行者123 更新时间:2023-11-28 04:19:35 25 4
gpt4 key购买 nike

例子:

class Bar;

class Foo
{
public:

Foo(const Bar& bar) : mBar(&bar) {}

/* Other methods use mBar. */

private:

const Bar* mBar;
};

所以目标是存储指向某个外部对象的常量指针,而不是存储外部对象内容的拷贝。

  • 通过 const 引用传递:Foo(const Bar& bar)
    • 将对象传递给构造函数的常用习惯,许多程序员会认为 Foo 将存储 Bar 的拷贝而不是指针/引用本身。
    • 来电者可以暂时通过。这可以通过删除右值重载 Foo(const Bar&&) = delete 来防止。然而,这并不是万无一失的,因为您仍然可以通过一个接受 const 引用并返回 const 引用的函数来走私临时文件。 Foo afoo(std::min(Bar{}, anotherBar)); 例如。
  • 通过 const 指针传递:Foo(const Bar* bar)
    • 必须检查 nullptr,这是一种运行时检查,首选编译时机制。
    • 仍然可以在临时对象中走私:Foo afoo(&std::min(Bar{}, anotherBar));

以上哪一项是首选,为什么?或者有没有更好的方法来做到这一点而不会遇到上述问题?

最佳答案

您可以接受 ::std::reference_wrapper<Bar> ,它将处理传递右值的情况,并提示您要复制包装器而不是对象。

关于c++ - 将 const 引用/指针传递给类进行存储的首选方法,而不是复制引用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55775342/

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