On 7/1/21 8:26 PM, someone wrote:
... just wondering:

I am writing pretty trivial code, nothing out of the ordinary, and attempted to check how much of it could be marked safe ...

It should be quite a bit.


- Lots of tiny common library functions are pretty easy

- Getter/Setter properties are easy too

- almost all this() constructors are a no-go providing you do something in-between with the parameters until you assign them back to the target variables; eg: you have a char parameter (that you need to do something with it) that needs to be assigned to a class/structure string member variable and then it needs a cast ... but no castings are allowed with @safe

This doesn't make a lot of sense, lots of constructors are safe.

And casting is OK as long as it's safe, including class downcasts.


But when you start attempting to declare @safe chunks of code that actually DO things ... well, it seems end-of-the-story.

This is why you encapsulate the unsafe parts in @trusted functions.

The classic example is the posix `read` and `write` functions. The function `int read(int fd, void *data, int len)` is not safe, nor can it be trusted. But a trusted wrapper is possible: `@trusted int readSafe(int fd, ubyte[] data)`. Now all of a sudden, safe functions have more utility.


Declaring @safe void() main() {...} as I was advised in some previous post (to avoid declaring @safe everywhere) is almost impossible unless you are doing the hello world app.

The point is to mark main @safe, and then fix whatever things that aren't safe that it calls to provide a safe interface.


I would love to hear how you, I mean the community, approach code safeness ?

Any function I want to make safe, I mark it as @safe. Then I fix the compiler complaints until it compiles (including functions that it calls), using as little @trusted code as possible.

-Steve

Reply via email to