Tag Info

Hot answers tagged

41

While the users who complain about rand() and recommend better RNGs are right about the quality of the random numbers, they are also missing the bigger picture. Duplicates in streams of random numbers cannot be avoided, they are a fact of life. This is the lesson of the birthday problem. On a grid of 20 * 20 = 400 possible spawn positions, a duplicate spawn ...


35

Follow the standard - the end is the iterator past the one you want. This allows you to use all the standard algorithms and containers without problem. It also means your users will be able to write the code they always have (eg for (x=startIt; x != endIt; x++) and this will work as expected. If you change this behaviour and set the last iterator to the ...


18

Return a unique_ptr: std::unique_ptr<Vertex> new_vertex(const Options& options) { // do stuff... return std::make_unique<Vertex>(...); } There can only ever be one unique_ptr pointing to a given object (unless you abuse it by casting to a Vertex* and back, anyway). You can't ever copy a unique_ptr, only move it. When a unique_ptr is ...


9

With your convention: every function in the algorithm library should be used changing the upper bound of the range and it can be quite error prone it isn't easy to represent empty sequences (this was Dijkstra's argument in Why Numbering Should Start At Zero). you can easily incur in off-by-one errors (e.g. when you take a partition of a collection). You ...


7

You have class A and you need to use A with C code: A.h #if !defined(A_H) #define A_H class A { public: void set(int); int get() const; private: int a; }; #endif A.cc (to be compiled with c++ compiler) #include "A.h" void A::set(int i) { a = i; } int A::get() const { return a; } Now to access A from C code: Add a wrapper: ...


6

Getting a segmentation fault only happens when you have invoked undefined behaviour. And undefined behaviour means that the normal rules of a programming language don't apply: whatever the run-time system does is by definition OK, and you don't get to complain about it. It might even do the expected thing, just to confuse you. In particular, adding debug ...


6

OO is not about syntax. Just because you use object.function() vs function(object), that doesn't mean you are now "doing OO." OO is about sending messages to objects to inform them about events, without knowing or caring how they will react to those events. Vector math is not OO in nature and it would be a mistake to try to force it into an OO context. In ...


6

How often should RAII be used? As often as it makes sense to use (that is, whenever you have an operation that will need to be inverted/undone/closed/finalized/committed/etc. you should probably use RAII). However, I also know that you are supposed to create as few objects as possible, as to save RAM. No; This is a form of premature optimization ...


4

A recap of what the final keyword does: Let's say we have base class A and derived class B. Function f() may be declared in A as virtual, meaning that class B may override it. But then class B might wish that any class which is further derived from B should not be able to override f(). That's when we need to declare f() as final in B. Without the final ...


4

One of the benefits of the C++ smart pointers is that their names document ownership semantic information and memory management information. For example: A std::shared_ptr<Foo> clearly suggests that this instance of Foo is intended for shared usage. Similarly, std::unique_ptr<Foo> clearly suggests that this instance is uniquely owned and ...


4

I assume you mean "get rid of accessors and make private members public"... well, from a design point of view, a getter/setter is not doing much more than a public variable anyway, just with more layers. Now, a good class design would not even begin to consider exposing a variable at all, it instead adds methods that apply to the internal state of the ...


4

You wrote: The std convention is to have the last iterator point beyond the last element I think I can help your mental model by giving you two little replies (one section each). Don't think of it as beyond-last indexing, think of it as edge-based indexing Why edge-based indexing (right-open interval indexing) is nice Don't think of it as ...


4

No reason why not... people embed Lua in C++ engines all the time, and sometimes JS engines. This enables them to run script-based code (eg for games, levels can be described in script). However, it does raise a large level of additional complexity that may not be needed if all you want to do is parse JSON. For that get a JSON library for C instead (Spirit ...


4

Your requirements describe Lua. Lua is designed to be embeddable as well as work as a declarative configuration language. Other options I’ve seen or used include Tcl, Python, and JavaScript. All of these languages can be embedded to various degrees of work and tend to be fairly easy for non-programmers (who think they can program) to use.


4

First, you have a false dilemma. If your users are not programmers and know only IDL, any other language (custom or existing) will look foreign to them. But that does not mean that they cannot learn something else. In fact, you would say that this is not really a problem: you'll have to write a tutorial and point them to documentation and other materials. ...


3

If you always want to avoid playing a new entity in a location that has already been allocated to something else, you can change around your process slightly. This would guarantee unique locations, but it requires a bit more overhead. Here are the steps: Setup a collection of references to all possible locations on the map (for the 20x20 map, this would be ...


3

Well from my point of view, you're trying to fix the wrong problem. You use the error-code "-1" to signalize that the MaxDigestSize should be used. This is a technique that Robert C. Martin calls "Mental mapping" in his book Clean Code. Your signed/unsigned conflict is solely caused by the fact that you're using this "error-code". So the problem that you ...


3

The one definition rule in the standard is not "appear" only once, but that they have only a single definition. E.g. if the const were in a header file, it could appear in multiple translation units, yet they would all have the same single definition. As an aside, the linker could then fold them all into a single location (if a location is even required). ...


2

What you are looking for is called a REPL, a quick search for "C++ REPL" gets you to Cling, but I have not used it. I'm not sure what is the real benefit from using a REPL over to use a debugger with an interface that you are comfortable with. Static typing should help you get the code right before ever running it, also IDE's suggestions become much better ...


2

Why not put configurable text logging into the C++ product. You can then write a separate program (in any language) to consume the log offline, or in real time, and populate a SQL database. This will decouple the SQL/DB requirement from your C++ code base, and you won't have to compile & link against or even install SQL on most machines. For the ...


2

Arbitrarily. The threads waiting are pushed into a container and on notify_one it will pick one and remove it. Usually the one most easily found in the structure. If you specify that the condition is fair then it's the oldest one. Often selected by keeping an ordered ring buffer that can grow as needed.


2

Segfaults often are affected by whatever garbage happened to be in the memory you're erroneously trying to access. Adding a cout near the bug can change that. I've also had bugs that are dependent on what memory location a pointer happened to be assigned to. Move the pointer by adding "irrelevant" code, and it changes the behavior. That's why the safest ...


2

There are several reasons why I dislike auto for general use: You can refactor code without modifying it. Yes, this is one of the things often listed as a benefit of using auto. Just change the return type of a function, and if all of the code that calls it uses auto, no additional effort is required! You hit compile, it builds - 0 warnings, 0 errors - ...


2

With C++ it's best if there is explicit documentation about who owns what pointer and is responsible for cleanup. shared_ptr tend to muddle that and it's possible that a shared_ptr ownership-loop emerges across the user and API which can lead to leaks. Let the user hold a small section of objects by unique_ptr and let other objects be owned (and cleaned ...


2

This is really more a case of the design of an API being more idiomatic C (and not even good idiomatic C at that) rather than idiomatic C++. If your callers are explicitly plugging in -1 or the result of MaxDigestSize(), it means they know ahead of time that they're using that default value. It also means they can leverage the C++ concept of a default ...


2

It looks like you have C code, so forget c++ifying it and stick with what it is. Converting all to unsigned is a good idea, getting your types right is a good thing. I would take the opportunity to remove int and replace with a known size type, such a long or __int32 so you know how many bytes of data are being manipulated (int is usually 32-bits, but ...


2

Is there a standard way to indicate that a function returns a new pointer? No, there is no "standard way" (but there is an API design policy currently considered "best practice"). Because of this ambiguity ("what does a function returning a pointer want me to do with it?"), it is currently considered best practice to impose the lifetime and ownership ...


2

You're close, but not quite. The bad practice here is declaring global variables outside of a namespace. namespace jucestain { const int k = 10; int foo(const int &i) { return 0; } } // end namespace jucestain Once you put it in a namespace, foo(k) will only resolve to foo(10) if you have using namespace jucestain; at the top of ...


2

In most respects the std::unique_ptr was made to be drop in (but safer) replacement for std::auto_ptr, so there should be very few (if any) code changes required other than (as you ask) directing the code to use either unique_ptr or auto_ptr. There a few ways to do this (and each comes with its own list tradeoffs) below. Given the code sample provided, I ...


1

Others mention methods for classes which is the Object Oriented way. Sounds like your task is to safely order the procedures. Well, a procedure is (abstractly) a behavior of an object. Are you locked into a single class to manage these procedures as methods, or can you create two classes? Say, DoerOne withDoerOne::DoSomethingOne(), and DoerTwo ...



Only top voted, non community-wiki answers of a minimum length are eligible