Skip to content

Allow const class have full authority internally #89

Description

@Mikk155

Allow const methods to modify non-const members internally, or clarify internal member authority

When defining a const method within a class, the compiler strictly prevents the modification of any member variables inside that method, throwing a "Reference is read-only" error.

From an object-oriented design perspective, a const method should guarantee to external callers that the object's public state will not change. However, the class itself should ideally retain internal authority to manage or cache its own data, or at least distinguish between const and non-const members if the language allowed a mutable keyword.

Example 1

Modifying internal state via a const fluid method

const HUDTextParams& MessageParams( uint8 red, uint8 green, uint8 blue ) const 
{
    this.m_MessageParams.r1 = red; 
    this.m_MessageParams.g1 = green;
    this.m_MessageParams.b1 = blue;
    
    return this.m_MessageParams;
}

output:

Angelscript: ... (371, 33) : Reference is read-only.


Example 2

Reusable interface at a big scale

In the snippet below, the Register method must modify internal class members during initialization. Because of this, the method cannot be marked const.

// Inherit from this interface to configure contexts from one key object at the root json
// Register your contexts at ASMapConfig::Registry()
// Do NOT hold references to your object if your Register can return false.
interface IConfigurable {
    // Unique key name in the root json object
    const string& GetName() const;

    // Schema for validating your object. Return null to avoid validation.
    const string GetSchema() const;

    // Called at MapInit with the json object at the root containing GetName() as key.
    // Return false to remove reference to this context.
    bool Register( meta_api::json::v2::json@ config ); 
}

Consequently, the entire class instance must be instantiated as non-const, exposing it to accidental modification or reference deletion anywhere else in the codebase.

Suggestion

If a class defines a method as const, the compiler ensures external safety. However, the internal implementation should have the authority to update its own members, or AngelScript should introduce a way to explicitly mark certain members as safe to update within const contexts similar to C++ mutable keyword or ultimatelly a similar keyword to C# readonly

If a member is not explicitly restricted, non-const members should only behave as read-only outside the class scope, not inside its own methods

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions