Auto Variable Assigning Array Does Not Copy

Started by
3 comments, last by WitchLord 3 years, 2 months ago

Declaring a variable as auto and assigning it to an array will not perform a shallow copy, instead effectively reusing the underlying references such that modifying one of the two arrays will modify the other. Declaring the variable as the array type explicitly will result in a copy. Is this something that's known/a feature?

Consider the two fragments below:

array<int> input = {1, 2, 3};
auto copied = input;
copied.insertLast(4);
// copied.length() == 4
array<int> input = {1, 2, 3};
const auto copied = input;
input.insertLast(4);
// copied.length() == 4
Advertisement

Yes, this is known and documented.

http://www.angelcode.com/angelscript/sdk/docs/manual/doc_datatypes_auto.html

The auto type will prefer handles where it can, to avoid making copies.

If you want the copy to be made, either declare the variable with the real type, or make an explicit copy.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

@WitchLord Ah, ok. I did not consider that the array would be considered an array. From what I understand, arrays are reference types. Is it correct to treat all reference types as handles when using them?

As a general rule you should prefer to use handles when working with reference types to avoid unnecessary memory copies and improve performance. But there is obviously nothing wrong to making a copy when you actually need to preserve the original while modifying the copy.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement