You can use an inner constructor (eg in the example below, with validation):
let counter = 0
global get_counter() = counter
struct Foo
x::Int
function Foo(x)
x > 0 || error("invalid x")
counter += 1
new(x)
end
end
end
which works like this (note counter is only incremented when you create a valid Foo
):
julia> get_counter()
0
julia> Foo(1)
Foo(1)
julia> get_counter()
1
julia> Foo(-1)
ERROR: invalid x
Stacktrace:
[1] error(::String) at ./error.jl:33
[2] Foo(::Int64) at /tmp/foo.jl:7
[3] top-level scope at REPL[41]:1
julia> get_counter()
1
That said, global mutable state is difficult to reason about and may preclude some compiler optimizations, so it is generally avoided in Julia. Instead of porting code in C++ style, I would recommend finding another solution.