为什么引用数组是非法的?

时间:2021-12-10 05:27:09

The following code does not compile.

以下代码不编译。

int a = 1, b = 2, c = 3;
int& arr[] = {a,b,c,8};

What does the C++ standard say about this?

c++标准对此怎么说?

I know I could declare a class that contains a reference, then create an array of that class, as shown below. But I really want to know why the code above doesn't compile.

我知道我可以声明一个包含引用的类,然后创建这个类的数组,如下所示。但是我真的想知道为什么上面的代码不能编译。

struct cintref
{
    cintref(const int & ref) : ref(ref) {}
    operator const int &() { return ref; }
private:
    const int & ref;
    void operator=(const cintref &);
};

int main() 
{
  int a=1,b=2,c=3;
  //typedef const int &  cintref;
  cintref arr[] = {a,b,c,8};
}

It is possible to use struct cintref instead of const int & to simulate an array of references.

可以使用struct cintref代替const int &来模拟引用数组。

15 个解决方案

#1


125  

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

回答你的问题我可以引用标准c++标准§8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

不应该有引用的引用,不应该有引用的数组,也不应该有引用的指针。

#2


47  

References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.

没有对象的引用。它们没有自己的存储空间,它们只是引用现有的对象。由于这个原因,使用引用数组是没有意义的。

If you want a light-weight object that references another object then you can use a pointer. You will only be able to use a struct with a reference member as objects in arrays if you provide explicit initialization for all the reference members for all struct instances. References cannot be default initalized.

如果需要引用另一个对象的轻量级对象,那么可以使用指针。如果您为所有struct实例的所有引用成员提供显式的初始化,那么您将只能使用具有引用成员的结构体作为数组中的对象。不能在默认情况下对引用进行initalize。

Edit: As jia3ep notes, in the standard section on declarations there is an explicit prohibition on arrays of references.

编辑:正如jia3ep所指出的,在声明的标准部分中,对引用数组有明确的禁止。

#3


24  

This is an interesting discussion. Clearly arrays of refs are outright illegal, but IMHO the reason why is not so simple as saying 'they are not objects' or 'they have no size'. I'd point out that arrays themselves are not full-fledged objects in C/C++ - if you object to that, try instantiating some stl template classes using an array as a 'class' template parameter, and see what happens. You can't return them, assign them, pass them as parameters. ( an array param is treated as a pointer). But it is legal to make arrays of arrays. References do have a size that the compiler can and must calculate - you can't sizeof() a reference, but you can make a struct containing nothing but references. It will have a size sufficient to contain all the pointers which implement the references. You can't instantiate such a struct without initializing all the members:

这是一个有趣的讨论。显然,refs的数组是完全非法的,但是我认为,为什么不简单地说“它们不是对象”或“它们没有大小”呢?我要指出的是,数组本身并不是C/ c++中的完整对象——如果您反对,尝试使用数组作为“类”模板参数实例化一些stl模板类,看看会发生什么。你不能返回它们,分配它们,作为参数传递它们。(数组参数被视为指针)。但是,数组的数组是合法的。引用的大小是编译器可以计算并且必须计算的——您不能sizeof()引用,但是您可以创建一个只包含引用的结构体。它的大小足以包含实现引用的所有指针。如果不初始化所有成员,就不能实例化这样的结构体:

struct mys {
 int & a;
 int & b;
 int & c;
};
...
int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs.a += 3  ;  // add 3 to ivar1

In fact you can add this line to the struct definition

实际上,您可以将这一行添加到struct定义中

struct mys {
 ...
 int & operator[]( int i ) { return i==0?a : i==1? b : c; }
};

...and now I have something which looks a LOT like an array of refs:

…现在我有了一些看起来很像参考文献的东西:

int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs[1] = my_refs[2]  ;  // copy arr[12] to ivar2
&my_refs[0];               // gives &my_refs.a == &ivar1

Now, this is not a real array, it's an operator overload; it won't do things that arrays normally do like sizeof(arr)/sizeof(arr[0]), for instance. But it does exactly what I want an array of references to do, with perfectly legal C++. Except (a) it's a pain to set up for more than 3 or 4 elements, and (b) it's doing a calculation using a bunch of ?: which could be done using indexing (not with normal C-pointer-calculation-semantics indexing, but indexing nonetheless). I'd like to see a very limited 'array of reference' type which can actually do this. I.e. an array of references would not be treated as a general array of things which are references, but rather it would be a new 'array-of-reference' thing which effectively maps to an internally generated class similar to the one above (but which you unfortunately can't make with templates).

