gpt4 book ai didi

c++ - 下标 this 指针的效果

转载 作者:太空狗 更新时间:2023-10-29 20:57:56 27 4
gpt4 key购买 nike

this[5] 有什么作用?我是否调用了某种未定义的行为?关于:

std::vector<decltype(this)> foo{this, this + 5u};

这个有用吗?我想知道指针算法对 this 的影响是什么。这是一个测试程序:

#include <iostream>
#include <vector>

struct Foo
{
int n = 1;

void foo()
{
std::vector<decltype(this)> foo{this, this + 5u};
for (decltype(foo.size()) i = 0; i != foo.size(); ++i)
{
std::cout << foo[i]->n << "\n";
}
}
};

int main()
{
Foo{}.foo();
}

/* OUTPUT:
* 1
* 0
*/

最佳答案

首先,您需要记住,指针下标本质上是一种语法糖,旨在简化对数组的操作。相反,它通过对指向此类数组元素的指针执行算术运算来实现这一点。

因此,给定 int array[3] 和一个指针 int* ptr = &array[0]ptr[2] 是指向 array 的第三个元素的指针。

出于完全相同的原因,并且由于数组的名称如何衰减为指针,array[2] 是指向 array 的第三个元素的指针。

您甚至可以更改“起点”:给定 int* ptr = &array[1]ptr[1] 也是指向第 3 个元素的指针array,因为您本质上是在编写 (array+1+1)

没有理由不能将相同的逻辑应用于名为 this 的指针。但是,如果且仅当对象被分配为数组的一部分,并且您不会尝试超出该数组的范围进行读取,那么它是明确定义的。

这是一个例子:

#include <iostream>

struct T
{
int x;

T(int x) : x(x) {};
void bar() { std::cout << x << std::endl; }
void foo() { this[1].bar(); } // or (this+1).bar()
};

int main()
{
T array[4] = { T(0), T(1), T(2), T(3) };
array[0].foo(); // OK, outputs 1
array[1].foo(); // OK, outputs 2
array[2].foo(); // OK, outputs 3
array[3].foo(); // undefined; `this[1]` is the same as `array[4]`, so
// evaluating that pointer has UB, never mind invoking
// bar() through it and printing a member variable!
}

这里是相关的标准措辞:

[C++11: 5.2.1/2]: A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ]

[C++11: 5.7/5]: When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. [..]

关于c++ - 下标 this 指针的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920949/

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