Declarations, definitions, initializations in C, C++, C#, Java and Python [closed] - initialization

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What do the terms mean in each of the above languages? Why do the languages differ (wherever they do, if at all they do) in this respect?

C/C++:
A declaration is a statement that says "here is the name of something and the type of thing that it is, but I'm not telling you anything more about it".
A definition is a statement that says "here is the name of something and what exactly it is". For functions, this would be the function body; for global variables, this would be the translation unit in which the variable resides.
An initialization is a definition where the variable is also given an initial value. Some languages automatically initialize all variables to some default value such as 0, false, or null. Some (like C/C++) don't in all cases: all global variables are default-initialized, but local variables on the stack and dynamically allocated variables on the heap are NOT default initialized - they have undefined contents, so you must explicitly initialize them. C++ also has default constructors, which is a whole nother can of worms.
Examples:
// In global scope:
extern int a_global_variable; // declaration of a global variable
int a_global_variable; // definition of a global variable
int a_global_variable = 3; // definition & initialization of a global variable
int some_function(int param); // declaration of a function
int some_function(int param) // definition of a function
{
return param + 1;
}
struct some_struct; // declaration of a struct; you can use pointers/references to it, but not concrete instances
struct some_struct // definition of a struct
{
int x;
int y;
};
class some_class; // declaration of a class (C++ only); works just like struct
class some_class // definition of a class (C++ only)
{
int x;
int y;
};
enum some_enum; // declaration of an enum; works just like struct & class
enum some_enum // definition of an enum
{
VALUE1,
VALUE2
};
I'm not as familiar with the other languages you asked about, but I believe they don't make much of a distinction between declarations and definitions. C# and Java have default initialization for all objects - everything is initialized to 0, false, or null if you don't explicitly initialize it. Python is even more lax, since variables don't need to be declared before they're used. Since bindings are resolved at runtime, there's no real need for declarations of functions, either.

Related

Qt/QML: std::vector<int> handling

Edit: problem was with 5.6 only, which has a reduced set of supported "native" types according to https://doc.qt.io/qt-5.6/qtqml-cppintegration-data.html vs the latest version ...
According to this page: https://doc.qt.io/qt-5/qtqml-cppintegration-data.html, std::vector<int> is suppported by QML if registered with qRegisterMetaType() and exposed/accessed as a property. However, I cannot get this to work.
My class (which can be instantiated by QML, so this level works) has declarations like:
// prop decl
Q_PROPERTY(std::vector<int> myVector READ myVector NOTIFY myVectorChanged)
// read accessor
Q_INVOKABLE std::vector<int> recordTime() const;
// signal (in signal section)
void myVectorChanged();
Registration via
qRegisterMetaType<std::vector<int> >("std::vector<int>");
When I push something into the vector and try accessing myVector.length or myVector.size, it returns 'undefined' (size() is not callable). How do I iterate over the elements? The page linked above says "Certain C++ sequence types are supported transparently in QML to behave like JavaScript Array types" (and mentions std::vector<int> in the list), so I expected length and index access to work.
The documentation says this container will be converted to a JS array automatically. You don't need to register anything.
Of course, the conversion will be a copy, so modifying it will not modify the original array, and the way you use that is the same way you use a regular JS array. It definitely should have a length (not length()) property and support index access via [].
Update:
After your stories of failure I decided to actually run a simple test:
class Test : public QObject {
Q_OBJECT
public slots:
std::vector<int> test() { return std::vector<int> {1, 2, 3, 4, 5, 6, 7}; }
};
// in main.cpp
qmlRegisterType<Test>("Core", 1, 0, "Test");
// in qml
Test {
Component.onCompleted: {
var t = test()
console.log(t.length, t) // qml: 7 [1,2,3,4,5,6,7]
}
}
As you can see, it gives the expected output, no need to register anything whatsoever.
IIRC there was a problem with Qt that for some reason caused those automatic conversions to not kick in when you use a Q_PROPERTY interface. I suppose that issue is still valid, the solution thankfully is to simply not use a property but a simple return value.
If your problems persist, I suggest to carefully examine your code, or if necessary, clean and rebuild your project, because the conversion is definitely working out as expected, aside from the property related issue.

Counting template instantiations with inline variables

