Questions tagged [c++]
Questions about C++, a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language.
2,769
questions
0
votes
1
answer
87
views
Which approach do I choose for representing objects and scenes in my 3D drawing library?
I'm creating my own drawing library in C++ to provide shared rendering code for my projects.
Since the library is designed to be used as a component of other projects, the renderer's representation of ...
5
votes
4
answers
1k
views
C++ and memory safety
At my tiny org, the core engine is C++ due to a compute heavy workload. I need to internally react to NSA's recommendation about replacing C++ with a memory safe language.
They're highlighting the ...
12
votes
7
answers
4k
views
Immutability across programming languages
I'm quite confused about the concept of mutability (or mutation?), especially across different languages. In a language like Python:
x = 10
x = 20
I believe this is called shadowing (or rebinding) ...
1
vote
3
answers
210
views
"use auto" and "declare most abstract type", which guideline has higher priority?
According to Why define a Java object using interface (e.g. Map) rather than implementation (HashMap), I know I should declare most abstract type when possible, for example, suppose I'm using an UI ...
4
votes
2
answers
629
views
In C++, why does the main function use 'char *argv[]'?
I was wondering why C++ uses the following function prototype for the main() function:
int main(int argc, char *argv[]);
instead of something like:
int main(std::vector<std::string> argv);
...
61
votes
12
answers
54k
views
Are utility classes with nothing but static members an anti-pattern in C++?
The question Where should I put functions that are not related to a class has sparked some debate over whether it makes sense in C++ to combine utility functions in a class or just have them exist as ...
2
votes
3
answers
3k
views
How to prevent 'global variables' in a big project?
With 'global variables', I mean
Variables on namespace level
Static data members in classes
Static variables in functions
In a big C++ project I would like to have a mechanism (like a compiler ...
5
votes
2
answers
696
views
Is "using active record pattern" a reason to inherit from standard container (eg:vector)?
According to Is it bad practice to use Inheritance to associate methods with a basic container?, I know it is bad to inherit form std containers, mainly because std containers are not designed to be ...
1
vote
2
answers
259
views
OOP Design of a Mathematical Group
A Group is formally defined as a set of Element's,
over which a single operator mul is defined.
There are different kinds of Groups,
and each kind requires a different set of parameters.
Operator mul ...
15
votes
6
answers
9k
views
Unstable output C++: running the same thing twice gives different output
So, the problem:
When I run the same C++ code in Visual Studio, with the same input and parameters, I get either the correct output, or an output that is completely messed up (99% of values go to zero)...
9
votes
5
answers
9k
views
C/C++: Which conversion warnings make sense in practice?
C/C++ implicit conversions can cause bugs. Here's one example:
int foo, bar;
scanf("%d", &foo);
scanf("%d", &bar);
float foobar = foo / bar;
If I input 7 and 2, it's not 3.5 as expected - it'...
3
votes
2
answers
2k
views
Are there real world examples demonstrating reasonable performance improvement by using move semantics?
(I've asked a similar question on SO but unfortunately it might not be proper, so I also put here; please kindly point out if you think it's a duplicate.)
I've heard many words about the move ...
75
votes
8
answers
107k
views
Using scoped enums for bit flags in C++
An enum X : int (C#) or enum class X : int (C++11) is a type that has a hidden inner field of int that can hold any value. In addition, a number of predefined constants of X are defined on the enum. ...
4
votes
1
answer
166
views
Having a collection of pointer that remove destroyed elements
Let's say I have an object Foo that uses another object Bar.
Many different Foo could use the same Bar.
When no Foo references a Bar, this Bar is useless and should be destroyed.
Clearly, that's a ...
10
votes
6
answers
16k
views
In C++, why shouldn't all function parameters be references?
I am currently learning C++ from the C++ Primer 5th edition. The book's chapter on functions states that only large objects (large being relative as standard library strings count, but "primitive ...
149
votes
15
answers
31k
views
Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class.
This syntax seems to have been inherited from C++, where new is used specifically to allocate a new ...
2
votes
2
answers
281
views
Optimal way to share data between different classes
I have a C++ code that performs simulation of a physical system which deals with motion of objects. It has the following classes:
Class Main, containing all the main calculation methods and the data ...
0
votes
4
answers
2k
views
Share Global Variable in DLL, feasible or naive?
So the gist is to have a static global variable that can be modified by different executables. For example I have 2 different source files including the same dll.h:
dll.h
#include <iostream>
...
4
votes
2
answers
942
views
How to make max-heap stable with counter and account for counter overflow?
Generally I need size-efficient data structure similar to std::priority_queue but stable (preserving order of insertion).
By adding just 4 bytes to the object I could have 1 byte serving as priority ...
1
vote
1
answer
106
views
How to Handle Additional Parameters in State Transition for State Pattern in C++
I'm implementing a state pattern in C++ with a context and several states. Each state implements its transition. Here's a simplified version of what that design could look like:
class Context;
class ...
179
votes
5
answers
76k
views
What's the reason for not using C++17's [[nodiscard]] almost everywhere in new code?
C++17 introduces the [[nodiscard]] attribute, which allows programmers to mark functions in a way that the compiler produces a warning if the returned object is discarded by a caller; the same ...
9
votes
4
answers
2k
views
Is the inability to find code by searching for a class name a reason to avoid using auto in c++ variable declarations?
According to https://softwareengineering.stackexchange.com/a/180616/432039 suggested, I know the answer advised "auto" should be used instead of the actual type when declaring variables.
...
4
votes
4
answers
1k
views
Is updating a macro value in the Xcode preprocessor's macros violating the open–closed principle?
For example, for some Xcode projects, if I have some places that defines a number at some .cpp files:
const int PAGE_MAX=5;
and a new requirement comes that needs to change PAGE_MAX, I need to modify ...
5
votes
1
answer
535
views
Confused on how abstraction and encapsulation is helpful
Using assimp I've created a function to load 3D models and it does everything I need and I don't plan to use another library or write something custom, however, I am curious how techniques such as ...
2
votes
1
answer
120
views
C++: Good approach to handle libxml2 resource management in a wrapper
I try to write a C++ wrapper to a well-known C library, libxml2. In libxml2, an xmlDocPtr represent an XML document and xmlNodePtr represents a node. An xmlDocPtr contains a root xmlNodePtr and every ...
1
vote
1
answer
72
views
CMake Reusability and Package Management
My question is focused on CMake C++ projects and separating out code into multiple repositories for re-usability, and somewhat mimicking a naive package management system. For now I would like to ...
2
votes
3
answers
190
views
How to decouple spagheti code for unit tests [duplicate]
A little background on the project: we as a company receive a spaghetti source code, and into that we add even more spaghetti code. So with that I want to say that
complete restructuring and ...
0
votes
2
answers
152
views
Why do you need to use pass by reference in C++ to change the value of the arguments inside the function?
I'm new to coding and am currently trying to learn C++ myself. I just learned about function parameters and pass by value vs pass by reference. Everywhere I read, they say that one of the reasons pass ...
4
votes
1
answer
445
views
Requesting information regarding the use of MUI vs. the use of GetText for i18n/L10n of Windows desktop applications
I have spent the past two days investigating which technology I will use to support translations of text strings (as part of an overall internationalization migration) for an archaic (VC6) Windows ...
5
votes
5
answers
748
views
Is it bad practice to use nullptr in ternary operation?
I've set up a ternary operator in place of a pile of if-else's, the final expression being nullptr in order to finish the loop, like so:
int menuSelect;
std::string operation="";
(...
5
votes
2
answers
2k
views
Suggestions for documenting namespaces with Doxygen
Consider several C++ classes which are all defined in a particular namespace. For cleanliness, each class is located within its own file, and are each well-documented.
For the purposes of completing ...
2
votes
1
answer
155
views
Embedded C++ classes vs. namespaced free functions
I am using C++ in an embedded environment (ESP32) and have been playing around with different ways of structuring my program. The program isn't super complex but not so simple that it could all be ...
1
vote
2
answers
289
views
Combining Command and Visitor design patterns
Designing the architecture of a personal project, I've come up with the idea of using the combination of these two patterns to solve an architectural issue. In an MVC context, I need to implement ...
253
votes
12
answers
30k
views
Why do many exception messages not contain useful details?
It seems there is a certain amount of agreement that exception messages should contain useful details.
Why is it that many common exceptions from system components do not contain useful details?
A few ...
0
votes
1
answer
88
views
Application plugin interface design
I build a plugin based Qt application which currently lives entirely in a library. The app as well as the plugins link to the library. The ::main(…) is just a tiny two line bootstrapper calling a ...
9
votes
1
answer
2k
views
How does condition_variable::notify_one() choose which thread to unblock?
notify_one() of C++ 11 thread library is used to unblock one of the waiting threads.
How does it choose which thread to unblock?
To begin with, I tried googling but could not find any appropriate ...
1
vote
1
answer
130
views
Do you re-include system headers in the implementation files?
Here's a scenario:
suppose you have #include <unordered_map> in the header
and you don't declare it anywhere in the implementation file
but you use it, maybe
mp[whatever] = some;
should you re-...
63
votes
9
answers
27k
views
Is it good practice to rely on headers being included transitively?
I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only ...
0
votes
2
answers
220
views
Use case comparison for std::optional vs default argument
Wanted your opinion on which way will be better. Below is a sample code where I have used std::optional in the argument of a lambda and the lambda itself is an argument of the class constructor.
...
0
votes
1
answer
149
views
Is it good practice for object APIs to be required to be called in sequence to gather information?
I had this discussion with someone and it ended ambiguously.
Suppose you have a class that needs to Parse a file to gather some information. It can expose this information to you after the fact.
...
13
votes
6
answers
10k
views
Why use a special "Name" class (instead of just a string) for representing object names in C++?
Suppose we have an Instance class in a C++ program, which has a GUID/UUID, name, parents, children, and other properties which can be saved to or loaded from an XML file.
The intuitive approach for ...
29
votes
14
answers
10k
views
Avoiding throw because we are not sure the exceptions will always be caught
I'm a junior in my company, and one of the coding rules they have is:
"a constructor object must never fail" (i.e., never throw). So what if I give them an invalid parameter? Then, the ...
3
votes
1
answer
815
views
C++: Broadcast/observer pattern with polymorphic events
I'm currently trying to implement an event-system following a broadcast/observer scheme. I have events/notifications that contain information about what is happening:
class Event
{
public:
Event(...
31
votes
9
answers
23k
views
Should there be assertions in release builds
The default behavior of assert in C++ is to do nothing in release builds.
I presume this is done for performance reasons and maybe to prevent users from seeing nasty error messages.
However, I'd ...
2
votes
2
answers
365
views
Game Systems Interaction Design
Intro
I'm writing an FPS game in c++. There is a timed game mode, players run around a map shoot from a variety of weapons which are either hitscan or projectile based, when a shot connects, based on ...
1
vote
1
answer
211
views
Using templates without generic implementation
Is it a good practice to declare a template class, but only with specialized implementations ?
Ie, there are many CRC flavours (see https://en.wikipedia.org/wiki/Cyclic_redundancy_check#...
5
votes
4
answers
3k
views
Should I initialize third party libraries in a class or function?
I'm making a game using C++ and a handful of libraries like SDL2 and OpenGL. For a lot of these libraries, you need to initialize or set them up, and there's usually some important object(s) that come ...
0
votes
2
answers
234
views
How to deal with boolean or enum variables used to decide code flow?
I am working on algorithm implemented in C++ that maintains several enum types. Say 3 to 4 enum types each with at least 4 different values. Plus the code maintains several boolean variables. The code ...
0
votes
1
answer
144
views
Error codes in a legacy C++ project [closed]
Background
I have a large C++ project which uses system error codes from errno.h, in C style.
int Cls::foo(A arg, O* out) {
if (!validate(arg)) return -EINVAL;
if (!out) return -EINVAL;
return 0;...
1
vote
5
answers
2k
views
How to write retry code when failure is inidicated by throwing an error?
Assume I have an API that indicates failure by throwing an error (because errors are not expected). In this situation, how should retry code be written?
My first thought was to use something like this:...