Tag Info

New answers tagged

1

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 ...


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 ...


0

My understanding is that a lazy evaluated language actually holds everything in a wrapper like this: class LogicalValue { ActualValue *value; ActualValue operator()() { if (value == null) { value = computeValue(); } return value; } } This is like your caching example, except that it doesn't attempt to reuse ...


0

If you think about the problem a bit, it should be obvious that of the eight queens, one must be on the first line, one must be on the second line, and so on. So the only thing you need to find is where in the first line the first queen is, where in the second line the second queen is, and so on. Here is an excellent data structure for that: int position ...


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 ...


1

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.


1

Following the StackOverflow Question suggested by Thomas, the answer should look like this: class SomeNode : Node { int indexA; int indexB; } template <typename N, int (N::*indexMember)> // Note the * class Heap{ update(N node, int key){ //... node.*indexMember = i; // Also here } } Heap<SomeNode, &SomeNode::indexA> ...


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: ...


7

When are macros idiomatic and when should they be avoided? Macros are idiomatic only when there is no alternative to their use. Examples are include guards (they are the only portable form), embedded domain-specific languages, special compiler support not available through other language features (embedding built-in macros like __FILE__, stringifying ...


3

The only time I'd consider macros are for compile time constants, typically ones that affect the compilation (as opposed to constant application values, which are better modelled as const types). However, I have modelled utility routines such as calls to logging functions in a macro just so they will be compiled out, but I think even this is unnecessary ...


10

As a rule, you should only use macros, when a better alternative does not exist. They should not be used to generate code; you should simply write the code instead (if the code is type-agnostic, write a template instead). They should not be used to define constants; constants should be defined using one of these: (static) constexpr/const variables, ...


1

Would this model benefit from shared pointers? It looks like you hold the pointers and take ownership of them. It also seemsn that client code doesn't share ownership. At this point (heh punny!), you would benefit from implementing this in terms of a std::unique_ptr, and exposing either a custom safe wrapper around a pointer, or a Blob* const to client ...


4

You seems to want to make some optimization (e.g. common subexpression extraction, as commented by rwong) in your interpreter. Notice also that a language (even a domain-specific language) is never defined by some internal representation, but a computer language is defined by its syntax and its semantics (so you'll better define them first, at least on ...


2

The accepted answer mentions only the pros of converting C to idiomatic C++, as if C++ code would be in some absolute sense better than C code. I agree with other answers that it's probably unnecessary to do any drastic changes to the mixed code if it isn't broken. Whether mixing C and C++ is sustainable depends on how the mixing is done. Subtle bugs can be ...


1

I'm no C++-Expert, but in the last days I did some research around "smart" pointers, so maybe I can help you: Shared pointers may help you in this situation, but they may be just a too easy way out of a situation where it is not too clear in the first place who the data really belongs to. Accessing a shared pointer is cheap, but copying it has a small ...


0

virtual bool behavesWell() incurs extra processing overhead but, usually, it's a nonissue (e.g. Virtual functions and performance - C++). bool behavesMemberWell() has extra storage requirements: you have an extra bool m_well in every object you create. With the first approach you just have an additional pointer in the vtable (once per class). If the ...


10

You have two separate issues: How to code a C or C++ program which can easily be ported to several operating systems. The easiest way is to use some cross-platform framework library like Qt or POCO (or perhaps libsdl or GTK) which has been ported to several platforms and provides a common set of abstractions. You could also restrict yourself to purely C99 ...


2

Services, not Superclasses These things are not related objects, they are behavioral aspects of game objects that may come and go as the state of the game objects change; think about them as services, not superclasses. They're not well-suited to purely compositional elements either, as the in-game behavior will likely be strongly dependent on the state of ...


0

I think Observer Pattern is a simple and clean solution to update your GUI. It is a behaviour pattern that allows you to implement an event like system. It will keep your GUI nicely decoupled from your library. I normally use it in conjunction with an Adapter pattern in other to decouple the concrete "update" implementation from my main Entity. This way I ...


4

Simplest method is to pass a callback function to the state machine that gets called when a state changes (or other event happens). Then when it gets called you can update the gui in that function (or forward the message to the gui thread if the state machine runs in a separate thread). The signature would be something like void callback(State oldstate, ...


2

GUI libraries (like for example Qt) are using some kind of subscriber-publisher design pattern, which is event based. That means, on an event, all subscribers are going to be notified. So, on a state change, publish the event. Every object that subscribed to the event, is going to execute a callback.


1

It's certainly do-able, but it's not small. An incomplete minimal example looks something like: template <typename BaseIterator, typename FieldType, FieldType SensorReading::*FieldPtr> class FilteredIterator { BaseIterator base_; typedef FilteredIterator<BaseIterator, FieldType, FieldPtr> self_type; public: // iterator type traits ...


10

Shipping tests? Yes. Shipping Unit tests? No. As you say in the comment, problem you may face when running the product on a client computer will include problems such as linking with the wrong dll, generally this is not something a unit test will catch (which will no doubt have mocked the dll out to test the code). Now, shipping an integration test suite, ...


16

Sometimes test code contains snippets of code from third parties, both external and internal to your company. This happens as users file bugs; your tests (such as regression tests) then incorporate the code supplied by them to reproduce. Often, the licensing of such code snippets to reproduce bugs is unclear. So, you should be aware of intellectual ...


0

Here is an O(n*log(k)) amortized* runtime and O(k) exact storage solution where n is the iteration limit and k is the number of divisors to test against. Algorithm: Preconditions: n is a non-negative integer, k is a positive integer, and each divisor supplied is a positive integer. Create a heap priority queue containing of (multiple, divisor, string) ...


0

The first thing to do is to get a precise specification of the task. "FizzBuzz" has two divisors (3 and 5), one word "Fizz" to be printed if the first divisor is present, and another "Buzz" to be printed if the second divisor is present. I seem to remember a variation where for numbers divisible by 15 the result wasn't "FizzBuzz" but "Fizzbuzz" or something ...


2

I want the new subtypes to inherit the way they are handled from their base type The classic GOF visitor pattern behaves exactly like that. For example, look the Wikipedia CarElement example (it is a Java example, but the important part is similar in C++). Lets assume you add new Wheel types like SquareWheel, RoundWheel by inheriting them from Wheel. ...


2

If the logic for choosing the next state is a part of the Algorithm classes, then clearly they must be able to communicate the specific state to change to to the Context class. If the concept of states to change to is useless without the 'context' object (hard to tell), passing a reference to the context object should be fine - the algorithms and the ...


2

Is all the functionality known at compile time? If so, template metaprogramming might work. See a real example here, but something like this --- template<class T> ExtraFunctionality { //do something with instances of class T } template<class T> OtherExtraFunctionality { //do something else with instances of class T } template< ...


2

You can try using std::function to pass function pointers around, or just raw function pointers if not (I have used the latter for lookup tables of routines to call based on some data input)


0

Simple: mock libraries (mocking both .cc and .h files) and be prepared that the same library will be mocked in different ways for different tests.


0

There are two options : don't link Socket compiled binary into the libaryA, and compile libraryA with mocks. I think this is what you are trying to do : link time dependency injection. use run-time dependency injection. Add interface for the Socket class, and use some kind of dependecy injection (factory, constructor or method), and in tests, instead of ...


2

C and C++ are different in this respect. C 2011 Online Standard 6.7.6.3 Function declarators (including prototypes) ... 10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters. ... 14 An identifier list declares only the identifiers of the parameters of the function. An empty ...


4

strtok is not thread-safe because it saves its state in static memory between calls. If two threads make concurrent or interleaved calls to strtok, they will get erroneous results. The strtok_r variant returns a pointer to the caller to use for future invocations on the same string. There are many other C and POSIX functions that are not safe to use from ...


0

If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes and race conditions I think you just hit what they were after. In any language you will have parts of it that are not thread safe and need synchronization mechanisms to prevent issues (look at the .net List for a ...


3

There are always two sides to constness: Being const in the sense of the programming language, and being logically constant. Say a C++ object has a pointer to a std::string object. If the C++ object is const, I can't change the pointer to point to a different std::string object. However, I can change the contents of the std::string object. Which doesn't ...


25

In C, a function with an empty parameter list () can take anything for its arguments. Literally anything. This is usually used to implement a function which can take a variable number of arguments, though these days it's considered preferable to use the more explicit ellipsis syntax (...) for these functions. In C, a function with the parameter list (void) ...


3

First of all, there is an important thing to understand in this line: char *s1 = "abc"; The variable s1 does not store any bytes of the string "abc". Instead it is a pointer (as indicated by its char * type) that contains some address in memory, where the actual bytes of the string are stored one after the other, with a zero terminator at the end. This is ...


0

Comment was getting too long, and my previous answer was complex enough not to further muddy it, but based on your VList link, here's another answer: Main data structure: List (no need to be linked) of arrays (I'll call them main_arrays), doubling in size whenever capacity is constrained. Start with 1 sized main_array, then add a 2-length main_array, then a ...


0

It took me a while to find something I thought to be authoritative and finally found this nugget from a Dr. Dobb's Journal 2001 article: "Intuitively, the standard-library vector class is like a built-in array: we can think of it as holding its elements in a single block of contiguous memory. Indeed, although the C++ Standard does not explicitly require ...


1

Boost may be cutting edge when it is first released. But it (boost) should also be considered a testing ground for new ideas. The thread ideas introduced in boost were a good idea at the time and the lessons learned helped the standardization committee when they added threads to the standard. But now that threads are part of the standard you should be ...


0

Finding very old STL documentation may not be as easy as it sounds. What I do recall from using STL back in 1996 was &vec[0] was already guaranteed to provide the beginning of the vector's array of data. I doubt there were any non-array implementations that met the original STL specs.


14

I do not know for sure, but I would be willing to bet that the answer is probably because the inventors of C ran out (or nearly ran out) of characters. The original intention was that the language should use symbols for operators, and also that the language must be expressable within the so-called "lower" ASCII table, which consists of ASCII values 0 ...


2

StackOverflow would be a somewhat better place for asking programming/algorithm related questions. In any case, the implementation you must have read would be based on "tables". Here is how such implementation works: Initialize vector with size n, say n = 16 Address: 0xAAA0 to 0xAAB0 Memory reserved Insert 17 elements. First 16 inserted fine. Next ...


0

First off, containers that hold raw pointers are only problematic because those pointers could become invalid/out of date at any time (from the point of view of the pointer container). Same goes for containers of iterators. Possible solutions I can think of: 1) The slightly-less-dangerous option: Store the objects in a stable, node-based container such as ...


3

During learning C++, I have found books recommending to avoid creating containers with pointers. So, should I just accept this case as an exception to the rule ? No, burn the books instead. There's nothing special about T* that makes it unsuitable in a container. How should I optimally design the initialization of the Nodes and the destruction ...


0

Is it normal design to save all this information outside of the code. I think it is perfectly normal. You can use Observable pattern for handling events dispatching and store its configuration (actual subscriptions) inside, say, database. I do not respect storing information in plain files. It is difficult to atomically change them and they are not ...



Top 50 recent answers are included