这不是一个真正的数组,它是一个运算符重载;它不会做数组通常做的事情,比如sizeof(arr)/sizeof(arr[0])。但它确实做到了我想要的一系列引用,完全合法的c++。除了(a)设置3或4个以上的元素是一件很痛苦的事情,(b)它使用一堆?:来进行索引计算(不是使用普通的c -指针-计算-语义索引,但不管怎样)。我希望看到一个非常有限的“引用数组”类型,它实际上可以做到这一点。例如,一个引用数组不会被看作是引用的一般数组,而是一个新的“引用的数组”,它有效地映射到一个内部生成的类,类似于上面的类(但不幸的是,您不能使用模板)。

this would probably work, if you don't mind this kind of nasty: recast '*this' as an array of int *'s and return a reference made from one: (not recommended, but it shows how the proper 'array' would work):

如果您不介意这种麻烦:将'*this'重写为int *'s的数组,并返回从one:(不建议这样做,但它显示了正确的'array'将如何工作):

 int & operator[]( int i ) { return *(reinterpret_cast<int**>(this)[i]); }

#4


21  

Comment to your edit:

评论你的编辑:

Better solution is std::reference_wrapper.

更好的解决方案是std::reference_wrapper。

Details: http://www.cplusplus.com/reference/functional/reference_wrapper/

详细信息:http://www.cplusplus.com/reference/functional/reference_wrapper/。

Example:

例子:

#include <iostream>
#include <functional>
using namespace std;

int main() {
    int a=1,b=2,c=3,d=4;
    using intlink = std::reference_wrapper<int>;
    intlink arr[] = {a,b,c,d};
    return 0;
}

#5


11  

An array is implicitly convertable to a pointer, and pointer-to-reference is illegal in C++

数组可以隐式地转换为指针,并且在c++中指针对引用是非法的

#6


9  

Given int& arr[] = {a,b,c,8};, what is sizeof(*arr) ?

给定int&arr [] = {a,b,c,8}, sizeof(*arr)是什么?

Everywhere else, a reference is treated as being simply the thing itself, so sizeof(*arr) should simply be sizeof(int). But this would make array pointer arithmetic on this array wrong (assuming that references are not the same widths is ints). To eliminate the ambiguity, it's forbidden.

在其他任何地方,引用都被视为简单的事物本身,所以sizeof(*arr)应该只是sizeof(int)。但是这会使这个数组上的数组指针算法出错(假设引用的宽度和ints不一样)。为了消除歧义,这是被禁止的。

#7


8  

Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.

因为像很多人说的那样,引用不是对象。他们只是别名。确实,一些编译器可能将它们作为指针来实现,但是标准没有强制/指定。因为引用不是对象,所以不能指向它们。在数组中存储元素意味着有某种索引地址(例如。,指向某一指标的元素);这就是为什么你不能有引用数组,因为你不能指向它们。

Use boost::reference_wrapper, or boost::tuple instead; or just pointers.

使用boost::::reference_wrapper或boost:::tuple代替;或者只是指针。

#8


4  

You can get fairly close with this template struct. However, you need to initialize with expressions that are pointers to T, rather than T; and so, though you can easily make a 'fake_constref_array' similarly, you won't be able to bind that to rvalues as done in the OP's example ('8');

您可以非常接近这个模板结构。但是,您需要使用指向T的表达式来初始化,而不是T;因此,虽然可以很容易地创建一个类似的“fake_constref_array”,但是不能像OP示例(“8”)那样将其绑定到rvalues;

#include <stdio.h>

template<class T, int N> 
struct fake_ref_array {
   T * ptrs[N];
  T & operator [] ( int i ){ return *ptrs[i]; }
};

int A,B,X[3];

void func( int j, int k)
{
  fake_ref_array<int,3> refarr = { &A, &B, &X[1] };
  refarr[j] = k;  // :-) 
   // You could probably make the following work using an overload of + that returns
   // a proxy that overloads *. Still not a real array though, so it would just be
   // stunt programming at that point.
   // *(refarr + j) = k  
}

int
main()
{
    func(1,7);  //B = 7
    func(2,8);     // X[1] = 8
    printf("A=%d B=%d X = {%d,%d,%d}\n", A,B,X[0],X[1],X[2]);
        return 0;
}

--> A=0 B=7 X = {0,8,0}

——> A=0 B=7 X = {0,8,0}

