Assignment operator overloading (Dynamic string library)


I've been working on a dynamic string library for Pawn, which would be to some extent similar to the string library in C++ standard libraries. Some of the features would be the dynamic nature (i.e. no need to define string lengths), and the ability to use overloaded operators, such as + and =. If the concept proves to be useful and possible to implement, I'll continue adding more functionality to the library.

The library is still in early stages, but some basic functionality is already there. The source is available here:, and the basic concept is illustrated in pawn/example.pwn file.

Now to the issue: The issue I'm currently facing involves the assignment operator, as I couldn't really think of a way to get it working properly. Right now it works fine when initialising a string, but it works incorrectly when setting the value of an existing string. String() function returns a reference to the data, which is then assigned to the variable. This is how it should be when initialising the string, but not when working on an existing string. The issue arises when the assignment operator is used on an existing string, which breaks the references to the strings. The code below illustrates the issue:

pawn Code:
new String:a = String("This is the first string."); // Variable a is set to value 0 (reference to the data)
new String:b = String("This is the second string."); // Variable b is set to value 1

// Variable a is set to reference the data of string b
// This means that both variables a and b now reference to the data of b (1)
a = b;
// Consequently, data of variable a (0) is no longer accessible
// Not only is this a memory leak, but modifying the data of a applies to the data of b and vice versa

// The desired functionality would be to set the data of a (0) to equal the data of (b), which can be achieve accordingly:
StringCopy(a, b);

// Being force to use this function, however, makes the library far less easy to use, and greatly diminishes its benefits
// Using the assignment operator would be much easier and cleaner
So what I'd like to achieve is to have the assignment operator to act similarly to StringCopy when used on an existing string, while maintaining the ability to initialise the string. StringCopy does not update the references, but simply modifies the data of the string. I am not quire sure as to which approach I should take, or whether or not it is possible at all.

Any help is appreciated and all ideas are welcome

Forum Jump:

Users browsing this thread: