How to add to an existing hash in Ruby

If you have a hash, you can add items to it by referencing them by key: Here, like [ ] creates an empty array, { } will create a empty hash. Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, … Read more

Create an empty object in JavaScript with {} or new Object()?

Objects There is no benefit to using new Object(); – whereas {}; can make your code more compact, and more readable. For defining empty objects they’re technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline – like so: Arrays For arrays, there’s similarly almost no benefit to ever using new Array(); over []; – … Read more

When to use “new” and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are: Some people will say that the use of new decides whether your object is on the heap or the stack, but that is … Read more

creating an array of object pointers C++

Will it work? Yes. However, if possible, you should use a vector: If you have to use a dynamically allocated array then I would prefer this syntax: But forget all that. The code still isn’t any good since it requires manual memory management. To fix that you could to change your code to: And best … Read more

Deleting an object in C++

Isn’t this the normal way to free the memory associated with an object? This is a common way of managing dynamically allocated memory, but it’s not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and … Read more

When should I use the new keyword in C++?

Method 1 (using new) Allocates memory for the object on the free store (This is frequently the same thing as the heap) Requires you to explicitly delete your object later. (If you don’t delete it, you could create a memory leak) Memory stays allocated until you delete it. (i.e. you could return an object that you created using new) The example in the question will leak memory unless … Read more

Why use a new call with a C++ ‘vector’?

Your first statement is not true. The elements in vector<someType> myVector will live until the vector is destroyed. If vector<someType> is a local variable, it will be destroyed automatically when it goes out of scope. You don’t need to call delete explicitly. Calling delete explicitly is error-prone if you take into account that because of exceptions that might be thrown, your delete statement … Read more