#9


2  

A reference object has no size. If you write sizeof(referenceVariable), it will give you the size of the object referenced by referenceVariable, not that of the reference itself. It has no size of its own, which is why the compiler can't calculate how much size the array would require.

引用对象没有大小。如果您编写sizeof(referenceVariable),它将给出referenceVariable引用的对象的大小,而不是引用本身的大小。它没有自己的大小,这就是为什么编译器不能计算数组需要的大小。

#10


1  

When you store something in an array , its size needs to be known (since array indexing relies on the size). Per the C++ standard It is unspecified whether or not a reference requires storage, as a result indexing an array of references would not be possible.

当您在数组中存储某样东西时,需要知道它的大小(因为数组索引依赖于大小)。根据c++标准,不确定引用是否需要存储,因为结果索引引用数组是不可能的。

#11


1  

Just to add to all the conversation. Since arrays requires consecutive memory locations to store the item, so if we create an array of references then it's not guaranteed that they will be at consecutive memory location so accessing will be a problem and hence we can't even apply all the mathematical operations on array.

只是为了增加谈话的内容。由于数组需要连续的内存位置来存储项,所以如果我们创建一个引用数组,那么不能保证它们将位于连续的内存位置,因此访问将是一个问题,因此我们甚至不能对数组应用所有的数学操作。

#12


0  

Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.

考虑一个指针数组。指针实际上是一个地址;所以当你初始化数组时,你就像在告诉计算机,“分配这块内存来保存这些X数字(它们是其他项目的地址)。”如果你改变其中一个指针,你只是改变它指向什么;它仍然是一个数字地址,它本身就位于同一个位置。

A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."

引用类似于别名。如果你声明一个引用数组,你基本上是在告诉计算机,“分配这个由分散在周围的所有不同项组成的无定形内存团。”

#13


0  

I believe the answer is very simple and it has to do with semantic rules of references and how arrays are handled in C++.

我认为答案非常简单,它与引用的语义规则以及在c++中如何处理数组有关。

In short: References can be thought of as structs which don't have a default constructor, so all the same rules apply.

简而言之:引用可以被认为是没有默认构造函数的结构体,所以所有的规则都适用。

1) Semantically, references don't have a default value. References can only be created by referencing something. References don't have a value to represent the absence of a reference.

1)语义上,引用没有默认值。引用只能通过引用一些东西来创建。引用没有一个值来表示引用的缺失。

2) When allocating an array of size X, program creates a collection of default-initialized objects. Since reference doesn't have a default value, creating such an array is semantically illegal.

当分配大小为X的数组时,程序会创建一个默认初始化对象的集合。由于引用没有默认值,创建这样的数组在语义上是非法的。

This rule also applies to structs/classes which don't have a default constructor. The following code sample doesn't compile:

这条规则也适用于没有默认构造函数的结构体/类。下面的代码示例没有编译:

struct Object
{
    Object(int value) { }
};

Object objects[1]; // Error: no appropriate default constructor available

#14


-1  

Actually, this is a mixture of C and C++ syntax.

实际上,这是C和c++语法的混合。

You should either use pure C arrays, which cannot be of references, since reference are part of C++ only. Or you go the C++ way and use the std::vector or std::array class for your purpose.

您应该使用纯C数组,这是不可引用的,因为引用只是c++的一部分。或者你使用c++的方法,使用std::vector或std::array类,用于你的目的。

As for the edited part: Even though the struct is an element from C, you define a constructor and operator functions, which make it a C++ class. Consequently, your struct would not compile in pure C!

对于已编辑的部分:尽管struct是来自C的元素,但您定义了构造函数和操作函数,这使它成为c++类。因此,您的结构不会在纯C中编译!

#15


-1  

For a simple reason arrays of references cannot exist! References are compile time entities. Meaning they are replaced with the appropriate addresses during compile time. Now Say you made and array of references array[].

因为一个简单的原因,引用数组不存在!引用是编译时实体。这意味着它们在编译期间会被适当的地址所取代。现在假设您创建了引用数组[]。

And some where in the code you did array[2], that would be fine. The compiler can just look at the third initializer from the array and replace the address.

在代码中,你做了数组[2],这没问题。编译器只需查看数组中的第三个初始化器并替换地址。

But now say you did array[i], what is it going to replace with? There is no information on i.

但是现在假设你做了数组i,它会用什么来代替呢?没有关于i的信息。

