【问题标题】:Pass a pointer by const reference通过 const 引用传递指针
【发布时间】:2021-02-28 07:27:47
【问题描述】:

通过 const 引用传递指针不是为了优化吗?

例如

bool testHelper(const TreeNode*& p, const TreeNode*& q) {
    return false;
}

TreeNode* test(TreeNode* root, TreeNode* p, TreeNode* q) {
    recursiveHelper(p, q);
}

错误:

Line 17: Char 28: error: binding reference of type 'const TreeNode *' to value of type 'TreeNode *' not permitted due to incompatible qualifiers
                testHelper(p, q);
                           ^
Line 12: Char 42: note: passing argument to parameter 'p' here
        bool testHelper(const TreeNode*& p, const TreeNode*& q) {
                                         ^

【问题讨论】:

  • 第一个问题:为什么是指针?第二个问题:通过传递一个琐碎的复制值,如指针作为引用,你有什么收获?
  • bool testHelper(const TreeNode* const& p, const TreeNode* const& q) 将通过 const 引用传递它。

标签: c++ pointers reference constants


【解决方案1】:

通过 const 引用传递指针不是为了优化吗?

不,不是,因为它并没有更快。添加的间接性可能会更慢。

bool testHelper(const TreeNode*& p, const TreeNode*& q) 

这些不是对 const 的引用。这些是对指向 const 的非 const 指针的引用。


其他错误:

  • test 被声明为非无效返回,但缺少返回语句
  • 您尚未声明您调用的函数recursiveHelper

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2014-07-27
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多