The answer
"Calling a non-virtual function will use the function from the same class as the pointer type, regardless of whether the object was actually created as some other derived type. Whereas calling a virtual function will use the function from the original allocated object type, regardless of what kind of pointer you're using."
was the best to me in the question link
What are the differences between overriding virtual functions and hiding non-virtual functions?
However, I still don't see the benefits of making a function virtual. Why not just make it concrete and override the function when necessary?
All the answers in your link are pretty complicated, since they actually answer more questions than actually asked :-)
I try to make it easier (lets hope for the best):
The concept of a virtual function allows you to guarantee that whatever pointer you use (see the example in the link Parent* p2 or Child* cp) on a class with some inheritance involved, it will always call the "youngest" child's implementation in the inheritance chain.
Example: If you have "child -> parent" and "grandchild -> child -> parent" with exact same function f2() definitions and all virtual, you can now assume that "grandchild::f2" is called in all circumstances. If you omitted the "virtual" keyword in your parent, you would have different functions being called, depending on which pointer you use to access the instance.
So. What is this useful for? Imagine you have a template based collection and want to put children inside the collection that is defined as parent-type collection list<Parent*>. If you now call a function on an element you fetch from the list, you can expect the child's function (definition) to be called! If you omit the "virtual" keyword in the f2() definition, the parents function is going to be called, which might be unexpected/undesired in most cases.
Any better? :-)
Related
defmodule HelloWeb.Router do
use HelloWeb, :router
scope "/", HelloWeb do
get("/", PageController, :index)
end
end
In this example, why isn't the controller's function passed directly, like get("/", PageController.index)?
I think there are two reasons for this. The first is in how the module name becomes known. In your example, you have a scope for HelloWeb, and then a get endpoint in PageController. This actually calls the HelloWeb.PageController module.
The second reason, which I think is more important here, is because the function is not actually called directly. When you use HelloWeb, :controller, it defines an action/2 function for you in your module. This action/2 function is what gets called. It just calls the function that you specified.
This may seem like it is needlessly complex. But it allows us to define your own action/2 function within your module to override the one provided by phoenix. Maybe all of the actions within a given module need some record(s) pulled from a database. This is where you could do that and put it within the assigns of the connection.
I want to find some ACSL annotation that can be applied to a function or function pointer to indicate that it has the property of referential transparency. Some way to say "this function will always return the same value when given the same arguments". So far I haven't found any such way. Can anyone point me to a way to express that?
Maybe some way to refer to an arbitrary logic function? If I could name an unknown logic boolean uknown_function(void* a, void* b) = /* this is unkown */; then I could document a function as having a postcondition that it's \result is equal to this arbitrary/unknown logic function?
The larger context is trying to do type-erased comparisons. I want to generally express the concept of "the user has given me void*s to work with and a bool (*)(void const*, void const*) to compare them with, and the user is guaranteeing to me that the function provided really is a strict partial order over whatever those pointers point to." If I had that, then I could start to describe properties of these type-erased objects being sorted, for example.
There is indeed no direct possibility to do that in ACSL: a function contract only specifies what happens during a single call of the function. You could indeed rely on a declared but left undefined logic function, with a reads clause that specifies the part of the C memory state that the function will need to compute its result, e.g.
/*# logic boolean unknown_function{L}(int* a, int* b) reads a[0 .. 1], b[2 .. 3]; */
but if you work with void *, without knowing the size of the underlying objects, this might be tricky to specify: unless the result of unknown_function relies solely on the value of the pointer, and not the content of the pointed object, in which case you don't need that reads trick.
Note in addition that contracts over function pointers are not supported yet, which will probably be an issue for what you intend to do if I understand correctly your last paragraph.
Finally, you might be interested in an upcoming plug-in, RPP, that proposes a way to specify, prove, and use properties relating several calls of one or more C function(s). It is described here and here, and a public release should happen in a not-too-distant future.
I've been wondering how delegated properties ("by"-Keyword) work under-the-hood. I get that by contract the delegate (right side of "by") has to implement a get and setValue(...) method, but how can that be ensured by the compiler and how can those methods be accessed at runtime? My initial thought was that obviously the delegates must me implementing some sort of "SuperDelegate"-Interface, but it appears that is not the case. So the only option left (that I am aware of) would be to use Reflection to access those methods, possibly implemented at a low level inside the language itself. I find that to be somewhat weird, since by my understanding that would be rather inefficient. Also the Reflection API is not even part of the stdlib, which makes it even weirder.
I am assuming that the latter is already (part of) the answer. So let me furthermore ask you the following: Why is there no SuperDelegate-Interface that declare the getter and setter methods that we are forced to use anyway? Wouldn't that be much cleaner?
The following is not essential to the question
The described Interface(s) are even already defined in ReadOnlyProperty and ReadWriteProperty. To decide which one to use could then be made dependable on whether we have a val/var. Or even omit that since calling the setValue Method on val's is being prevented by the compiler and only use the ReadWriteProperty-Interface as the SuperDelegate.
Arguably when requiring a delegate to implement a certain interface the construct would be less flexible. Though that would be assuming that the Class used as a Delegate is possibly unaware of being used as such, which I find to be unlikely given the specific requirements for the necessary methods. And if you still insist, here's a crazy thought: Why not even go as far as to make that class implement the required interface via Extension (I'm aware that's not possible as of now, but heck, why not? Probably there's a good 'why not', please let me know as a side-note).
The delegates convention (getValue + setValue) is implemented at the compiler side and basically none of its resolution logic is executed at runtime: the calls to the corresponding methods of a delegate object are placed directly in the generated bytecode.
Let's take a look at the bytecode generated for a class with a delegated property (you can do that with the bytecode viewing tool built into IntelliJ IDEA):
class C {
val x by lazy { 123 }
}
We can find the following in the generated bytecode:
This is the field of the class C that stores the reference to the delegate object:
// access flags 0x12
private final Lkotlin/Lazy; x$delegate
This is the part of the constructor (<init>) that initialized the delegate field, passing the function to the Lazy constructor:
ALOAD 0
GETSTATIC C$x$2.INSTANCE : LC$x$2;
CHECKCAST kotlin/jvm/functions/Function0
INVOKESTATIC kotlin/LazyKt.lazy (Lkotlin/jvm/functions/Function0;)Lkotlin/Lazy;
PUTFIELD C.x$delegate : Lkotlin/Lazy;
And this is the code of getX():
L0
ALOAD 0
GETFIELD C.x$delegate : Lkotlin/Lazy;
ASTORE 1
ALOAD 0
ASTORE 2
GETSTATIC C.$$delegatedProperties : [Lkotlin/reflect/KProperty;
ICONST_0
AALOAD
ASTORE 3
L1
ALOAD 1
INVOKEINTERFACE kotlin/Lazy.getValue ()Ljava/lang/Object;
L2
CHECKCAST java/lang/Number
INVOKEVIRTUAL java/lang/Number.intValue ()I
IRETURN
You can see the call to the getValue method of Lazy that is placed directly in the bytecode. In fact, the compiler resolves the method with the correct signature for the delegate convention and generates the getter that calls that method.
This convention is not the only one implemented at the compiler side: there are also iterator, compareTo, invoke and the other operators that can be overloaded -- all of them are similar, but the code generation logic for them is simpler than that of delegates.
Note, however, that none of them requires an interface to be implemented: the compareTo operator can be defined for a type not implementing Comparable<T>, and iterator() does not require the type to be an implementation of Iterable<T>, they are anyway resolved at compile-time.
While the interfaces approach could be cleaner than the operators convention, it would allow less flexibility: for example, extension functions could not be used because they cannot be compiled into methods overriding those of an interface.
If you look at the generated Kotlin bytecode, you'll see that a private field is created in the class holding the delegate you're using, and the get and set method for the property just call the corresponding method on that delegate field.
As the class of the delegate is known at compile time, no reflection has to happen, just simple method calls.
Is it possible to declare a tuple struct where the members are hidden for all intents and purposes, except for declaring?
// usize isn't public since I don't want users to manipulate it directly
struct MyStruct(usize);
// But now I can't initialize the struct using an argument to it.
let my_var = MyStruct(0xff)
// ^^^^
// How to make this work?
Is there a way to keep the member private but still allow new structs to be initialized with an argument as shown above?
As an alternative, a method such as MyStruct::new can be implemented, but I'm still interested to know if its possible to avoid having to use a method on the type since it's shorter, and nice for types that wrap a single variable.
Background
Without going into too many details, the only purpose of this type is to wrap a single type (a helper which hides some details, adds some functionality and is optimized away completely when compiled), in this context it's not exactly exposing hidden internals to use the Struct(value) style initializing.
Further, since the wrapper is zero overhead, its a little misleading to use the new method which is often associated with allocation/creation instead of casting.
Just as it's convenient type (int)v or int(v), instead of int::new(v), I'd like to do this for my own type.
It's used often, so the ability to use short expression is very convenient. Currently I'm using a macro which calls a new method, its OK but a little awkward/indirect, hence this question.
Strictly speaking this isn't possible in Rust.
However the desired outcome can be achieved using a normal struct with a like-named function (yes, this works!)
pub struct MyStruct {
value: usize,
}
#[allow(non_snake_case)]
pub fn MyStruct(value: usize) -> MyStruct {
MyStruct { value }
}
Now, you can write MyStruct(5) but not access the internals of MyStruct.
I'm afraid that such a concept is not possible, but for a good reason. Each member of a struct, unless marked with pub, is admitted as an implementation detail that should not raise to the surface of the public API, regardless of when and how the object is currently being used. Under this point of view, the question's goal reaches a conundrum: wishing to keep members private while letting the API user define them arbitrarily is not only uncommon but also not very sensible.
As you mentioned, having a method named new is the recommended approach of doing that. It's not like you're compromising code readability with the extra characters you have to type. Alternatively, for the case where the struct is known to wrap around an item, making the member public can be a possible solution. That, on the other hand, would allow any kind of mutations through a mutable borrow (thus possibly breaking the struct's invariants, as mentioned by #MatthieuM). This decision depends on the intended API.
This happens to me time and again: I define the class and forget that I wanted it funcallable or it is, say, Gtk widget class, thus it's metaclass needs to be stated. Once it is defined, however, SBCL doesn't let me change me the metaclass (even if there is no instance of this class). For example, evaluating
(defclass foo ()
((slot-a)))
and then adding a metaclass and re-evaluating:
(defclass foo ()
((slot-a))
(:metaclass gobject:gobject-class))
results in error:
Cannot CHANGE-CLASS objects into CLASS metaobjects.
[Condition of type SB-PCL::METAOBJECT-INITIALIZATION-VIOLATION]
See also:
The Art of the Metaobject Protocol, CLASS [:initialization]
Unfortunately I don't have a copy of The Art of the Metaobject Protocol to check what it says. For now the only way I could figure out is to restart lisp, which can be quite disruptive.
Since I realise the error soon enough, I don't mind dodging the defined class completely by removing it. Questions:
If I have created instances of the class, is there a way to find them to nullify them and get them GCed?
How to remove the class? Something like fmakunbound for functions.
Unfortunately I don't have a copy of The Art of the Metaobject Protocol to check what it says.
Even though I recommend reading the book, you can find some information online. See for example ENSURE-CLASS-USING-CLASS.
How to remove the class?
You can use (SETF FIND-CLASS):
(setf (find-class 'foo) nil)
Or, you can use the fancy slime inspector. You call slime-inspect-defintion while pointing the name of the class. Then, you'll see the name. When you select it, you inspect the symbol naming your class. Then, you can see something like:
It names the class FOO [remove]
Provided FOO only names a class, you can use the bigger hammer:
(unintern 'foo)
If I have created instances of the class, is there a way to find them to nullify them and get them GCed?
No, only the GC has the global view, and for practical reasons, it doesn't generally keep backward references about who references a particular object (and how)1.
There is no global record of all instances of a class unless you introduce your own (weak) hash-table to store them. But if you have kept a record of all of your instances, you can CHANGE-CLASS them. For example, you define:
(defclass garbage () ())
... any previously held reference in your object will be released and the GC has an opportunity to dispose of objects your instances where referencing. And when another object reference an instance of 'garbage, you can update it. Instead of using 'garbage, you could probably change instances of old classes to your new class (the name is the same, but the class object is different).
Note also that CHANGE-CLASS is a generic function.
1. Implementations might offer heap walkers. See for example Heap walkers in Allegro CL.