【问题标题】:Reference to pointer to const as function argument引用指向 const 作为函数参数的指针
【发布时间】:2020-08-12 05:02:58
【问题描述】:

我有以下基本代码:

基本代码

int main()
{
  int i = 1;

  const int* p = &i;
  int* q = &i;

  test_ptr(p);
  test_ptr(q);
}

谁能解释为什么第一个和第三个示例可以使用上述基本代码,而第二个则不能?

示例实现test_ptr()

示例 1 有效。这是可行的,因为具有指向 const int 的指针的函数也将接受指向非 const int 的指针(但不是相反)

void test_ptr(const int* p)  // pointer to const int
{

}

示例 2 不起作用。我真的不明白为什么。它仍然是指向 const int 的指针,但作为引用传递。这与我对引用如何工作的理解不一致。当我将非常量指针传递给函数时,它会失败。

void test_ptr(const int*& p)  // reference to pointer to const int
{

}

示例 3 再次运行,我完全迷失了。那么,如果情况 2 不起作用,为什么我将 int* 表示为 typedef 会再次起作用?

typedef int* int_ptr;

void test_ptr(const int_ptr& p)  // like case 2 but int* expressed as typedef
{

}

当我使用指针指向指针而不是引用指针时也会发生这种情况。

编辑:示例 3 需要一个不同的 main 函数来使用 typedef:

int main()
{
  int i = 1;

  const int_ptr p = &i;  // use typedef here
  int_ptr q = &i;  // use typedef here

  test_ptr(p);
  test_ptr(q);
}

【问题讨论】:

  • 示例 2 不起作用是什么意思?它可以与正确的呼叫类型一起使用。见a live demo
  • void test_ptr(int const* const& p) 将是 2 的正确签名。指针也需要为 const
  • .... 当您将 p 传递给它时,3 不起作用,因为 int_ptr 是非常量的。 const int_ptr& 表示 int* const& 不是 int const*&
  • this 回答你的问题了吗?
  • @TedLyngmo 没关系。任何有更好建议的人都可以提出他们的建议。一个不完美的答案总比没有好。感谢您的帮助。

标签: c++ pointers reference arguments constants


【解决方案1】:

示例 2:

void test_ptr(const int*& p);

这适用于const int*,但不适用于int*,因为从int*const int* 的转换意味着必须使用const& 来完成与临时的绑定,以延长寿命。

示例 3(使用第一个 main 版本时):

typedef int* int_ptr; // or: using int_ptr = int*;

void test_ptr(const int_ptr& p);

这两个都一样:

void test_ptr(int_ptr const& p);
void test_ptr(int* const& p);

const 从右到左应用于新类型,所以不是intconst,而是指针。因此,该函数将接受int*,但不接受const int*,因为允许该函数根据其签名更改int:s。

同时接受int*const int* 的函数应该具有以下等效签名之一:

void test_ptr(const int* const& p);
void test_ptr(int const* const& p);

免责声明:我非常不确定此答案中使用的措辞

【讨论】:

  • 这似乎行得通。我选择去掉 typedef,因为它不是我想要表达的。将 const 从 int_ptr 之前移到 int_ptr 之后可以解释为什么会这样。我在你回答的最后加上了额外的 const,这对我有用。
  • @Cerno 太棒了!我试图在标准中找到正确的段落,以便通过使用标准的词语来更好地回答 - 但是当涉及到这个时,它会在不同的章节之间来回引用,所以我发现很难让它更清楚。跨度>
猜你喜欢
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多