New answers tagged

0

This looks like two circles and and_not operation on them. Filled circle is simply x^2+y^2<r^2 and you need two of them with different r. Then it's just matter of and_not operation: x \in (A and_not B) <=> (x \in A) && !(x \in B)


5

The value isn't assigned to the complicated expression. The expression is evaluated to a pointer, and the value is assigned to the location of that pointer (via the dereference operator *). The entire thing is quite legit, it just looks really weird because of the complicated casts.


1

The correct answer is: C. None of the above. Option A: void fill_array(Array<Type>* array_to_fill); This is more idiomatic for pre-C++11 code where smart pointers were troublesome due to a lack of move semantics, and still continues to be the safer of the two options. The key here is the function does not "own" the memory: it performs one ...


0

Is there any design error by which I need the template type of the solution in every other class? That dependency is quite common in Genetic Algorithm / Genetic Programming frameworks and it isn't per se a design error. There are two reasons because of which your code looks that way: classes that interact with Solutions often need to store them ...


2

You have already an accepted answer, but I am adding a new one (because I disagree with what @ixrec said). I imagine there is a subtle difference, but I don't know what it is. Could someone explain when I might prefer one form over the other? Ideally (in a perfect world), you should use the second form, for three reasons: it composes it naturally ...


7

The first kind of signature is usually preferable. The difference is that the second signature requires the array to be created inside the function. In particular, the second signature effectively requires the array to outlive the scope in which it was created. So what we're really comparing are these two snippets: function foo1() { Array<Type>* ...


2

It seems most likely that the second one returns Array<Type> and not Array<Type>*. In the first case, there is an Array<Type> somewhere and you pass a pointer to it, so the function can fill it. In the second case, the function creates an object and returns it (unless the type is Array<Type>* and I don't know what's going on). If you ...


2

This is an example where the forward links in the graph are difficult to calculate, but the reverse links are quite easy, so index those instead. Go through the word list and create entries for every link back to the word. For example, the word "cat" would generate the following index entries: ".at" -> Set("cat") "c.t" -> Set("cat") "ca." -> ...


0

Why you would even begin to implement this is beyond me. Qt has such a tools for such animations in place already for both its widgets and qml (qml side being slightly more convenient imo). If qt is not possible, there is probably numerous other libraries.


0

When having to inherit a third-party's class, how are naming conventions handled? TL;DR: It is almost always better to prefer composition over inheritance. Do not inherit from third party software, and that includes classes defined in the std namespace, and your problem will be solved. Inverting Nike's catchline: Just don't do it. Details: Don't, ...


4

