Advertisement

Allowing &inout references for primitive/value types when those are on the stack

Started by October 01, 2018 12:07 AM
3 comments, last by Miss 6 years, 1 month ago

Hi,

I've noticed this topic where dangers of passing non-reference types as &inout were described. However, I believe there is no danger in passing non-reference types as &inout when the referenced values are located on the stack. Consider a simple example:


void foo(int &inout a)
{
  a = 1;
}

void bar()
{
  int a;

  // I believe this is always safe
  foo(a);
  
  // a is now 1
}

Since the value passed in bar() is located on the stack which is inaccessible by foo(), I believe there's no way a corruption can occur.

While this use case is specific, this covers a very common idiom, and I believe allowing this by default could be quite beneficial. What do you think?

You're right that it is safe for local variables. 

I have considered this before but opted not to allow it, because I felt it would be confusing to users that it works in some cases and others not.

 

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

Advertisement

If a compiler would issue an error clearly explaining that &inout references for primitive types only work with locals, I don't think it would be confusing. As for disallowing things just because they may be confusing, I observed that AngelScript specifically tries to give more power to the user at the expense of more complexity. For instance, just having references in the first place, and three kinds of it with different semantics, may be quite confusing too - see e.g. this topic. I was thrilled to find out that AngelScript chooses the path of treating its users as being capable of learning things and empowering them instead of trying to make things as simple as possible. In this case there's a technical reason why only locals can be referenced, so I don't see it as an arbitrary restriction. On the other hand, allowing this could be useful, considering all the code is already there, and the only thing needed is a compiler check and a diagnostic if the check fails.

To be honest, it's already confusing to me that the example given above doesn't work, it seems like a perfectly normal thing to do, so running into compiler errors when trying these things with &inout is always a surprise.

This topic is closed to new replies.

Advertisement