What's wrong with arrays?

本文探讨了C++中数组的一些根本问题,如不保存自身大小信息及指针衰变等,并通过实例比较了使用标准库vector的优势,包括安全性、易用性和效率等方面。

In terms of time and space, an array is just about the optimal construct for accessing a sequence of objects in memory. It is, however, also a very low level data structure with a vast potential for misuse and errors and in essentially all cases there are better alternatives. By "better" I mean easier to write, easier to read, less error prone, and as fast.

The two fundamental problems with arrays are that

  • an array doesn't know its own size
  • the name of an array converts to a pointer to its first element at the slightest provocation
Consider some examples:
	void f(int a[], int s)
	{
		// do something with a; the size of a is s
		for (int i = 0; i<s; ++i) a[i] = i;
	}

	int arr1[20];
	int arr2[10];

	void g()
	{
		f(arr1,20);
		f(arr2,20);
	}
The second call will scribble all over memory that doesn't belong to arr2. Naturally, a programmer usually get the size right, but it's extra work and ever so often someone makes the mistake. I prefer the simpler and cleaner version using the standard library vector:
	void f(vector<int>& v)
	{
		// do something with v
		for (int i = 0; i<v.size(); ++i) v[i] = i;
	}

	vector<int> v1(20);
	vector<int> v2(10);

	void g()
	{
		f(v1);
		f(v2);
	}

Since an array doesn't know its size, there can be no array assignment:

	void f(int a[], int b[], int size)
	{
		a = b;	// not array assignment
		memcpy(a,b,size);	// a = b
		// ...
	}
Again, I prefer vector:
	void g(vector<int>& a, vector<int>& b, int size)
	{
		a = b;	
		// ...
	}
Another advantage of vector here is that memcpy() is not going to do the right thing for elements with copy constructors, such as strings.
	void f(string a[], string b[], int size)
	{
		a = b;	// not array assignment
		memcpy(a,b,size);	// disaster
		// ...
	}

	void g(vector<string>& a, vector<string>& b, int size)
	{
		a = b;	
		// ...
	}

An array is of a fixed size determined at compile time:

	const int S = 10;

	void f(int s)
	{
		int a1[s];	// error
		int a2[S];	// ok

		// if I want to extend a2, I'll have to chage to an array
		// allocated on free store using malloc() and use ralloc()
		// ...
	}
To contrast:
	const int S = 10;

	void g(int s)
	{
		vector<int> v1(s);	// ok
		vector<int> v2(S);	// ok
		v2.resize(v2.size()*2);
		// ...
	}
C99 allows variable array bounds for local arrays, but those VLAs have their own problems.

The way that array names "decay" into pointers is fundamental to their use in C and C++. However, array decay interact very badly with inheritance. Consider:

	class Base { void fct(); /* ... */ };
	class Derived { /* ... */ };

	void f(Base* p, int sz)
	{
		for (int i=0; i<sz; ++i) p[i].fct();
	}

	Base ab[20];
	Derived ad[20];

	void g()
	{
		f(ab,20);
		f(ad,20);	// disaster!
	}
In the last call, the Derived[] is treated as a Base[] and the subscripting no longer works correctly when sizeof(Derived)!=sizeof(Base) -- as will be the case in most cases of interest. If we used vectors instead, the error would be caught at compile time:
	void f(vector<Base>& v)
	{
		for (int i=0; i<v.size(); ++i) v[i].fct();
	}

	vector<Base> ab(20);
	vector<Derived> ad(20);

	void g()
	{
		f(ab);
		f(ad);	// error: cannot convert a vector<Derived> to a vector<Base>
	}
I find that an astonishing number of novice programming errors in C and C++ relate to (mis)uses of arrays.  
D:\AwesomeProject>npm run android AwesomeProject@0.0.1 android react-native run-android info Running jetifier to migrate libraries to AndroidX. You can disable it using “–no-jetifier” flag. Jetifier found 1852 file(s) to forward-jetify. Using 12 workers… info JS server already running. info Installing the app… Configure project :react-native-reanimated AAR for react-native-reanimated has been found D:\AwesomeProject\node_modules\react-native-reanimated\android\react-native-reanimated-68-jsc.aar Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0. You can use ‘–warning-mode all’ to show the individual deprecation warnings and determine if they come from your own scripts or plugins. See https://docs.gradle.org/7.4/userguide/command_line_interface.html#sec:command_line_warnings 6 actionable tasks: 6 up-to-date FAILURE: Build failed with an exception. What went wrong: Could not determine the dependencies of task ‘:app:compileDebugJavaWithJavac’. Could not resolve all task dependencies for configuration ‘:app:debugCompileClasspath’. Could not resolve project :react-native-mqtt. Required by: project :app No matching configuration of project :react-native-mqtt was found. The consumer was configured to find an API of a component, preferably optimized for Android, as well as attribute ‘com.android.build.api.attributes.BuildTypeAttr’ with value ‘debug’, attribute ‘com.android.build.api.attributes.ProductFlavor:react-native-camera’ with value ‘general’, attribute ‘com.android.build.api.attributes.AgpVersionAttr’ with value ‘7.3.1’ but: - None of the consumable configurations have attributes. Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. Get more help at https://help.gradle.org BUILD FAILED in 20s error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081 FAILURE: Build failed with an exception. What went wrong: Could not determine the dependencies of task ‘:app:compileDebugJavaWithJavac’. Could not resolve all task dependencies for configuration ‘:app:debugCompileClasspath’. Could not resolve project :react-native-mqtt. Required by: project :app No matching configuration of project :react-native-mqtt was found. The consumer was configured to find an API of a component, preferably optimized for Android, as well as attribute ‘com.android.build.api.attributes.BuildTypeAttr’ with value ‘debug’, attribute ‘com.android.build.api.attributes.ProductFlavor:react-native-camera’ with value ‘general’, attribute ‘com.android.build.api.attributes.AgpVersionAttr’ with value ‘7.3.1’ but: - None of the consumable configurations have attributes. Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. Get more help at https://help.gradle.org BUILD FAILED in 20s at makeError (D:\AwesomeProject\node_modules\execa\index.js:174:9) at D:\AwesomeProject\node_modules\execa\index.js:278:16 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async runOnAllDevices (D:\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5) at async Command.handleAction (D:\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9) info Run CLI with --verbose flag for more details.
08-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值