Let's say we want to count the number of a template instantiations for a certain template.
In C++17 I think I can do it like this:
static inline size_t my_template_count = 0;
template <typename T>
struct my_template {
static inline char count_me = []{ my_template_count++; return 0; }();
// mention count_me in all functions.
};
My questions are:
- Will it work?
- Can there be a race condition on the total_count?
(Reading while DLL loading, something like that).
Update: as #n.m. correctly pointed out - I have to reference the variable.
It's ok for my usecase to include (void)count_me in all constructors, destructor, static methods etc. And if none of them are used, it's ok to ignore the instantiation.
A similar question came up in a discussion with Sean Parent.
He said:
Not thread safe because deferred dynamic initialization is not guaranteed to happen on the main thread cppreference

To avoid creation of std::shared_ptr from raw pointers? [duplicate]

This question already has answers here:
How do I call ::std::make_shared on a class with only protected or private constructors?
(19 answers)
Closed 7 years ago.
I am currently following the book **Effective Modern C++" and it says
Avoid creating std::shared_ptrs from variables of raw pointer type.
And I am convinced with the explanation so that I, too, agree on that we need to avoid. But there is an exception I encountered.
class Person
{
protected:
Person();
public:
static std::shared_ptr<Person> getShared()
{
return std::shared_ptr<Person>(new Person());
}
When we hide the default constructor std::make_shared cannot do its job. That's why I use a static method in the example above. My question is
Is this best I can do about the situation?
I still use raw pointer to create a shared_ptr, but in this case I can predict what may happen to this pointer. Does this practice still threaten my code?
Although this might not be the best way to do that, one way to do get your constructor protected to a certain degree but still make it callable by std::make_shared is the following:
class MyClass
{
protected:
struct ConstructorGuard {};
public:
MyClass(ConstructorGuard g) {}
static std::shared_ptr<MyClass> create()
{
return std::make_shared<MyClass>(ConstructorGuard());
}
};
The constructor itself is public, but it cannot be called from outside the class, because it requires an argument of type ConstructorGuard which is a protected nested class, such that only the class itself (and the derived classes) can construct such an object to pass it to the constructor.

Canceling a Flex two way binding change [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What's the best way(s) to implement a "cancel" button feature (say for a dialog which uses some shared model & two way bindings)?
The obvious solution of copying every field in the object into a "revert" obj defeats the purpose (might as well just set each value manually upon a save). I've used ObjectUtil.copy/clone in the past, but I'm not aware of all the caveats with more complex data types which contain lists, etc. (Deep vs. Shallow copy)
Are there any better/other methods?
Please read AS3 - Clone an object
For complex Value Objects will be good using the ByteArray class for creation clone.
But make sure that you are using [RemoteClass] or registerClassAlias for all classes that you what to clone.
I've had issues with the builtin ObjectUtil.clone() and ObjectUtil.copy() methods. Thats why I created my own version that uses introspection instead using ByteArray.
One method copies all properties from one instance to another:
private static const rw:String = "readwrite";
public static function copyProperties(source:Object, target:Object):void {
if (!source || !target) return;
//copy properties declared in Class definition
var sourceInfo:XML = describeType(source);
var propertyLists:Array = [sourceInfo.variable, sourceInfo.accessor];
for each (var propertyList:XMLList in propertyLists) {
for each (var property:XML in propertyList) {
if (property.#access == undefined || property.#access == rw) {
var name:String = property.#name;
if (target.hasOwnProperty(name)) target[name] = source[name];
}
}
}
//copy dynamic properties
for (name in source)
if (target.hasOwnProperty(name))
target[name] = source[name];
}
The other creates a complete clone of an object by copying all its properties to a new instance:
public static function clone(source:Object):* {
var Clone:Class = getDefinitionByName(getQualifiedClassName(source)) as Class;
var clone:* = new Clone();
copyProperties(source, clone);
return clone;
}

Synchronizing arbitrary properties in an object transparently in D

Let's say I have a class like so:
class Gerbil{
int id;
float x,y,z;
}
Let's further say this is part of a real-time simulation where I have a server/client setup and I change a property on the server-side:
//...
gerbil.x = 9.0;
//...
Now I want to send over this change to the client to synchronize the world state. However, the problem is I have potentially vast amounts of gerbils, and these gerbils also potentially have long lists of properties—not just x,y,z as depicted here.
My question is: Is there a way we can intercept these property assignments, transparently, and compile a diff from them?
From reading the D reference I got the impression opAssign might be the right thing, only there's actually no examples of how to use it? (D Ref. / opAssign) I suppose it would look something like this, but I'm just shooting from the hip:
void opAssign(string name)(float val){ //Just guessing here
if(name in floatProps){
if(isServer){
changedProps.push(this.id, name, val);
}
floatProps[name] = val;
}
}
And then opAssign would be called when we do:
gerbil.x = 9.0; //Same as gerbil.opAssign!("x")(9.0) ??
Apart from possibly wrong syntax, is this a step in the right direction? What is the right syntax? What about performance? It looks like it could be quite slow? Is there a faster, more "direct" way of this?
What I'd really like to avoid here are elaborate setups like:
gerbil.incProp(Prop.X, 9.0);
Thanks for your time.
Building on Jonathan's answer, I use code like this in a number of my libraries:
public template property(string name, T) {
mixin(`protected T _`~name~`;` ~
propertyGetter!(name, T) ~ propertySetter!(name, T));
}
public template property(string name, T, T def)
{
mixin(`protected T _`~name~` = `~def.stringof~`;` ~
propertyGetter!(name, T) ~ propertySetter!(name, T));
}
template propertyGetter(string name, T) {
enum propertyGetter = `public T `~name~`(){ return _`~name~`; }`;
}
template propertySetter(string name, T) {
enum propertySetter = `public typeof(this) `~name~`(T value){ _`~name~` = value;`~
`/* notify somebody that I've changed here */`~
`return this; }`;
}
The mixin strings are a bit ugly, but they preserve the proper line count.
I add properties to my classes like this:
class Gerbil {
mixin property!("id", int);
mixin property!("x", float);
mixin property!("y", float, 11.0); // give this one a default value
}
If you wanted, you could add some code to the propertySetter template that notified some sort of monitor that it had changed (passing id, property name, and new value). Then the monitor could transmit this info to a corresponding monitor on the server side who would find the object with proper id and set the specified property to the new value.
Overloading opAssign() is like overloading the assignment operator in C++. It's for assigning to the object itself, not one of its members. It's really not going to do what you want. I believe that the closest that you're going to get is properties:
class Gerbil
{
public:
#property int id()
{
return _id;
}
#property id(int newID)
{
//... Do whatever interception you want.
_id = newID;
}
#property float x()
{
return _x;
}
#property x(float newX)
{
//... Do whatever interception you want.
_x = newX;
}
#property float y()
{
return _y;
}
#property y(float newY)
{
//... Do whatever interception you want.
_y = newY;
}
#property float z()
{
return _z;
}
#property z(float newZ)
{
//... Do whatever interception zou want.
_z = newZ;
}
private:
int _id;
float _x, _y, _z;
}
#property enables property syntax so that you can use the function as if it were a variable. So,
//...
auto copyOfGerbilX = gerbil.x; //translates to gerbil.x()
gerbil.x = 9.0; //translates to gerbile.x(9.0)
//...
is now legal even though x is a function rather than a variable. You can insert whatever special handling code you want in the functions. And because the syntax used to access the variables is just as if they were public member variables, you can freely refactor your code to switch between having them be properties or public member variables in your class definition (assuming that you haven't tried to do something like take their address, since that doesn't mean the same thing for a variable as a function).
However, if what you're looking for is a generic way to not have to do all of those functions yourself, there is no direct construct for it. I believe that you could do it with compile-time reflection and string mixins or template mixins which would look at the list of your variables and then generate each of the property functions for you. However, then the extra handling code would have to be essentially the same for each function, and you'd have to be careful that the generated code was really what you wanted. I'm sure that it's feasible, but I'd have to work on the problem for a bit to produce a workable solution.
To generate such code, you'd need to look at __traits and std.traits for the compile-time reflection and at template mixins and string mixins for the code generation. I'd think twice about generating the code like that though rather than writing it by hand. It should be quite doable, but it won't necessarily be easy, debugging it could be entertaining, and if you're going to have to be fairly good with D templates and mixins to get it right.
But essentially, what you're looking for is to use #property functions so that you can add your handler code and then possibly use compile-time reflection along with mixins to generate the code for you, but generating code like that is a fairly advanced technique, so you may want to wait to try that until you're more experienced with D.

Resources