That's the challenge with languages where the language community hasn't established a naming convention. One work around if (like you say in your case) there are only a few offending inherited functions, you could make your subclass a facade class YourClass: private LibraryClass { public: int yourNamingConvention() { return ...


1

The documentation explain very well the 4th and 5th parameters, dwMaximumSizeHigh and dwMaximumSizeLow. They are however not the highest and the lowest possible size of the data, as you exprect. They are the high order and the low order part of the same, each being a 32 bit part of the 64 bit size: ...


4

Could someone write an opensource version of the Windows API? Yes, but you are asking the wrong question! Okay, after that teaser ;-) let's step back a bit. The answer to the question "can someone write X" is almost always "Yes". Unless it is "No". Well, okay, that's not terribly helpful. Obviously, the answer to a Yes/No question is either Yes or No. ...


1

The syntax of init-declarator-lists is: init-declarator-list: init-declarator init-declarator-list , init-declarator init-declarator: declarator initializer So it seems they are saying a init-declarator-list should contain only 1 init-declarator at a time. so instead of int a,b; they want int a; int b; (although they could be ...


0

Not... really. You can implement most APIs that way but some of them fundamentally expose the model used by the operating system. For example, consider fork(), which basically has no possible Windows implementation. In the general case, you can do, but for specific APIs, it may be that the underlying OS such as Linux simply does not offer that feature.


1

Don't use Pthread mutexes to synchronize between processes, at least on Linux. (I am not sure that Linux is implementing pthread_mutexattr_setpshared correctly and efficiently, at least not in GNU glibc 2.21). Use POSIX semaphores, see sem_overview(7). Or consider the Linux specific eventfd(2) probably with poll(2) & read(2) & write(2). Both ...


0

If you use frame numbers as reference, your animation may run faster or slower, depending how good the PC is. A better approach would be to have timed events, and to update your animation depending on these. By the way, in qt it is possible to do whatever you like. Animated widgets are easy to do. Handle a timer event, and do custom paining of the widget. ...


3

How would you design this in a way that prevents doing that from the users of the library? Separate Texture interface from implementation: class API_DLL ObjectTag { uuid mUUID; public: uuid getUUID() { return mUUID; } }; class API_DLL Texture: public ObjectTag // Texture interface visible in client code { public: virtual ...


1

If I were you, I'd forget about using either pthreads (which only works on threads and not processes, and you're clearly using multiple processes) or shared memory of the kind you're talking about, as transferring the handles between processes is going to be a bit of a pain point when working in C#. A simpler technique, which is becoming increasing frequent ...


5

If you want to serialize and deserialize Texture objects, then you should have constructors, methods or interfaces explicitly designed for this purpose. Serialization is one of the few use cases that's special enough to deserve it. Since this is C++, you have many options. Off the top of my head: Give the Texture class serialize() and deserialize() ...


2

pthread_mutex_t is not designed to work cross process like that. It was built with the assumption that all threads using it will have the same address space. There are however other options to share a mutex between processes. As discussed in the comments there is futex(7) (which will work over shared memory) and sem_overview(7) (an explicit named semaphore ...


4

Today, the preprocessing is actually happening inside the compiler (e.g. inside the cc1plus executable started by g++ command). Use g++ -C -E to get the preprocessed form. Preprocessing and parsing is a well known art, and does not take that much time. However, the standard headers of C++11 (e.g. <vector> or <map>) are pushing a lot of stuff. ...


0

C++ does resolution by name, not by signature. That means that if two functions/variables/member variables in the same scope have the same name, they can conflict. When you do something like using namespace std;, you are including the entire std namespace in your code. What would happen if you had a templated function called count in your code that took 3 ...


8

Why doesn't the compiler complain? Because it's not required to. The language standard describes the circumstances that require a compiler to complain, and a mere array-index-out-of-bounds is not one of them. Decent static analysis tools are capable of detecting this scenario for specific cases. The simple case of: int anArray[25]; anArray[25] = 0; will ...


0

MIT (I think) has some great online courses archived that I've been observing. One of the really cool and powerful things about being able to do this is that you can specifically access memory that you wouldn't normally be allowed to. This offers you all sorts of ways to do things you probably shouldn't. ;) But I think the main reason that this is ...


0

Practically, this cannot be done with your piece of code. Because, C++ doesn't provide primitive types as class. Hence, abc.number.IsNeg() is not possible. You can achieve it using the code given below. But I will not recommend this, instead follow @David's advice to avoid complexity. class ABC { public: Number number; } class Number { public: int ...


1

As observed by Jules it's a fact that early C++ implementations (CFront pre-1.0) had a dot for scope identification. A dot was also used in C with Classes (1980). Indeed this is a simple snippet from Classes: An Abstract Data Type Facility for the C Language 1: class stack { char s[SIZE]; /* array of characters */ char * min; /* pointer ...


0

How to test send method (that I really send what I want)? I can't mock it. I can write that HTTPClient receives SomeLibrary::ClientSession object in constructor (in test I would pass mock) but is it good design? Yes. You should definitely inject the connection/session into the client. I think that the way of implementing of session etc. should by ...


13

The book you are reading was published in 2007. The C++ API for managing threads wasn't standardised until 2011. At the time, on different systems you had to use entirely different platform-specific libraries (pthreads, win32 threads, etc). Now, this is no longer true. Your book is out of date.


1

The short answer is no (take a look at Extension methods in c++ and C++ Extension functions? for more details). For operators that haven't been already defined by a class you can write overloads which work on that class and it's a little like method extensions. However the "everything is an object paradigm" doesn't hold in C++ and free functions (What's ...


3

The behaviour should be inside the class, so you do not need these nested . calls. The following design delivers exactly what you want without adding special complexity of a custom class representing a value. class ABC { public: int number; bool isNumberNegative() const { return number < 0; } }; // ... // ABC abc; auto ...


1

It gets interesting when Run does other things besides just calling DoIt, and DoIt is just a customization point. So basically,Run is a complicated operation, with small variations. Those variations are achieved by various DoIt functions in the different subclasses, while the bulk of the code is shared. For example, the base class could be a helper to ...


5

... threading is platform-dependent, can someone explain, why? The platform dependencies are typically differences in the way that the thread scheduler works. The fact is that thread schedulers do behave differently on different platforms due to: differences in the thread scheduler algorithms across different operating systems and versions. ...


0

You could use static inheritance, and inject the object through the template argument. Then in the unit tests, inject the mock object, instead of the real object. Something like this : struct A { void doThings() { } }; struct MockA { MOCK_METHOD0(doThings, void()); }; template< typename doer > struct B { void foo() { a.doThings(); } ...


1

You usually mark class as virtual when, besides having some sort of implementation (either directly in the class declaring the function itself or in a child inheriting this class), you want the declaration to state a contract, which must be fulfilled by the implementations. The declaration basically says: If you give me this set of parameters of these ...


1

Your design or test is wrong. Instead of mocking using a framework, try create your own derived class and design your test around this "mock" class. You will realize that idea of mocking non-virtual methods doesn't make any sense. The idea of virtual methods is that the base class wants some functionality and expects it's children to provide it. If the base ...


2

Yes, it would be a good design to break that direct dependency on the session implementation and instead inject it. (Not only for testing purpose.) template <typename SessionT> class HTTPClient { private: SessionT session_ {}; public: HTTPClient(SessionT session) : session_ {std::move(session)} { } // Optional convenience overload ...


2

The most C++-like way to pass a range of items is to pass iterators; which as you suggest, involves template parameters. The reason for this is that a range represented by iterators can be anything, including: A complete container A sub-range within a container A stream Pointers An 'inserter' (e.g. std::back_inserter) std::regex matches Something from ...


5

Given that you're writing C++, a function template that accepts a pair of iterators for the beginning and (one past the) end would make sense. Especially if this code is more about the future than the past, I'd consider working with a Range instead. There's a draft Technical Specification for ranges, and a high likelihood that (perhaps a revised form of) it ...


3

If the goal is to accept as many different types of "list" as possible, then you should write a template function that accepts anything, and in your implementation either use the begin() and end() free functions to get iterators for it, or use a foreach loop (which the compiler will implement for you using begin() and end()). This will work for raw arrays, ...


0

An alternate approach is to return a struct which combines whether the value is valid and what the value is. (This is admittedly more natural in languages with multiple returns.) Like this: struct maybe_double { bool isValid; double value; }; maybe_double getCompositeValue() { maybe_double term1 = hopefullyGetSomeData("Data1"); if (! ...


5

This could be refactored in several ways with varying levels of elegance and intrusiveness. Do repetitive things in a loop The idea is simple: Put your values into arrays and use a loop to retrieve them. void logAnError(const std::string& message); bool hopefullyGetSomeData(const std::string& id, double& destination); bool ...


2

The main advantage of doing this replacement would be the cost of bringing in new people. If you bring in a new C++ programmer, they will have to learn the particulars and vagaries of your smart pointer. Whereas if you used unique_ptr, there is a reasonable chance that they already know its peculiarities. And if they don't, then there's an entire Internet ...


5

This is a common problem for maintainers of old/legacy code, and there is no single perfect answer. Before making the decision to replace working code, I would propose trying to answer these three questions. Is it possible? Can you devise a method whereby existing instances of the 'old way' can be reliably replaced by the 'new way' such that each change is ...


1

This is a problem for many legacy systems. On one hand, this custom std::unique_ptr-like capability has been around for a long time. Bugs were wrung out long ago, and people on the project know how to use it. "It ain't broke, so don't fix it". On the other hand, it is broke in a sense. One of the biggest challenges facing older solutions to some problem is ...


1

Also is it possible to tell exactly which files a process will need before running it? This is not feasible. First, there are many APIs that load files. You'd need to scan for every one of them. Then, you'd need to figure out what the appropriate parameter would be at runtime. Consider this code: char foo[100] scanf("%s",foo); FILE* fp = open(foo) ...


0

In .NET there are mechanisms around to assist with loading libraries. To quote the MSDN article: The .NET Framework provides the AppDomain.AssemblyResolve event for applications that require greater control over assembly loading. By handling this event, your application can load an assembly into the load context from outside the normal probing paths, ...


0

Is it possible to have private objects? Not in the strict sense of private. This word only makes sense when talking about members/methods of a class and has no other place. In a broader sense, it is possible (and quite common) to create objects inside a class in a way that they never leave the class, and thus are invisible to the outside world (i.e., ...


-1

Java objects instantiated with new operator (ie. Example eObject = new Example()) can't be specified private or public. They are limited by the scope and visibility based on context they are defined in. For example, an object created inside a method can be accessed from within that method only. But objects composed within other objects (ie. instance ...


6

The question of whether an object is private or protected or public simply doesn't make sense: you cannot name an object, and thus you cannot access an object by name, so access restrictions based on names simply do not apply to objects. The only way to access an object is if that object is either referenced by a field or returned by a method, both of which ...



Top 50 recent answers are included