Skip to main content
gamedev.net
🔒 Locked

Auto Variable Assigning Array Does Not Copy

Started by TrevorThoele Feb 20, 2021 at 12:59 AM 3 replies 4.6k views
Original Post
TrevorThoele
TrevorThoele

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
WitchLord
WitchLord

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 - <a href="http://www.angelcode.com/tower" rel
TrevorThoele
TrevorThoele

@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?

WitchLord
WitchLord

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 - <a href="http://www.angelcode.com/tower" rel

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.