The case with pointers is different. They are actual variables which have memory allotted to them and are resolved during runtime if you do *pointer. Hence if you have an array of pointers and do *array[i], it will be valid since there is information about of i during execution.

指针的情况不同。它们是具有分配给它们的内存的实际变量,如果执行*指针,则在运行时解析它们。因此,如果您有一个指针数组和do *array[i],那么它将是有效的,因为在执行过程中有关于i的信息。

I hope it answers the query.

我希望它能回答这个问题。

#1


125  

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

回答你的问题我可以引用标准c++标准§8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

不应该有引用的引用,不应该有引用的数组,也不应该有引用的指针。

#2


47  

References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.

没有对象的引用。它们没有自己的存储空间,它们只是引用现有的对象。由于这个原因,使用引用数组是没有意义的。

If you want a light-weight object that references another object then you can use a pointer. You will only be able to use a struct with a reference member as objects in arrays if you provide explicit initialization for all the reference members for all struct instances. References cannot be default initalized.

如果需要引用另一个对象的轻量级对象,那么可以使用指针。如果您为所有struct实例的所有引用成员提供显式的初始化,那么您将只能使用具有引用成员的结构体作为数组中的对象。不能在默认情况下对引用进行initalize。

Edit: As jia3ep notes, in the standard section on declarations there is an explicit prohibition on arrays of references.

编辑:正如jia3ep所指出的,在声明的标准部分中,对引用数组有明确的禁止。

#3


24  

This is an interesting discussion. Clearly arrays of refs are outright illegal, but IMHO the reason why is not so simple as saying 'they are not objects' or 'they have no size'. I'd point out that arrays themselves are not full-fledged objects in C/C++ - if you object to that, try instantiating some stl template classes using an array as a 'class' template parameter, and see what happens. You can't return them, assign them, pass them as parameters. ( an array param is treated as a pointer). But it is legal to make arrays of arrays. References do have a size that the compiler can and must calculate - you can't sizeof() a reference, but you can make a struct containing nothing but references. It will have a size sufficient to contain all the pointers which implement the references. You can't instantiate such a struct without initializing all the members:

这是一个有趣的讨论。显然,refs的数组是完全非法的,但是我认为,为什么不简单地说“它们不是对象”或“它们没有大小”呢?我要指出的是,数组本身并不是C/ c++中的完整对象——如果您反对,尝试使用数组作为“类”模板参数实例化一些stl模板类,看看会发生什么。你不能返回它们,分配它们,作为参数传递它们。(数组参数被视为指针)。但是,数组的数组是合法的。引用的大小是编译器可以计算并且必须计算的——您不能sizeof()引用,但是您可以创建一个只包含引用的结构体。它的大小足以包含实现引用的所有指针。如果不初始化所有成员,就不能实例化这样的结构体:

struct mys {
 int & a;
 int & b;
 int & c;
};
...
int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs.a += 3  ;  // add 3 to ivar1

In fact you can add this line to the struct definition

实际上,您可以将这一行添加到struct定义中

struct mys {
 ...
 int & operator[]( int i ) { return i==0?a : i==1? b : c; }
};

...and now I have something which looks a LOT like an array of refs:

…现在我有了一些看起来很像参考文献的东西:

int ivar1, ivar2, arr[200];
mys my_refs = { ivar1, ivar2, arr[12] };

my_refs[1] = my_refs[2]  ;  // copy arr[12] to ivar2
&my_refs[0];               // gives &my_refs.a == &ivar1

Now, this is not a real array, it's an operator overload; it won't do things that arrays normally do like sizeof(arr)/sizeof(arr[0]), for instance. But it does exactly what I want an array of references to do, with perfectly legal C++. Except (a) it's a pain to set up for more than 3 or 4 elements, and (b) it's doing a calculation using a bunch of ?: which could be done using indexing (not with normal C-pointer-calculation-semantics indexing, but indexing nonetheless). I'd like to see a very limited 'array of reference' type which can actually do this. I.e. an array of references would not be treated as a general array of things which are references, but rather it would be a new 'array-of-reference' thing which effectively maps to an internally generated class similar to the one above (but which you unfortunately can't make with templates).

这不是一个真正的数组,它是一个运算符重载;它不会做数组通常做的事情,比如sizeof(arr)/sizeof(arr[0])。但它确实做到了我想要的一系列引用,完全合法的c++。除了(a)设置3或4个以上的元素是一件很痛苦的事情,(b)它使用一堆?:来进行索引计算(不是使用普通的c -指针-计算-语义索引,但不管怎样)。我希望看到一个非常有限的“引用数组”类型,它实际上可以做到这一点。例如,一个引用数组不会被看作是引用的一般数组,而是一个新的“引用的数组”,它有效地映射到一个内部生成的类,类似于上面的类(但不幸的是,您不能使用模板)。

this would probably work, if you don't mind this kind of nasty: recast '*this' as an array of int *'s and return a reference made from one: (not recommended, but it shows how the proper 'array' would work):

如果您不介意这种麻烦:将'*this'重写为int *'s的数组,并返回从one:(不建议这样做,但它显示了正确的'array'将如何工作):

 int & operator[]( int i ) { return *(reinterpret_cast<int**>(this)[i]); }

#4


21  

Comment to your edit:

评论你的编辑:

Better solution is std::reference_wrapper.

更好的解决方案是std::reference_wrapper。

Details: http://www.cplusplus.com/reference/functional/reference_wrapper/

详细信息:http://www.cplusplus.com/reference/functional/reference_wrapper/。

Example:

例子:

#include <iostream>
#include <functional>
using namespace std;

int main() {
    int a=1,b=2,c=3,d=4;
    using intlink = std::reference_wrapper<int>;
    intlink arr[] = {a,b,c,d};
    return 0;
}

#5


11  

An array is implicitly convertable to a pointer, and pointer-to-reference is illegal in C++

数组可以隐式地转换为指针,并且在c++中指针对引用是非法的

#6


9  

Given int& arr[] = {a,b,c,8};, what is sizeof(*arr) ?

给定int&arr [] = {a,b,c,8}, sizeof(*arr)是什么?

Everywhere else, a reference is treated as being simply the thing itself, so sizeof(*arr) should simply be sizeof(int). But this would make array pointer arithmetic on this array wrong (assuming that references are not the same widths is ints). To eliminate the ambiguity, it's forbidden.

在其他任何地方,引用都被视为简单的事物本身,所以sizeof(*arr)应该只是sizeof(int)。但是这会使这个数组上的数组指针算法出错(假设引用的宽度和ints不一样)。为了消除歧义,这是被禁止的。

#7


8  

Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.

因为像很多人说的那样,引用不是对象。他们只是别名。确实,一些编译器可能将它们作为指针来实现,但是标准没有强制/指定。因为引用不是对象,所以不能指向它们。在数组中存储元素意味着有某种索引地址(例如。,指向某一指标的元素);这就是为什么你不能有引用数组,因为你不能指向它们。

Use boost::reference_wrapper, or boost::tuple instead; or just pointers.

使用boost::::reference_wrapper或boost:::tuple代替;或者只是指针。

#8


4  

You can get fairly close with this template struct. However, you need to initialize with expressions that are pointers to T, rather than T; and so, though you can easily make a 'fake_constref_array' similarly, you won't be able to bind that to rvalues as done in the OP's example ('8');

您可以非常接近这个模板结构。但是,您需要使用指向T的表达式来初始化,而不是T;因此,虽然可以很容易地创建一个类似的“fake_constref_array”,但是不能像OP示例(“8”)那样将其绑定到rvalues;

#include <stdio.h>

template<class T, int N> 
struct fake_ref_array {
   T * ptrs[N];
  T & operator [] ( int i ){ return *ptrs[i]; }
};

int A,B,X[3];

void func( int j, int k)
{
  fake_ref_array<int,3> refarr = { &A, &B, &X[1] };
  refarr[j] = k;  // :-) 
   // You could probably make the following work using an overload of + that returns
   // a proxy that overloads *. Still not a real array though, so it would just be
   // stunt programming at that point.
   // *(refarr + j) = k  
}

int
main()
{
    func(1,7);  //B = 7
    func(2,8);     // X[1] = 8
    printf("A=%d B=%d X = {%d,%d,%d}\n", A,B,X[0],X[1],X[2]);
        return 0;
}

--> A=0 B=7 X = {0,8,0}

——> A=0 B=7 X = {0,8,0}

#9


2  

A reference object has no size. If you write sizeof(referenceVariable), it will give you the size of the object referenced by referenceVariable, not that of the reference itself. It has no size of its own, which is why the compiler can't calculate how much size the array would require.

引用对象没有大小。如果您编写sizeof(referenceVariable),它将给出referenceVariable引用的对象的大小,而不是引用本身的大小。它没有自己的大小,这就是为什么编译器不能计算数组需要的大小。

