Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am observing undefined behavior/seg fault when I add the method setValue to ClazzI below. Removing this method eliminates the issue; however, I have not been able to reproduce in a simple example. The below roughly outlines what is being done and it seems the real issue relates to touching the member vector in the non const function.
class AnotherClazz;
using AnotherClazzPtr = std::shared_ptr<AnotherClazz>;
class AnotherClazz {
public:
AnotherClazz(const std::vector<double>& values)
:m_values(values)
{}
std::vector<double> m_values;
};
class ClazzI;
using ClazzPtr = std::shared_ptr<ClazzI>;
class ClazzI {
public:
virtual void setValue(size_t i, double value) = 0;
virtual ClazzPtr clone() const = 0;
virtual ~ClazzI() = default;
};
class Clazz : public ClazzI {
public:
Clazz(const std::vector<double>& values)
:m_values(values)
, m_another(std::make_shared<AnotherClazz>(m_values))
{}
void setValue(size_t i, double value) override {
m_values.at(i) = value;
m_another = std::make_shared<AnotherClazz>(m_values);
}
ClazzPtr clone() const override {
return std::make_shared<Clazz>(m_values);
}
private:
std::vector<double> m_values;
AnotherClazzPtr m_another;
};
Calling clone whilst the setValue function seems to trigger a destructor call which then leads to the below.
Segmentation fault (Invalid permissions for mapped object [0x55a3b0309540])
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
I've identified what the problem was, though it was entirely unrelated to the source and was related to bad symbols that got generated in my build output.
Related
I use Piece class as Map's key.
But when this code ran, error occured Uncaught exception:
C.JSNull_methods.$indexSet is not a function.
class Piece {
int type;
Piece(this.type);
}
void main() {
Map<Piece, int> hand;
hand[Piece(5)] = 5;
if (hand.containsKey(Piece(5))) {
print("contains");
}
print('${hand[Piece(5)]}');
}
In dart-lang, how can I use class as Map's key?
First, the error you got has nothing to do with using types as keys but are before you never initialize the hand variable. So you need to do this:
Map<Piece, int> hand = {};
Now, you will not get the exception but your code will properly not work as expected since hand.containsKey(Piece(5)) will return false and print('${hand[Piece(5)]}') will return null.
This is because the map Map<Piece, int> are not using the Type as key but instead objects of the type Piece. So if we take your code here:
Map<Piece, int> hand = {};
hand[Piece(5)] = 5;
if (hand.containsKey(Piece(5))) {
print("contains");
}
print('${hand[Piece(5)]}');
You are here creating a new object instance of the Piece type each type you are writing "Piece(5)". Since each of this objects will be a separate instance of a Piece then you will not receive the value 5 you have saved because the value 5 has been saved for a different object than you are requesting.
There are multiple solutions for that and I don't know which one are the best for you. But the simple solution in this case is to either only creating one instance of Piece and reuse that:
void main() {
Map<Piece, int> hand = {};
final piece = Piece(5);
hand[piece] = 5;
if (hand.containsKey(piece)) {
print("contains");
}
print('${hand[piece]}');
}
Or make a const constructor for your Piece class so instances with the same arguments are made into the same object. This solution requires that the int type are final since you cannot edit a const constructed object (since it is constant):
class Piece {
final int type;
const Piece(this.type);
}
void main() {
Map<Piece, int> hand = {};
hand[const Piece(5)] = 5;
if (hand.containsKey(const Piece(5))) {
print("contains");
}
print('${hand[const Piece(5)]}');
}
Note that you need to prefix you object instantiation with const like "const Piece(5)" each time you want a instance where you are sure it will returns the same object for the same arguments.
I currently created a new actionScript class, called Quiz.as
// package
// {
// public class Quiz
// {
public var knowledgePoints:int = 10;
public var allQuestions:Array = new Array;
public var questionCorrect:Boolean = false;
public function getTotalScore():int
{
// var totalScore:int = 0;
var totalScore = 0;
for (var i = 0; i < allQuestions.length; i++)
{
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect)
{
knowledgePoints++;
}
else
{
knowledgePoints--;
}
}
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
// }
//}
This solution derived from my original question at: keeping track of a series of simple multiple choice web form answers
But now with the above code I am getting errors in flash console. My latest attempt to fix these errors are with the commented out regions above.
Error 1. Attribute used outside of class.
So I comment out first couple lines, but error continues to point to whatever line is exposed first.
Error 2. 'Int' could not be loaded.
Thanks for any advice,
Your issue is likely the result of using the above code on the timeline in AnimateCC/FlashPro.
Class files (and their corresponding attributes like public/private) need to be in their own actionscript (.as) file.
To create a class file in AnimateCC, go to file -> new and choose ActionScript 3.0 Class. Give it the class name of Quiz (so it matches what you've declared in your code)
Replace the default code with the class file code from your question (you'll need to restore those commented out lines too)
Save the file in the same directory as your .fla
To use your new class file in the timeline, you'd do something like this:
var quiz:Quiz = new Quiz(); //make an instance of your custom class
quiz.allQuestions.push(whateverAQuestionIs); //add a question to your array
trace(quiz.getTotalScore()); //trace out the total score
If you want to use that code in the timeline and forgo using a class file, you'll just need to remove the 4 public keywords (in addition to the lines you've already commented out)
I have the following original C code:
static guint event_signal_id;
struct _MatrixClientIface {
void (*event)(MatrixClient *client, const gchar *room_id, const JsonNode *raw_event, MatrixEvent *event);
}
static void
matrix_client_default_init(MatrixClientIface *iface)
{
event_signal_id = g_signal_new("event",
MATRIX_TYPE_CLIENT,
G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
G_STRUCT_OFFSET(MatrixClientIface, event),
NULL, NULL, _matrix_marshal_VOID__STRING_BOXED_OBJECT,
G_TYPE_NONE, 3,
G_TYPE_STRING,
JSON_TYPE_NODE,
MATRIX_TYPE_EVENT);
}
void
matrix_client_incoming_event(MatrixClient *client,
const gchar *room_id,
const JsonNode *raw_event,
MatrixEvent *event)
{
GQuark equark;
equark = g_type_qname(G_TYPE_FROM_INSTANCE(event));
g_signal_emit(client,
event_signal_id, equark,
room_id, raw_event, event);
}
Now I want to transform this to Vala; however, I cannot find a tutorial about emitting signals (defining them appears in tutorials many times). I found GLib.Signal.emit() in the docs, but there is no example there on how to get a GLib.Signal object.
My current interface looks like this:
namespace Matrix {
public interface Client : GLib.Object {
public virtual signal void
#event(string? room_id, Json.Node raw_event, Matrix.Event matrix_event)
{
Quark equark = #event.get_type().qname();
#event.emit(room_id, raw_event, matrix_event);
}
}
This obviously doesn’t work. The questions are:
Am I defining the emitter as I should, at all?
If so, how do I actually emit the event signal with equark as a detail?
I cannot find a tutorial about emitting signals (defining them appears in tutorials many times).
I suspect that you actually have, but missed the significance because emitting signals is so easy. For example, see the Signals section of the Vala Tutorial; emitting is shown (t1.sig_1(5);).
I found GLib.Signal.emit() in the docs, but there is no example there on how to get a GLib.Signal object.
GLib.Signal.emit is the low-level way of emitting signals, and there is basically no reason to ever use it from Vala.
Note that the first argument to emit is a pointer. There are few exceptions (most notably libxml), but for the most part if you ever encounter a pointer in Vala, you're doing something wrong. For the most part that also holds true for quarks; virtually everything you would use quarks for has syntax support in Vala.
Am I defining the emitter as I should, at all?
Nope. For starters, get rid of the method body and the "virtual".
If so, how do I actually emit the event signal with equark as a detail?
All you need is something like this:
namespace Matrix {
public class Client : GLib.Object {
[Signal (detailed = true)]
public signal void #event (string? room_id, Json.Node raw_event, Matrix.Event evt);
}
To emit it, you can do something like:
client.#event[evt.get_type().name()](room_id, raw_event, evt);
To connect:
client.#event[evt.get_type().name()].connect((room_id, raw_event, evt) => {
// Signal with a matching detail received
});
client.#event.connect((room_id, raw_event, evt) => {
// Signal received with *any* value for the detail
});
This question already has answers here:
How does the const constructor actually work?
(5 answers)
Closed 8 years ago.
I've just started to learn dart, but I can't understand const constructor. Can someone illustrate how to use const constructor.
Under what circumstances do I need to use it?
Did you happen to stumble upon Chris Strom's post about constant constructors? What Chris Strom does in the article is an explanation of final fields, but scroll down to the comments section and there's a nice clarification of constant constructors from a certain Lasse.
Const objects are used in annotations:
import 'dart:mirrors';
class Foo{
final name;
const Foo(this.name);
}
#Foo("Bar")
class Baz{}
void main() {
ClassMirror cm = reflectClass(Baz);
print(cm.metadata.first.getField(#name).reflectee); // prints Bar
}
Why const objects were introduced(from the dev team):
Why does Dart have compile time constants?
Also they can provide extra optimization. For example, my dar2js experiment:
Does dart2js optimize const objects better?
Some specifics:
class Foo{
final baz;
const Foo(this.baz);
}
void main() {
//var foo = const Foo({"a" : 42}); //error {"a" : 42} is a mutable Map
var foo = const Foo(const {"a" : 42}); //ok
//foo.baz["a"] = 1; //error Cannot set value in unmodifiable Map
var bar = new Foo({"a" : 42}); //ok
//bar.baz = {"c" : 24}; //error NoSuchMethodError: method not found: 'baz='
bar.baz["a"] = 1; //ok;
}
If class has only const constructor you still can create mutable object with new
final baz is immutable reference. But since bar is mutable, you can change baz object.
Given the following class, Dart Editor (build 5549) gives me some conflicting feedback (per the comments in the constructor body):
class Example {
final int foo;
Example() :
foo = 0
{
foo = 1; // 'cannot assign value to final variable "foo"'
this.foo = 2; // ok
}
}
Even more confusingly, it will happily generate equivalent (working) javascript for both lines. The situation seems to be the same with methods as it is with the constructor; this especially leads me to believe that it was intended to be disallowed in both cases.
The Dart Style Guide suggests using public final fields instead of private fields with public getters. I like this in theory, but non-trivial member construction can't really go into the initializer list.
Am I missing a valid reason for the former to be reported as an error while the latter is not? Or should I be filing a bug right now?
This is surely a bug in the JavaScript generator if you run the following in the Dart VM:
main() {
new Example();
}
class Example {
final int foo;
Example() : foo = 0 {
foo = 1; // this fails in the dart vm
this.foo = 2; // this also fails in the dart vm
}
}
then it refuses to execute both the line foo = 1 and this.foo = 2. This is consistent with the spec which requires (if I read it correctly) that final fields to be final in the constructor body.