Class with static linkage - class

If I recall correctly, static linkage means that a variable or function is local to its compilation unit. Meaning that there could be variables or functions with the same name and parameters in other compilation units.
I want this for a class.
Let's say I have multiple compilation units that need to ensure proper deletion at exit. So I use atexit handlers. But every compilation unit should put its own atexit-handler into place.
I did this by making a class like this:
class Init {
private:
static Init* self;
Init() {
std::atexit(Init::cleanup);
}
static void cleanup() {
// Do cleanup
}
};
Init* Init::self = new Init;
But if I have multiple classes called Init in various CUs the linker gets confused. And the compiler won't let me do static class Init {...}.
How do I archive my cleanup (if possible with classes that are called Init)?

You can put your class into an unnamed namespace.
Then, although types don't have linkage, the same effect is borne.
// Everything inside here is unique to this TU
namespace {
class Init { /** whatever **/ };
Init* Init::self = new Init;
}
int main()
{
// "Init" in here will refer to that which you created above
}

Related

why we should use static keyword in dart in place of abstract?

I m preparing a class in my flutterfire project and their I want to use some method Which can't change further so that I want to know consept of static keyword in Dart ?
"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members.
Static methods
Static methods (class methods) don’t operate on an instance, and thus don’t have access to this. They do, however, have access to static variables.
void main() {
print(Car.numberOfWheels); //here we use a static variable.
// print(Car.name); // this gives an error we can not access this property without creating an instance of Car class.
print(Car.startCar());//here we use a static method.
Car car = Car();
car.name = 'Honda';
print(car.name);
}
class Car{
static const numberOfWheels =4;
Car({this.name});
String name;
// Static method
static startCar(){
return 'Car is starting';
}
}
static keyword in dart used to declare a variable or method that belongs to just the class not the instants which means the class has only one copy of that variable or method and those static variables(class variables) or static methods(class methods) can not be used by the instances created by the class.
for example if we declare a class as
class Foo {
static String staticVariable = "Class variable";
final String instanceVariable = "Instance variable";
static void staticMethod(){
print('This is static method');
}
void instanceMethod(){
print('instance method');
}
}`
the thing here to remember is static variables are created only once and every instance crated by the class has different instance variables. therefore you can not call static variables form the class instances.
following codes are valid,
Foo.staticVariable;
Foo().instanceVariable;
Foo.staticMethod();
Foo().instanceMethod();
there for following codes will give errors
Foo().staticVariable;
Foo.instanceVariable;
Foo().staticMethod;
Foo.instanceMethod
Use of static variables and methods
you can use static variables when you have constant values or common values that are relevant for the class.
you can read more here - https://dart.dev/guides/language/language-tour#class-variables-and-methods

Can I define a reusable subroutine/function/method within a Cake script?

I'm trying out Cake (C# Make). So far all the examples and documentation have the script file declaring all of its code inside delegates, like this:
Task("Clean")
.Does(() =>
{
// Delete a file.
DeleteFile("./file.txt");
// Clean a directory.
CleanDirectory("./temp");
});
However, one of the reasons I'm interested in using Cake is the possibility of writing my build scripts in a similar way to how I write code, as the scripts use a C#-based DSL. Included in this possibility is the ability to separate code that I use into methods (or functions / subroutines, whatever terminology is appropriate) so I can separate concerns and reuse code. For example, I may want to run the same set of steps for a multiple SKUs.
While I realize that I could create my own separate DLL with Script Aliases, I would like to avoid having to recompile a separate project every time I want to change these bits of shared code when working on the build script. Is there a way to define, inline with the normal build.cake file, methods that can still run the Cake aliases (e.g., DeleteFile) and can themselves be called from my Cake tasks?
Cake is C#, so you can create classes, methods, just like in regular C#
I.e. declare a class in a cake file
public class MyClass
{
public void MyMethod()
{
}
public static void MyStaticMethod()
{
}
}
and then use it a script like
var myClass = new MyClass();
// Call instance method
myClass.MyMethod();
//Call static method
MyClass.MyStaticMethod();
The Cake DSL is based on Roslyn scripting so there are some differences, code is essentially already in a type so you can declare a method without a class for reuse
public void MyMethod()
{
}
and then it can be called like a global methods
MyMethod();
A few gotchas, doing class will change scoping so you won't have access to aliases / context and global methods. You can get around this by i.e. passing ICakeContext as a parameter to class
public class MyClass
{
ICakeContext Context { get; }
public MyClass(ICakeContext context)
{
Context = context;
}
public void MyMethod()
{
Context.Information("Hello");
}
}
then used like this
// pass reference to Cake context
var myClass = new MyClass(Context);
// Call instance method which uses an Cake alias.
myClass.MyMethod();
You can have extension methods, but these can't be in a class, example:
public static void MyMethod(this ICakeContext context, string message)
{
context.Information(message);
}
Context.MyMethod("Hello");

I can I get similar end results to "protected" access of C# but in Swift?

My goal is to write a class and have a function in it that contains code to run (in a run() function for example) in a background thread. Here are some requirements of my class (and related classes):
Ensure that when I write the run() function, the code is guaranteed to run in a background thread without the programmer needing to know anything about threading and without having to remember to call any other code in that run() function related to the threading.
Have a completion function function that is set elsewhere that is called when the background thread is finished its processing without the programmer having to write code in this run() function to make the call.
Pretty much let someone derive a class from some base class and then write their background code in it in a run() function without writing anything else related to managing the background thread, completion function, etc.
Here's the code I might write in C#, in two DIFFERENT files:
class MyBase
{
public Action completionFunction = NULL;
public void begin()
{
RunInOtherThread( run ); // This function call is just pseudo-code for running that run() function in a background thread.
if( completionFunction != Null )
completionFunction();
}
virtual protected void run() = 0 // so this class cannot be instantiated
{
}
};
And in the other file:
class MySpecificClass : MyBase
{
override void run()
{
// Do important stuff here!
}
};
I do not know how to meet my requirements in Swift. They left out the "protected" level of protection for reasons that do not make sense to me (like thinking that I could not just fire a programmer that screwed up the code by exposing a base class protected function through a public function).
I am not familiar enough with some of the features of Swift to get these results. I do not need to have the classes work like the C# code even though it is a pretty good solution for me and my C# programmers.
How can I meet my requirements Swift?
BTW, I have seen Q&A about this with no reasonable way to fake the protected access level. I don't need to fake it, I just need another way to achieve the goal of hiding code in a derived class from all the world except for the base class, or something like that.
I'd be tempted to use protocols for this, rather than sub-classing. For example:
public protocol MyBase {
// *** This requires any object that conforms to the protocol
// *** to provide these, without specifying what they do
var completionFunction: (() -> ())? {get set}
func run()
}
public extension MyBase {
// *** This extension provides all objects that conform to the
// *** protocol with this function
func begin() {
RunInOtherThread( self.run ) // This function call is just pseudo-code for running that run() function in a background thread.
if let c = self.completionFunction {
c()
}
}
}
public class MySpecificClass: MyBase {
// *** Now, rather than subclassing, we simply conform to the protocol
public var completionFunction: (() -> ())? = nil
public func run() {
// *** No need to `override` - but *must* be supplied
// Do important stuff here!
}
}

Valac won't let me "install_style_property" from a static method

I would like to use Gtk.Widget's ìnstall_style_property () on a widget I'm writing. In the docs, this method is declared as static, so I am wondering why valac still complains that I am calling it from a static method:
public class MyClass : Gtk.Widget {
public static void init () {
ParamSpecDouble _the_property = new ParamSpecDouble
(
"dummy", "dummy", "dummy,
0, double.MAX, 0,
ParamFlags.READWRITE | ParamFlags.STATIC_STRINGS
);
install_style_property (_the_property);
}
}
void main (string? argv) {
Gtk.init (ref argv);
MyClass.init ();
}
The error message:
test.vala:11.9-11.46: error: Access to instance member `Gtk.Widget.install_style_property' denied
If this does not work, what is the preferred pattern to install custom style properties to a custom widget in Gtk? Personally, I would prefer not to have to call an init () before using my widget, but as adding style properties is done per-class instead of per-instance, putting it into the constructor does not seem right, either.
install_style_property() is not static; it's actually a class method. valadoc.org is showing static for some reason; you'll probably have to report that as a bug (if it hasn't already).
class methods operate on a class itself. GObject classes have shared metadata, and these methods modify that metadata. Such metadata should only be modified when the class is first initialized; therefore, the methods should only be called within that class's GObjectClass.class_init() method. In Vala, this is the static construct method:
public class MyClass : Gtk.Widget {
static construct {
ParamSpecDouble _the_property = new ParamSpecDouble
(
"dummy", "dummy", "dummy,
0, double.MAX, 0,
ParamFlags.READWRITE | ParamFlags.STATIC_STRINGS
);
install_style_property (_the_property);
}
}

How non-static is accessible in static context in this program?

I am having confusion with the following code:
class A
{
int x;
static void F(B b) {
b.x = 1; /* Ok,
I want to know how is this ok, in a static block how a non static
instance variables are called because as I know that static block
gets memory at compile time before execution of a single command
while non static at run time and static method accessing a non static
variable which is not created yet please elaborate me on this
*/
}
}
class B: A
{
static void F(B b) {
b.x = 1; // Error, x not accessible
}
}
Nothing gets memory at compile time. Static fields are indeed placed in the static block of memory when the type gets initialized. Call stacks for static methods are allocated at run time exactly like in case of instance methods.
Now, why static methods don't have access to the instance fields. Consider this:
class A {
public int Value;
static int GetValue() {
return Value;
}
}
There you have a class with an instance field and a static method. Now, somewhere else you try this:
var a1 = new A();
a1.Value = 5;
var a2 = new A();
a2.Value = 10;
int result = A.GetValue();
Now, if compiler allowed this, what value would the result get? 5 or 10 or something else? This just doesn't make sense, because static methods are declared for class as a whole and aren't aware of instances of this class. So in the code of static method you don't know how many (if any) instances of this class exist and can't access their instance fields.
Hope this makes a little sense.
Either you changed the code in question a bit or I didn't read very carefully. Seems like it's completely different problem right now. The variable x is indeed not accessible for the class B because of its level of protection (default in C# is private). Class A can modify X because it's declared in class A and visible to its method. Class B can't do it (you must make x protected or public for that).