#10


1  

When you store something in an array , its size needs to be known (since array indexing relies on the size). Per the C++ standard It is unspecified whether or not a reference requires storage, as a result indexing an array of references would not be possible.

当您在数组中存储某样东西时,需要知道它的大小(因为数组索引依赖于大小)。根据c++标准,不确定引用是否需要存储,因为结果索引引用数组是不可能的。

#11


1  

Just to add to all the conversation. Since arrays requires consecutive memory locations to store the item, so if we create an array of references then it's not guaranteed that they will be at consecutive memory location so accessing will be a problem and hence we can't even apply all the mathematical operations on array.

只是为了增加谈话的内容。由于数组需要连续的内存位置来存储项,所以如果我们创建一个引用数组,那么不能保证它们将位于连续的内存位置,因此访问将是一个问题,因此我们甚至不能对数组应用所有的数学操作。

#12


0  

Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.

考虑一个指针数组。指针实际上是一个地址;所以当你初始化数组时,你就像在告诉计算机,“分配这块内存来保存这些X数字(它们是其他项目的地址)。”如果你改变其中一个指针,你只是改变它指向什么;它仍然是一个数字地址,它本身就位于同一个位置。

A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."

引用类似于别名。如果你声明一个引用数组,你基本上是在告诉计算机,“分配这个由分散在周围的所有不同项组成的无定形内存团。”

#13


0  

I believe the answer is very simple and it has to do with semantic rules of references and how arrays are handled in C++.

我认为答案非常简单,它与引用的语义规则以及在c++中如何处理数组有关。

In short: References can be thought of as structs which don't have a default constructor, so all the same rules apply.

简而言之:引用可以被认为是没有默认构造函数的结构体,所以所有的规则都适用。

1) Semantically, references don't have a default value. References can only be created by referencing something. References don't have a value to represent the absence of a reference.

1)语义上,引用没有默认值。引用只能通过引用一些东西来创建。引用没有一个值来表示引用的缺失。

2) When allocating an array of size X, program creates a collection of default-initialized objects. Since reference doesn't have a default value, creating such an array is semantically illegal.

当分配大小为X的数组时,程序会创建一个默认初始化对象的集合。由于引用没有默认值,创建这样的数组在语义上是非法的。

This rule also applies to structs/classes which don't have a default constructor. The following code sample doesn't compile:

这条规则也适用于没有默认构造函数的结构体/类。下面的代码示例没有编译:

struct Object
{
    Object(int value) { }
};

Object objects[1]; // Error: no appropriate default constructor available

#14


-1  

Actually, this is a mixture of C and C++ syntax.

实际上,这是C和c++语法的混合。

You should either use pure C arrays, which cannot be of references, since reference are part of C++ only. Or you go the C++ way and use the std::vector or std::array class for your purpose.

您应该使用纯C数组,这是不可引用的,因为引用只是c++的一部分。或者你使用c++的方法,使用std::vector或std::array类,用于你的目的。

As for the edited part: Even though the struct is an element from C, you define a constructor and operator functions, which make it a C++ class. Consequently, your struct would not compile in pure C!

对于已编辑的部分:尽管struct是来自C的元素,但您定义了构造函数和操作函数,这使它成为c++类。因此,您的结构不会在纯C中编译!

#15


-1  

For a simple reason arrays of references cannot exist! References are compile time entities. Meaning they are replaced with the appropriate addresses during compile time. Now Say you made and array of references array[].

因为一个简单的原因,引用数组不存在!引用是编译时实体。这意味着它们在编译期间会被适当的地址所取代。现在假设您创建了引用数组[]。

And some where in the code you did array[2], that would be fine. The compiler can just look at the third initializer from the array and replace the address.

在代码中,你做了数组[2],这没问题。编译器只需查看数组中的第三个初始化器并替换地址。

But now say you did array[i], what is it going to replace with? There is no information on i.

但是现在假设你做了数组i,它会用什么来代替呢?没有关于i的信息。

The case with pointers is different. They are actual variables which have memory allotted to them and are resolved during runtime if you do *pointer. Hence if you have an array of pointers and do *array[i], it will be valid since there is information about of i during execution.

指针的情况不同。它们是具有分配给它们的内存的实际变量,如果执行*指针,则在运行时解析它们。因此,如果您有一个指针数组和do *array[i],那么它将是有效的,因为在执行过程中有关于i的信息。

I hope it answers the query.

我希望它能回答这个问题。