question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,834,147 | 70,835,273 | C++ overload assignment operator | I'm currently struggling with the assignment operator. I keep missing something.
Could you help me out here?
Check it out here
https://godbolt.org/z/rfvTqcjoT
class SpecialFloat
{
public:
explicit SpecialFloat(const float f);
SpecialFloat& operator=(const float f);
private:
float m_float;
};
SpecialFloat::SpecialFloat(const float f):
m_float(f)
{
}
SpecialFloat& SpecialFloat::operator=(const float f)
{
m_float = f;
}
int main()
{
SpecialFloat f = 1.0f;
}
why is my operator overloading not working?
<source>(27): error C2440: 'initializing': cannot convert from 'float' to 'SpecialFloat'
<source>(27): note: Constructor for class 'SpecialFloat' is declared 'explicit'
or can the assignment operator not take custom types?
| The line SpecialFloat f = 1.0f; cannot perform assignment from 1.0f to f because f doesn't exist yet. We are just creating it.
It would do if you had written SpecialFloat f{0.0f}; f = 1.0f [Demo].
The line SpecialFloat f = 1.0f; is doing copy initialization (1).
Initializes an object from another object.
Syntax
T object = other; (1)
In your code T is SpecialFloat, a class type, and other is a float (not T or derived from T).
The effects of copy initialization are:
...
If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T [...] user-defined conversion sequences that can convert from the type of other to T are
examined and the best one is selected through overload resolution. The result of the conversion, which is a rvalue temporary [...] of the cv-unqualified version of T if a converting constructor was used, is then used to direct-initialize the object.
User-defined conversions from float to SpecialFloat should be examined. However, explicit constructors are not considered for copy-initialization.
Notes
Copy-initialization is less permissive than
direct-initialization: explicit constructors are not converting
constructors and are not considered for copy-initialization.
One way to solve this is to use direct initialization, and, if possible, with braces instead of parentheses, i.e. SpecialFloat f{1.0f}; [Demo].
There's a C++ Core Guideline advising about preferring the {}-initializer syntax.
Also, declaring single-argument constructors explicit is a general recommendation, so I would keep the user-declared constructor as explicit.
Another way would be to make SpecialFloat class an aggregate, by removing the user-declared constructor, and use aggregate initialization, SpecialFloat f = {1.0f}; [Demo].
Finally, as commented by others, notice the signature of the assignment operator is SpecialFloat& operator=(const float f), what indicates that a SpecialFloat& has to be returned. So first, update the object with m_float = f;; then, return it with return *this;.
[Edit]
I just came accross this article from Arthur O'Dwyer's, The Knightmare of Initialization in C++ where he basically favours copy initialization over direct initialization with braces, in order to improve the readability of the code.
Simple guidelines for variable initialization in C++:
Use = whenever you can.
Use initializer-list syntax {} only for element initializers (of containers and aggregates).
Use function-call syntax () to call a constructor, viewed as an object-factory.
Thus:
int i = 0;
std::vector<int> v = {1, 2, 3, 4};
Widget w(name, price, quantity);
Moreover, he suggests to combine the copy initialization with the Almost Always Auto style. Going back to the original OP's question, that would allow us to keep the SpecialFloat class untouched and write auto f = SpecialFloat{1.0f}; [Demo].
He acknowledges though that his guidelines conflict with the aforementioned C++ Core Guideline of preferring the {}-initializer syntax.
|
70,834,212 | 70,834,304 | C++ const parameter directive blocks function use of class | I have a C++ class that is used as a function parameter which is causing me some grief. I can't seem to call function from the class parameter when it is designated as const.
sample class:
class FooBar
{
private:
bool barFoo; // I want this modifiable only through functions
public:
const bool& getBarFoo() // this function needs to be used to retrieve it
{
return barFoo;
}
void setBarFoo(bool newVal) // this is the set function. It validates if the set is possible
{
// check if modification is possible.
barFoo = newVal
}
}
I try to use this class in a function similar to this:
void DoShizzle(const FooBar& yesOrNo)
{
if(yesOrNo.getBarFoo()) // here the code shows an error*
{
// do shizzle
}
else
{
// do other shizzle
}
}
* the message says 'the object has type qualifiers that are not compatible with the member function "FooBar::getBarFoo" object type is: const FooBar'.
If I remove the 'const' directive from the FooBar parameter in the DoShizzle function, the error goes away. However I read that you should try to tell developers and the compiler what you're doing. I want to keep the variable barFoo private so that it can only be modified using the setBarFoo function, to prevent it being modified without validating if it can be. But I also want to communicate that the function DoShizzle will not edit the FooBar class.
What can is a good solution to my problem? Live with the fact I can't use const here? Or am i missing another solution to my problem? I'm fairly new to C++ and a C# developer by nature so I know I might have to unlearn some practices
| const qualifier of a member function is not necessarily the same as the const qualifier of its return type. Actually they are unrelated in general (only when you return a reference to a member, from a const method one can only get a const reference). Your method:
const bool& getBarFoo() // this function needs to be used to retrieve it
{
return barFoo;
}
Is a non-const method that returns a const bool& (a constant reference to a bool).
If you want to be able to call the method on a const FooBar you must declare the method as const:
const bool& getBarFoo() const // <--------
{
return barFoo;
}
|
70,834,499 | 70,835,752 | Runtime error: signed integer overflow: 3 * 965628297 cannot be represented in type 'int' | I am solving a problem of code forces. Here is the problem link -> Problem Link
My code passes 9 test cases out of 10 and the 10th case is this
100
??b?a?a???aca?c?a?ca??????ac?b???aabb?c?ac??cbca???a?b????baa?ca??b???cbc??c??ab?ac???c?bcbb?c??abac
and the error I got is this
wrong answer expected '331264319', found '-2013109745'
Diagnostics detected issues [cpp.clang++-diagnose]: p71.cpp:14:20: runtime error: signed integer overflow: 3 * 965628297 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior p71.cpp:14:20 in
Other test cases
6 ac?b?c output - 24
7 ??????? output - 2835
9 cccbbbaaa output - 0
100 accbaccabccbbbbabacabaaccacbcbcababbbcbcbcccabcbbc?caaabcabcaaccbccabaaaaccacabbaabcbbccbbababaac output - 14634
This all test cases gives the right answer except the 1st on
and my code which I was submitted is this
#include<bits/stdc++.h>
using namespace std;
int main(){
int n; cin>>n;
string s; cin>>s;
int e=1, a=0, ab=0, abc=0;
for(int i=0; i<n; i++){
if(s[i] == 'a') a+=e;
else if(s[i]=='b') ab+=a;
else if(s[i]=='c') abc+=ab;
else if(s[i]=='?') {
abc = 3*abc+ab;
ab = 3*ab+a;
a = 3*a+e;
e = 3*e;
}
}
cout<<abc<<endl;
return 0;
}
I have tried these things -> Change int to long long int.
Here the output changes but is still wrong and negative. Output -> -1959750440526388721.
Then I tried using unsigned while declaring variables. This also gives me wrong and but not negative. Output -> 2281857551.
| Since you need the result "modulo 10^9+7", you can reduce the result of all additions and multiplications "modulo 10^9+7" (i.e. find the remainder after division by 10^9+7 - this is what the % operator does).
In the code, you can either do this in each calculation or at the end of the loop. Applying the first option (and a few good habits) looks like this:
#include <iostream>
#include <string>
// Avoid using namespace std;
int main() {
unsigned n; std::cin >> n;
std::string s; std::cin >> s;
unsigned e = 1, a = 0, ab = 0, abc = 0; // We do not need negative numbers
unsigned m = 1000000007; // Calculate result modulo 10^9+7
for(unsigned i = 0; i < n; i++) {
if(s[i] == 'a') a = (a + e) % m;
else if(s[i]=='b') ab = (ab + a) % m;
else if(s[i]=='c') abc = (abc + ab) % m;
else if(s[i]=='?') {
abc = (3 * abc + ab) % m;
ab = (3 * ab + a) % m;
a = (3 * a + e) % m;
e = (3 * e) % m;
}
}
std::cout << abc << std::endl;
return 0;
}
|
70,834,618 | 70,836,001 | Z3 and let statement in C/C++ | SMT-LIB support a let statement:
(let ((x1 t1) · · · (xn tn)) t)
Which statements must be used if the C/C++ library of Z3 is being used?
| There's no corresponding statement in C/C++, because it is not needed.
Note that SMTLib's let statement allows you to give a name to a subexpression so you can use it multiple times. If you want to do the same thing in C/C++, you'd simply use a C/C++ variable (of the right type) that contains that expression, and use it later on in building bigger expressions. So, in this sense, the let expression of SMTLib corresponds to the regular variables and expressions in C/C++.
PS. I suspect, however, you might actually have a different question about writing z3 programs in C/C++, and perhaps the way you formulated it is an instance of the so called XY problem. If you ask about exactly what you're trying to achieve, you'll no doubt receive a better answer.
|
70,834,849 | 70,835,915 | QT C++ to QML can not be connected | I have the following code:
class Boundaries: public QObject{
Q_OBJECT
enum Type{
in,
out
};
QDateTime m_startTimeBoundary{};
QDateTime m_endTimeBoundary{};
QDateTime m_from{};
QDateTime m_to{};
Q_PROPERTY(QDateTime fromDate READ getFromDate NOTIFY emitSignal1)
Q_PROPERTY(QDateTime toDate READ getToDate NOTIFY emitSignal1)
QDateTime getFromDate(){
return m_from;
}
QDateTime getToDate(){
return m_to;
}
public: signals:
void emitSignal1();
public:
void initBoundaries(const QDateTime& start,const QDateTime& end){
if (m_startTimeBoundary.isNull() && m_endTimeBoundary.isNull()){
m_startTimeBoundary = start;
m_endTimeBoundary = end;
}
}
void myClass(const QDateTime& origin, qint64 diffMs, Type type)
{
//..some code..
emit emitSignal1();
}
Q_INVOKABLE void myClassIn(const QDateTime& origin, qint64 diffMs){
myClass(origin, diffMs, Type::in);
}
Q_INVOKABLE void myClassOut(const QDateTime& origin, qint64 diffMs){
myClass(origin, diffMs, Type::out);
}
};
My C++ model:
class MyCustomModel: public QObject{
Q_OBJECT
..some code..
Q_PROPERTY(Boundaries* myClass READ getmyClass)
Boundaries* m_myClass;
Boundaries* getmyClass(){
return m_myClass;
}
.. some other code..
}
And here comes my QML connection problem:
MyButton {
anchors.verticalCenter: timeFilterRow.verticalCenter
onClicked:{
var x = getDataX()
var y = getDataY()
myCustomModel.myClass.myClassIn(_org, diff)
}
}
But I get an error that says that the Boundaries is unknown. Could any of you help me to understand what I did wrong here? Or am I missing something?
| To my understanding with myCustomModel.myClass.myClassIn(_org, diff) you are trying to invoke a function of an object from your C++ environment but you are actually creating a new instance of type MyCustomModel which requires QML to know of the class Boundaries
Instead of registering the type (qmlRegisterType) to make it instantiable I guess you are searching for a way to pass over your C++ object to make it accessible within QML
If that's the case you can achieve this by declaring a context property:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MyCustomModel model;
engine.rootContext()->setContextProperty(QStringLiteral("modelinstance"), &model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml"));
return app.exec();
}
Then you should be able to invoke on this object instance from within QML:
if (modelinstance)
modelinstance.myclass.myClassIn(_org, diff)
|
70,835,208 | 71,268,759 | Need some assistance in understanding FBX SDK data structures | I am attempting to convert the animation of some older files over to the FBX file format in order to import them into the Unreal engine. I am currently going through the data structures and see how what I have can relate to the FBX data structures. I have a few questions that I am asking the community to help me in my understanding:
Am I able to create the animation separately? As in, do I have to attach a skeleton within the FBX file format? I am asking because Yes, I do have a skeleton for the animation but I would like to be able to extract these separately. Unreal is able to handle combining them both within the program but is it theoretically possible to export the skeleton then the animation? Or do I have to have the skeleton in the animation export in order for the FBX file format to work properly?
With that being said, the old animation file does have references to bones. And by reference to bones, I only have the name of the bone that is belongs to. There is no id, just a string of the name. Which is fine. So when I go to build the FBX for the animation, I will create a scene that holds all of the data. Now for the stack and the layer, should I give each bone name it's own stack? Or should I have only 1 stack and underneath that give each bone name it's own layer?
Note: this is only for 1 object. Each scene will only have 1 object that I am animating. There will never be more then 1 object.
|
Do I have to attach a skeleton within the FBX file format?
FBX uses FbxAnimCurveNodes to link FbxAnimCurves to animatable FbxObject properties (such as translation and rotation). Therefore, if you omit the skeleton from the file, then FbxAnimCurveNodes theoretically become useless, and all you're left with are generic FbxAnimCurves.
An FbxAnimCurve by itself doesn't really have much significance. You could think of it like a traditional math function f(n). Is f(n) driving translation along the X-axis or is it driving rotation about the Y-axis? There is no embedded information telling what is actually changing with time. (That is the role of FbxAnimCurveNode.)
That all being said, you might be able to get away with naming each curve. For example, "left_wrist_position_x" or "hip_rotation_z". (This approach might not work with programs such as Maya though.)
Now for the stack and the layer, should I give each bone name it's own stack? Or should I have only 1 stack and underneath that give each bone name it's own layer?
To answer this question: you wouldn't really do either. Bones are defined as FbxNodes with an FbxSkeleton attribute attached.
You can think of the FbxAnimStack as a collection of animation sequences for a single character. You can then think of FbxAnimLayer as the different sequences for the character such a standing, walking, and running. Each FbxAnimLayer holds a collection of FbxAnimCurves, which are linked to properties such as object translation, rotation, or even changing material color - using FbxAnimCurveNodes.
The FBX SDK also allows you to blend between layers - for example, blending from a walking cycle into a running cycle.
Hope that helps a bit!
Autodesk goes a little more in depth about these types here
|
70,835,747 | 70,837,216 | Access a struct variable when struct is passed as a double pointer | I have a function as follows
int check_inband_status(Port **ePort, Port **wPort, InbandPort *inbandPort)
{
std::ifstream ring_config_file(RING_CONFIG_FILE);
Json::Value ring_config;
ring_config_file >> ring_config;
(*ePort)->port_id = ring_config["east_port"]["port_id"].asInt();
(*ePort)->port_type = ring_config["east_port"]["port_type"].asString();
(*wPort)->port_id = ring_config["west_port"]["port_id"].asInt();
(*ePort)->port_type = ring_config["west_port"]["port_type"].asString();
ring_config_file.close();
}
I have a json file and I am reading it and assigning the values to ePort and wPort.
This is the variable ePort and wPort
class InbandPort : public Port
{
public:
uint32_t vid;
uint32_t nicid;
uint32_t intf_id;
uint32_t number_of_nni;
bool is_lag;
olt_intf_type_t intftype;
Port *port1;
Port *port2;
SubportList sPorts;
ERPSPort *erpsPort;
bool is_active;
bool is_dhcp_done; /* to mark the dhcp is done or not is static dhcp case by default value is true*/
bool is_ring_configured;
InbandPort() : Port()
{
vid = INVALID_ID;
nicid = INVALID_ID;
intf_id = INVALID_ID;
port1 = NULL;
port2 = NULL;
erpsPort = NULL;
is_lag = false;
is_dhcp_done = false;
is_ring_configured = false;
port_id = 0;
number_of_nni = 0;
}
.....
Here is the json file
{
"east_port" : {
"port_id" : 2,
"port_type" : "nni"
},
"west_port" : {
"port_id" : 4,
"port_type" : "nni"
}
}
It is crashing at
(*ePort)->port_id = ring_config["east_port"]["port_id"].asInt();
I know I am making some mistake in accessing/assigning double pointer. Can someone please point me to it?
Edit: I am passing it as a double pointer because I want to access the same value from other function as well.
And how I am passing is
Port *ePort = NULL;
Port *wPort = NULL;
check_inband_status(&ePort, &wPort, inbandPort);
| You're passing the addresses of null pointers, so both *ePort and *wPort are null.
And then you dereference them, and it goes boom.
The function is probably supposed to (dynamically) create new objects and assign their addresses to *ePort and *wPort.
It's not obvious what type of objects to create, but I would expect it to look something like this (but with some error handling):
int check_inband_status(Port **ePort, Port **wPort, InbandPort *inbandPort)
{
std::ifstream ring_config_file(RING_CONFIG_FILE);
Json::Value ring_config;
ring_config_file >> ring_config;
Port* east = new Port;
east->port_id = ring_config["east_port"]["port_id"].asInt();
east->port_type = ring_config["east_port"]["port_type"].asString();
Port* west = new Port;
west->port_id = ring_config["west_port"]["port_id"].asInt();
west->port_type = ring_config["west_port"]["port_type"].asString();
*ePort = east;
*wPort = west;
return something_meaningful;
}
Another option is that it's not supposed to create objects dynamically but just modify them.
In that case, you need just one level of pointer (or a reference):
int check_inband_status(Port *east, Port *west, InbandPort *inbandPort)
{
std::ifstream ring_config_file(RING_CONFIG_FILE);
Json::Value ring_config;
ring_config_file >> ring_config;
east->port_id = ring_config["east_port"]["port_id"].asInt();
east->port_type = ring_config["east_port"]["port_type"].asString();
west->port_id = ring_config["west_port"]["port_id"].asInt();
west->port_type = ring_config["west_port"]["port_type"].asString();
return something_meaningful;
}
// ...
Port ePort;
Port wPort;
check_inband_status(&ePort, &wPort, inbandPort);
|
70,836,002 | 70,836,248 | Constructors for different ways of initialisation | I was writing code on class Matrix. So I have a small difficulty in understanding how constructor is used. Actually I have particular doubt on default constructor and parameterized constructor.
Default constructor of class : Matrix() Initialise rows and columns and matrix elements zero.
Parameterized constructor: Matrix(int rows, int columns) initialise the values passed, and 2D matrix elements with default value 0.
I don't know how both constructors work. Don't class has only one constructor, or can it have more than one constructor.
I know how to write default constructor and how to write parameterized constructor. And help with some on how this both constructors work when we write both in same class.
Will this work?
class Matrix{
private:
int rows;
int columns;
int **mat;
public:
Matrix(int row, int column){
this->rows = row;
this->columns = column;
mat = new int *[row];
for(int i=0;i<rows;i++){
mat[i]=new int[column];
}
}
};
| There is much wrong in your code. You cannot use rows and columns as array size when they are only known at runtime. Even if you could use row and columns as array size, you are using them as size of the array before you assign any value to them. Moreover this->mat[rows][columns]={0}; tries to access one element that is out of bounds of the array, it invokes undefined behavior. Use a std::vector for dynamically sized arrays.
Yes a class can have more than one constructor. Which constructor gets called is decided by overload resolution. In the example that follows, the constructor to be called can be simply determined by the number of parameters passed. In general overload resolution is more complicated (and beyond the scope of this answer).
#include <vector>
#include <iostream>
struct Matrix {
int rows;
int columns;
std::vector<std::vector<int>> data;
Matrix() : rows(0),columns(0) {}
Matrix(int rows,int columns) : rows(0),columns(0),data(rows,std::vector<int>(columns)) {}
};
int main() {
Matrix m1;
std::cout << m1.rows() << "\n";
std::cout << m1.columns() << "\n";
Matrix m2{5,10};
std::cout << m2.rows() << "\n";
std::cout << m2.columns() << "\n";
}
Note that std::vector also has more than one constructor: https://en.cppreference.com/w/cpp/container/vector/vector. Matrix() uses the vectors default constructor (1) to create an empty vector. data(rows,std::vector<int>(columns)) initializes data with a vector of vectors, by calling the vector constructor that takes a size and value (3).
The term "parametrized constructor" is a misnomer. The distinction between a "parametrized constructor" and a default constructor is wrong and misleading. A constructor can be parametrized and a default constructor at the same time. A default constructor is a constructor that can be called without parameters. This can be because it has no arguments or because it has default arguments. For example the two above can be equivalently written as one. Moreoever you do not need to store rows and columns as members, because the vector can tell you its size via its size() method:
#include <vector>
#include <iostream>
struct Matrix {
std::vector<std::vector<int>> data;
Matrix(int rows=0,int columns=0) : data(rows,std::vector<int>(columns)) {}
size_t rows() { return data.size(); }
size_t columns() {
if (data.size()) return data[0].size();
return 0;
}
};
int main() {
Matrix m1;
std::cout << m1.data.size() << "\n";
Matrix m2{5,10};
std::cout << m2.data.size() << "\n";
std::cout << m2.data[0].size() << "\n";
}
Here Matrix(int rows=0,int columns=0) is a default constructor and it is parametrized, because it can be called with either of the two:
Matrix m1;
Matrix m2{5,10};
However, the constructor with default parameters can also be called via
Matrix m3{42};
and this may not be desirable. Hence the better alternative is perhaps (as mentioned by Caleth):
struct Matrix {
std::vector<std::vector<int>> data;
Matrix(int rows,int columns) : rows(0),columns(0),data(rows,std::vector<int>(columns)) {}
Matrix() : Matrix(0,0) {}
};
This uses a delegating constructor to avoid repeating some code (available since C+11).
PS: A vector of vectors isnt a particularly good data structure. The strenght of std::vector is locality of its data, but that gets lost in a std::vector<std::vector<int>>. The ints in a std::vector<int> are stored in contiguous memory. But the ints in a std::vector<std::vector<int>> are not all stored in contiguous memory. That is because the elements are not stored within the vector. Often it is better to use a flat std::vector<int> also for the 2D case and emulate the second dimension by index transformations.
|
70,836,396 | 70,836,756 | Use child variable without to rewrite function Class | I have a question is possible to use children variable for display something.
For example:
// Entity.hpp
class Entity {
public:
Entity();
~Entity();
// For this function
virtual void attack();
virtual int getNbAttack();
protected:
private:
int _nbAttack = 0;
int _nbAttackCost = 0;
std::string _msgAttack = "message class Entity";
};
// Player.hpp
class Player : public {
public:
Entity();
~Entity();
protected:
private:
int _nbAttack = 5;
int _nbAttackCost = 5;
std::string _msgAttack = "message class Player";
};
// Entity.cpp
int Entity::attack() {
this->_power -= 10;
std::cout << _msgAttack << std::endl;
return this->_nbAttack;
}
Is it possible to do so:
// Main.cpp
Entity entity;
entity.attack();
std::cout << entity.getNbAttack() << std::endl;
Player player;
player.attack();
std::cout << player.getNbAttack() << std::endl;
Result:
message class Entity
0
message class Player
5
Is this possible or do I have to rewrite my function?
Thanks in advance for your help!
| You can absolutely do that.
But you need to make a few changes to the code you posted:
add Entity as base class to the class definition of Player (it is missing after public)
make the data members of Entity protected or add protected setters for them
if you want to use the base class' constructors in your derived class, use using Entity::Entity;, but declare Player's constructors/destructor with Player(); and ~Player(); respectively.
there is a member variable declaration missing (power)
[optional] you can get rid of the this-> to access members from inside the class. You can use it, but it is not strictly necessary
Generally I've got two tips:
First: Just try it out. Use the compiler and run your program. You can also use pages like https://godbolt.org/ to run your code (beware it might be too much information for a beginner).
Second: Get a good book on the programming language and/or see https://en.cppreference.com/w/cpp
|
70,836,505 | 70,836,853 | C++20: Implement std::is_constructible using concepts | Is there a portable way to implement std::is_constructible using concepts without STL using requires expression or template metaprogramming only?
Consider this code:
template <class T, class... Args>
struct is_constructible
: std::bool_constant<requires {
new T(std::declval<Args>()...);
}> {
};
It works fine for other data types except for references because one can't new a reference type.
// Test cases
auto main() -> int {
static_assert(is_constructible<int>::value);
static_assert(is_constructible<int, int>::value);
static_assert(is_constructible<int, float>::value);
static_assert(!is_constructible<int, int *>::value);
static_assert(is_constructible<int &, int &>::value);
static_assert(is_constructible<int &&, int &&>::value);
static_assert(!is_constructible<void, void>::value);
static_assert(!is_constructible<int(), int()>::value);
static_assert(is_constructible<int (*)(), int()>::value);
static_assert(!is_constructible<intptr_t, int *>::value);
static_assert(!is_constructible<int &, float &>::value);
static_assert(std::is_constructible<int>::value);
static_assert(std::is_constructible<int, int>::value);
static_assert(std::is_constructible<int, float>::value);
static_assert(!std::is_constructible<int, int *>::value);
static_assert(std::is_constructible<int &, int &>::value);
static_assert(std::is_constructible<int &&, int &&>::value);
static_assert(!std::is_constructible<void, void>::value);
static_assert(!std::is_constructible<int(), int()>::value);
static_assert(std::is_constructible<int (*)(), int()>::value);
static_assert(!std::is_constructible<intptr_t, int *>::value);
static_assert(!std::is_constructible<int &, float &>::value);
return {};
}
| No. Certainly not "cleanly and nicely".
In fact, early proposals during the standardization process attempted to implement constructible_from using requires expressions, but there were so many corner cases that we gave up and specified it in terms of the type trait instead.
|
70,836,549 | 70,894,727 | Old xlib programs hang the Linux GUI on window resize. Why? | I have noticed, that with the older X programs, when the user start to resize window by dragging its edges, the whole GUI of the OS freezes.
I am testing with glxgears - the gears stop rotating. The same happens with the content update of all other programs - such as the task manager, terminal windows and so on.
After stopping moving the mouse, all activity starts again.
Resizing newer program windows (I mean using GTK or Qt) does not freeze anything.
In the same time, the GUI of the older programs is much more responsive than the new. Only the dragging resize is the problem.
The older programs all use the standard documented way of handling the message queue. Something like the following (more complex, of course):
while (1) {
XNextEvent(d, &e);
if (e.type == Expose) {
XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg));
}
}
I have tried to eliminate the whole message processing by setting XSetWindowAttributes.event_mask = 0 on main window creation. The events stop flowing at all, but on resizing the empty window, all GUI still freezes.
So, the problem is not (only) on the client side. Although, it can be in the way the client and the server interact. For example it can be because the client does not do something.
So, what the newer toolkits do differently? What to change in the older programs in order to avoid such freezes.
| Well, after some research I have found the answer.
The problem is that the old programs does not use the _NEW_WM_SYNC_REQUEST protocol in order to synchronize their ability to redraw the window content with the rate of the resize events from the window manager.
Because of this the window manager resizes the window in too high rate and the application can't draw so fast. This way, the window manager effectively loads the X server and provides DoS hanging to the other running applications.
Of course in this case, the rate of the resize events depends on the window manager, but most of them simply resize the window on every mouse move.
The _NET_WM_SYNC_REQUEST protocol is aimed to provide information to the window manager when the application finished drawing its window and to stop it from resizing the window before previous resize is processed.
The implementation is pretty simple.
At first, the application must include the _NET_WM_SYNC_REQUEST in the WM_PROTOCOLS property of the window.
Also, the application should provide one (possibly two) synchronization counters (see SYNC X extension or xcb-sync library or the libX variant)
Then the protocol looks the following way:
Before to resize the window, WM sends to the application ClientMessage with data[0] set to the Atom of _NEW_WM_SYNC_REQUEST string. In the data[2] and data[3] of this event there is an 64 bit number. The application must store this number somewhere.
After processing the following ConfigureNotify and Expose events and having the window surface fully redrawn, it must set the synchronization counter to this 64 bit value.
The window manager checks the value of the counter and after see there its number, knows that it is safe to resize the window again.
Of course, there are some timeout mechanisms and if the program responds too slow or does not responds at all, the window manager switches to fall-back mode and starts to resize the windows the old way.
There is another variant of this protocol with two synchronization counters, but IMHO, it aims to solve another programs. With the window resizing, the first version of the protocol works great.
|
70,836,591 | 70,960,003 | Low quality QPixmap in Windows | I am uploading QPixmap to QTableView via QSqlTableModel. On Linux, images are displayed in normal quality, but on Windows, the image quality is very low. Is it possible to fix it somehow?
Qt 6
fragment of my code:
SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db)
: QSqlTableModel(parent, db)
{
int iconheight = QFontMetrics(QApplication::font()).height() * 2 - 4;
m_IconSize = QSize(iconheight, iconheight);
/*...*/
m_ActoinMMIcon = QPixmap(":/resources/img/many_many.svg", "SVG").
scaled(m_IconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
/*... etc ...*/
}
QVariant SqlTableModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::BackgroundRole && isDirty(index)) return QBrush(QColor(Qt::yellow));
auto field = record().field(index.column());
auto tablename = field.tableName();
auto fieldname = field.name();
/*...*/
// TABL_TASKS
if(tablename == TABL_TASKS)
{
if(fieldname == COL_TASKACTTYPE)
{
if(role == Qt::DisplayRole) return QString();
else if(role == Qt::DecorationRole)
{
auto value = QSqlTableModel::data(index, Qt::DisplayRole).toInt();
if(value == Action::ManyFromMany) return m_ActoinMMIcon;
else if(value == Action::OneFromMany) return m_ActoinOMIcon;
else if(value == Action::AsValue) return m_ActoinValueIcon;
else return m_ErrorIcon;
}
else if(role == Qt::SizeHintRole) return m_IconSize;
}
/*...*/
}
/*...*/
return QSqlTableModel::data(index, role);
}
Linux:
Windows:
| Yes, I fixed it. The problem is detected if the interface scaling is enabled in the Windows 10 OS settings (in my case it is 125%). It wasn't immediately clear.
The problem is fixed as follows:
SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db)
: QSqlTableModel(parent, db)
{
auto pixelratio = qApp->primaryScreen()->devicePixelRatio();
auto iconheight = config->GUISize();
m_IconSize = QSize(iconheight, iconheight);
/*...*/
m_ActoinMMIcon = QPixmap(":/resources/img/many_many.svg", "SVG").
scaled(m_IconSize * pixelratio, Qt::KeepAspectRatio, Qt::SmoothTransformation);
m_ActoinMMIcon.setDevicePixelRatio(pixelratio);
/*...*/
}
/* etc */
|
70,836,668 | 70,836,669 | Allocating structs of arbitrary constant size on the stack | I've written a small working plugin server. The plugins are implemented using .so shared objects, which are manually loaded during runtime in the "server" by calls to dlopen (header <dlfcn.h>).
All of the shared object plugins have the same interface:
extern "C" void* do_something() {
return SharedAllocator<T>{}.allocate(...); // new T
}
extern "C" size_t id = ...; // unique
Basically, do_something returns a pointer to heap memory, that the caller is expected to free.
id is simply an identifier unique per .so.
T is a struct specific to each .so. Some of them share the same return type, some of them don't. The point here is, sizeof(T) is .so specific.
The server is in charge of dynamically loading and reading the symbols of the .so binaries. All .so plugins can call each other through a method do_something_proxy defined in the server binary, which acts as the glue between the callers and the callees:
extern "C" void* do_something_proxy(size_t id) {
// find the requested handle
auto handle = some_so_map.find(id)->second;
// call the handle's `do_something`
void* something_done = handle.do_something();
// forward the result
return something_done;
}
To simplify things a bit, let's say that some_so_map is a plain std::unordered_map<size_t, so_handle_t> filled using a bunch of calls to dlopen when the proxy is executed.
My issue is that every caller of do_something_proxy knows T at compile time. As I said earlier, T can vary from call site to call site; however T never changes for an arbitrary call site.
For reference, here's the definition all callers use:
template <typename T, size_t id>
T* typed_do_soemthing_proxy() {
// simple cast of the proxy
return reinterpret_cast<T*>(do_soemthing_proxy(id));
}
In other words, do_something_proxy for some arbitrary plugin id always has the same return type.
If it wasn't for the proxy, I could just template do_soemthing_proxy and pass T or an std::array<int8_t, N> with sizeof(T) == N, and the unnecessary memory allocated to ensure T is not sliced when calling do_something_proxy could be moved to the stack. However, the proxy cannot be aware of all possible return types during compile time and export a zillion versions of do_something_proxy.
So my question is, is there any way for do_soemthing_proxy to allocate the effective size of T on its stack (i.e. using alloca or some other form of stack allocation)?
As far as I can tell, alloca doesn't seem to work here, as do_soemthing_proxy can only receive a single value from the do_something function of the requested plugin. do_soemthing_proxy would receive both the size to allocate, and the bytes to copy to the allocated memory, at the same time. If only alloca could be "squished" in between...
I know I could allocate a fixed amount of memory on the stack using an std::array<int8_t, N> with 256 or even 1024 for values of N. However, this solution is a bit dirty. It unnecessarily copies data from one stackframe to another, and limits the amount of data that a plugin can return. To top it off, (while I haven't benchmarked this solution yet) unless compilers can elide copies across dynamic boundaries, I'd assume copying 1024 bytes is more work than copying i.e. sizeof(std::string) bytes.
In an ideal world, I believe do_soemthing_proxy should return a struct that handles this with RAII. A const std::any that is stack-allocated, if you will. Is this even possible?
If this is not possible at all within c++, would it possible to achieve this behavior in a portable manner in assembly, i.e. by hijacking the stack or base pointers manually?
Thanks.
| Actually, I just found a solution. It boils down to inverting the direction in which the memory location for the allocation of T is passed around.
Is there any way for do_soemthing_proxy to allocate the effective size of T on its stack?
Maybe. But what the code actually needs is an allocation of the effective size of T at the caller's location, not inside the proxy. And since the caller knows sizeof(T), all you have to do is allocate the space for T on the stack of the caller before calling do_something, and then pass the address of the allocated buffer to do_something_proxy when calling it:
For the caller:
template <typename T, size_t id>
T typed_do_something_proxy() {
std::aligned_storage_t<sizeof(T), alignof(T)> return_buffer;
do_something_proxy(id, &return_buffer);
return *std::launder(reinterpret_cast<T*>(&return_buffer));
}
For the proxy:
extern "C" void do_something_proxy(size_t id, void* return_buffer) {
auto handle = some_so_map.find(id)->second;
handle.do_something(return_buffer);
}
For the callee
extern "C" void do_something(void* return_buffer) {
new(return_buffer) T(...); // placement new
}
|
70,837,571 | 70,837,748 | How to initialize a shared_ptr to a QTextCodec in my constructor? | I am trying to initialize a shared_ptr to a QTextCodec (Qt class for charset conversion) in my class constructor.
This is the code I have where I get a ‘virtual QTextCodec::~QTextCodec()’ is protected within this context error:
myencoder.h
#ifndef MYENCODER_H
#define MYENCODER_H
#include <memory>
#include <QTextCodec>
class MyEncoder
{
std::shared_ptr<QTextCodec> m_codec;
public:
MyEncoder(QString &aCodec);
};
#endif // MYENCODER_H
myencoder.cpp
#include "myencoder.h"
MyEncoder::MyEncoder(QString &aCodec)
{
m_codec = std::shared_ptr<QTextCodec> (QTextCodec::codecForName(aCodec.toLatin1()));
}
How can I initialize my m_codec property in MyEncoder's constructor?
| From docs:
QTextCodec::~QTextCodec ( )
protected virtual
Destroys the QTextCodec. You should not delete codecs. Once created their lifetime becomes the responsibility of CopperSpice.
Same with the incorporated version:
QTextCodec::~QTextCodec()
[virtual protected]
Destroys the QTextCodec. Note that you should not delete codecs yourself: once created they become Qt's responsibility.
So perhaps add empty deleter to your shared_ptr or use raw pointer and leave it up to library.
|
70,839,287 | 70,839,339 | candidate template ignored: could not match 'function<type-parameter-0-0 ()>' against 'double (*)()' | I am trying to use a template that takes in an std::function, but the template argument deduction is failing.
double foo(){
return 2.3;
}
template <typename V>
void funcC (V (*fptr)()){
std::cout << "C function's value is\"" << fptr() << '\"' << std::endl;
}
template <typename V>
void funcCxx (std::function<V()> fptr){
std::cout << "C++ function's value is\"" << fptr() << '\"' << std::endl;
}
funcC (foo);
funcCxx (foo);
The C function-pointer style (funcC) works, but the C++ std::function (funcCxx) doesn't.
I get this compiler error candidate template ignored: could not match 'function<type-parameter-0-0 ()>' against 'double (*)()'
Any idea what causes this error? Just in case, this is being compiled in clang with C++17, but I don't think it's a compiler error.
| It cannot be deduced because you are not passing a std::function to funcCxx.
Function argument and parameter type must match in template argument deduction. Otherwise deduction fails.
You could let the function take any type instead of constraining it to function pointers or std::function and then you can construct the std::function inside the function:
template <typename V>
void funcCxx (V&& v){
auto f = std::function(std::forward<V>(v));
std::cout << "C++ function's value is\"" << f() << '\"' << std::endl;
}
|
70,839,540 | 70,839,674 | deduced return type depedent on member function template argument | I am trying to figure out what's wrong with this code:
#include <string>
struct Bar
{
using Deduced = typename std::string;
};
class Test
{
template<typename Foo>
auto Func() -> decltype(Foo::Deduced)
{
return Foo::Deduced();
}
};
int main()
{
Test t;
std::string ret = t.template Func<Bar>();
}
I am refactoring a class where Func return type was declared as a template class parameter of Test class, but I would like to change this to work as a member template parameter.
Is this possible?
If yes, anyone could suggest me the right syntax?
| Remove the decltype.
decltype gives the type of an expression. But Foo::Deduced is already a type, so you can't apply decltype to it. You simply want to refer to that type itself. So all you have to do is write Foo::Deduced.
However, in some contexts, you need to prefix it with typename to tell the compiler that it's really a type. In C++20, you need typename in return Foo::Deduced() but you don't need it in the trailing return type. Prior to C++20, it was needed in both places. Thus your code could be rewritten like so:
template<typename Foo>
auto Func() -> Foo::Deduced
{
return typename Foo::Deduced();
}
Or a deduced return type could be used:
template<typename Foo>
decltype(auto) Func() // notice no trailing return type
{
return typename Foo::Deduced();
}
|
70,839,660 | 70,839,688 | std::max with overloaded less operator doesn't compile | Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <utility>
struct student
{
std::string full_name;
int group;
int number;
friend std::istream& operator>>(std::istream& in, student& obj)
{
in >> obj.full_name >> obj.group >> obj.number;
return in;
}
friend std::ostream& operator<<(std::ostream& out, const student& obj)
{
out << "Full name: " << obj.full_name << '\n';
out << "Group: " << obj.group << '\n';
out << "Number: " << obj.number << '\n';
return out;
}
bool operator<(const student& obj)
{
return this->number < obj.number;
}
};
int main()
{
std::ifstream fin("input.txt");
student a, b;
fin >> a >> b;
std::cout << std::max(a, b) << " studies at senior course.";
}
Here's the errors:
In file included from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\char_traits.h:39,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ios:40,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ostream:38,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:39,
from 2.cpp:1:
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\stl_algobase.h: In instantiation of 'constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = student]':
2.cpp:37:28: required from here
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\stl_algobase.h:227:15: error: no match for 'operator<' (operand types are 'const student' and 'const student')
227 | if (__a < __b)
| ~~~~^~~~~
What's the problem? I could've used (a < b ? b : a) instead of std::max() and it would compiled, but still I don't understand what's the problem with second option. Tried to compile on visual studio compiler and g++, result is still the same.
| You are missing a const qualifier on comparison function:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
struct student
{
std::string full_name;
int group;
int number;
friend std::istream& operator>>(std::istream& in, student& obj)
{
in >> obj.full_name >> obj.group >> obj.number;
return in;
}
friend std::ostream& operator<<(std::ostream& out, const student& obj)
{
out << "Full name: " << obj.full_name << '\n';
out << "Group: " << obj.group << '\n';
out << "Number: " << obj.number << '\n';
return out;
}
bool operator<(const student& obj) const { return this->number < obj.number; }
};
int main()
{
std::ifstream fin("input.txt");
student a, b;
fin >> a >> b;
std::cout << std::max(a, b) << " studies at senior course.";
}
|
70,839,790 | 70,882,789 | How reliable is the format of demangled names? | I am working on a pretty dynamic C++ program which allows the user to define their own data structures which are then serialized in an output HDF5 data file. Instead of requiring the user to define a new HDF5 data type, I am "splitting" their data structures into HDF5 subgroups in which I store the different member variable data sets. I am interested in labeling the HDF5 group that has the subgroup members with the type of the data structure that was written to it so that future users of the data file will have more knowledge about how to use the data contained within it.
All of this context gets me to my question in the title. How reliable are demangled names? The crux of the issue could be summarized with the following example (using boost to demangle as an example, not a necessity). If I use
std::string tn = boost::core::demangle(typeid(MyType).name());
to get the demangled name of MyType on one system with a given compiler, will I get the same result if I use the same code on a different system with a potentially different compiler? Could I safely do tn_sys_with_clang == tn_sys_with_gcc and trust that this equality holds as long as MyType is the same type?
The answer seems to me to be obviously yes, and I have checked a few examples across many different compilers on Compiler Explorer; however, I want to be confident that I am not missing any edge cases. Moreover, I'm not sure how the demangling process differs between compilers and how that might lead to the introduction of differing amounts of whitespace.
The emphasis here is that the only variable changing is the system and compiler. I know that changing the definition of MyType or moving it to a different namespace or including a pesky using directive or changing how I demangle could change the string output by the demangling. I want to focus on a more limited question where only the compiler and system change.
| Unreliable.
If you compile with the same compiler on the same OS then you should have some stability — but that is absolutely not guaranteed. ABI changes in name mangling can happen at any time in a compiler’s release cycle.
Individual compiler teams may have some information about this in their documentation. I am not going to look it up. Sorry.
All bets are off if you compile with either different compilers or different operating systems.
For example, LLVM/Clang on Windows comes with a version that uses MSVC as the backend. Consequently, name mangling on the native Windows Clang port is not compatible with the native Linux Clang.
Finally, just running a few tests with your (current) compiler is always a good way to shoot yourself in the foot. As the adage goes, “just because it works on your compiler, today...”
|
70,840,151 | 70,840,227 | Operator new behaves differently in Debug mode than in Release mode in MSVC | While testing some things regarding page faults I discovered a curious difference between how new operates in Debug mode and Release mode in MSVC. Consider the following code1:
#include <array>
constexpr size_t PAGE_SIZE = 4096;
int main()
{
const size_t count = 1000000;
char* const mem = new char[PAGE_SIZE * count];
// page align the pointer, c-style casts used for brevity
auto* pages = (std::array<char, PAGE_SIZE>*)((size_t)mem - (size_t)mem % PAGE_SIZE + PAGE_SIZE);
for (int i = 0; i < count; ++i)
pages[i][0] = 'a';
}
The code allocates a million normal memory pages on most architectures. It then physically writes to this allocated memory, so the memory really has to be "given"2 to the program - not merely "reserved" for it in some way. The curious thing is, when this actually happens. To investigate this, I stepped through the code using the Visual Studio debugger and looked at the memory usage graph in Task Manager. The results are below:
The red time point is the program being launched, the green time point/interval is the call to new char[], the blue time point/interval is the for loop.
As it turns out, in Debug mode, new both "reserves" and "gives" memory to the program. Meanwhile, in Release mode, it only "reserves" it, as the memory is "given" by the loop. I expected only the behavior present in Release mode - I thought that the memory is "given" to the program only when a page fault occurs.
Why does new behave in this way? Does this have any significant implications?
1 By the way, for some reason changing auto* pages to auto* const pages causes an Internal Compiler Error.
2 I am a bit confused regarding the correct terminology, so I used "given" and "reserved" instead.
| To understand what happened you need to know two things:
The debug builds do a lot of cool stuff for you to help you find bugs. One is writing a known value into the program's memory so you'll more easily recognize that you've messed around with uninitialized storage.
Modern memory management systems in CPUs are complicated, but one thing they all tend to do is as little as possible until they have to. When a program requests storage the underlying system checks that there is enough virtual addressing space and then almost always allows the request without filling it. No physical memory is found and assigned to the virtual memory. When the memory is accessed, then physical memory will be found and assigned or the program fails because memory was not available.
The combination of points 1 and 2 mean the debug version of new acquires the memory and immediately accesses it by writing in the uninitialized memory detection pattern and forcing the system to find and hand over real memory in the green region. As an added bonus if the computer does run out of physical storage, the program will likely crash here and not some seemingly random point in the future when the request cannot be satisfied.
The release version of new does not do point 1, so physical memory acquisition is deferred as per point 2. new exits the green region quickly without any physical memory. If some or all of the requested memory is never used, the computer profits by never having to do the work fulfilling the request. The program does use the requested storage in the for loop, so the system is forced to find and supply physical memory in the blue region.
|
70,840,406 | 70,845,460 | Why is member function return type instantiated much later than the expression types it depends on? | Pardon the confusing title.
I have this code, which is accepted by GCC, Clang, and MSVC:
#include <type_traits>
template <typename T>
struct Reader
{
friend auto adl(Reader<T>);
};
template <typename T, typename U>
struct Writer
{
friend auto adl(Reader<T>) {return U{};}
};
struct A
{
struct Tag {};
auto helper() -> decltype(void(Writer<Tag,decltype(this)>{})) {}
using Self = std::remove_pointer_t<decltype(adl(Reader<Tag>{}))>;
};
It uses stateful metaprogramming to write a type, and then read it back.
Notice the weird use of Writer. I thought I could simplify it to:
auto helper() -> Writer<Tag,decltype(this)> {return {};}
But then it stops working (on all three compilers), due to Writer being instantiated after the read happens. run on gcc.godbolt.org
But if I then move using Self = ... to a static function body below helper, it starts working again. Meaning Writer is now instantiated along with the body of helper, not with its declaration.
After experimenting with different return types, it seems that Writer is instantiated early whenever it's used as a type of an expression. Here's another example: auto helper() -> std::enable_if_t<(Writer<Tag,decltype(this)>{}, true), void> {}
What causes this difference? Since the three compilers agree on this, it's not a fluke of stateful templates, right?
| The declaration auto helper() -> Writer<Tag,decltype(this)>; doesn't cause instantiation of Writer<Tag,decltype(this)> because the return type is not required to be complete.
The definition of helper() and with it the implicit instantiation of Writer<Tag,decltype(this)> are then in a complete-class context, which it seems the compilers assume means that the member function definition is located after the class definition and that the point-of-instantiation of Writer<Tag,decltype(this)> is then also after the class definition.
I don't know whether this is actually how it is supposed to work or which paragraph in the standard would specify this behavior, though.
Reading the tag only in the body of another (static) member function causes the read to also be located in a complete class context, i.e. after the class definition in the above interpretation, which is why it works again.
|
70,840,420 | 70,840,529 | For some reason, when i use getch() my program crash, but if i use cin, then it works | I would like to know what knowledge I lack about inputs of arrays. I want to input one character and then automatically go to the next line of the code.
Here is the code:
char word[21];
for(int i = 0;i < 21; i++)
{
word[i] = getch();
//cin>>word[i];
if(word[i] == '/')break;
}
for(int j = 0;j < strlen(word); j++ )
{
if(j < (strlen(word) - 1 ))cout<<word[j];
}
| Here's how I would do this:
char c;
std::cin >> c; // Input the character.
std::cin.ignore(10000, '\n'); // Ignore remaining characters on the line.
You could replace 10000 with the maximum value for unsigned integers, but I just use an improbable large number (to fuel the improbability drive).
|
70,840,467 | 70,840,496 | Difference between foo = bar and foo{ bar } | I was under the impression that foo = bar and foo{ bar } both did the same thing and it was just a matter of preference, but in my code foo = bar gives an error but foo{ bar } does not:
std::vector<std::unique_ptr<bar>> bars;
bar& myFunction() {
bar* b = new bar();
std::unique_ptr<bar> foo{ b }; //works fine
std::unique_ptr<bar> foo = b; //error
bars.emplace_back(std::move(foo));
return *b;
}
Any idea why this is happening?
| The second one does not work because unique_ptr has an explicit constructor:
explicit unique_ptr( pointer p ) noexcept;
The below line:
std::unique_ptr<bar> foo = b;
tries to call the above-mentioned constructor of std::unique_ptr. And because of the explicit keyword, that call to the constructor is invalid.
So only these two will work:
std::unique_ptr<bar> foo { b };
std::unique_ptr<bar> foo ( b ); // or this
|
70,840,683 | 71,201,077 | Installed Visual Studio 2022 but 'cl' is not recognized as an internal or external command | None of my terminals on Windows 10 recognize cl 'as an internal or external command'.
I have Visual Studio 2022 installed and I've tried it on every terminal, including terminals in the Visual Studio 2022 under the Start menu.
I've tried the other solutions to Stack Overflow. I tried setting an environment variable of cl to "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\Hostx86\x86\cl.exe"
Under 'Modify' in Visual Studio 2022 I have the boxes for 'Desktop development with C++' and 'Universal Windows Platform development' checked and installed.
I know there are other answers to this question but Visual Studio 2022 seems like it make have another solution.
| Please find in your system this path:
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\bin\Hostx64\x64
and add this path in the user variable path for your user name in the edit system environment variables.
this will work.
|
70,840,857 | 70,939,098 | push-buffer is invalid for instance of type GstWebRTCBin | Hi i am trying to push data into a webrtcbin of Gstreamer.
this is my pipeline which works fine with testdata
pipeline =
gst_parse_launch("webrtcbin "
"name=webrtcbin stun-server=stun://stun.l.google.com:19302 "
"appsrc ! videorate ! "
"video/x-raw,"
"width=1280,"
"height=720,"
"framerate=15/1 "
"! videoconvert ! queue max-size-buffers=1 ! "
"x264enc bitrate=600 speed-preset=ultrafast tune=zerolatency key-int-max=15 ! "
"video/x-h264,profile=constrained-baseline ! queue max-size-time=100000000 ! h264parse ! "
"rtph264pay config-interval=-1 name=payloader ! "
"application/x-rtp,"
"media=video,"
"encoding-name=H264,"
"payload=96 ! webrtcbin. ", &error);
Now i try to push in some camera data
based on my reading of https://gstreamer.freedesktop.org/documentation/app/appsrc.html?gi-language=c
GstFlowReturn ret;
memcpy(gst_Imageptr, msg->data.data(), msg->data.size());
gst_ImageBuffer = gst_buffer_new_wrapped((void*)gst_Imageptr, msg->data.size());
g_signal_emit_by_name(webrtcbin, "push-buffer", gst_ImageBuffer, &ret);
if (ret != GST_FLOW_OK) {
/* some error, stop sending data */
GST_DEBUG ("some error");
}
but I get the error
push-buffer' is invalid for instance '0x55bb4cc0f0' of type 'GstWebRTCBin
So my question is, is there a different way to push data into a GstWebRTCBin?
the page https://gstreamer.freedesktop.org/documentation/webrtc/index.html?gi-language=c#signals only show signals relevant for setting up a connection.
Thanks for any advice!!
| So i found my problem, and as alyways it was very simple but for me hard due to the lack of knowledge in gstreamer
i tried to push the signal against the webrtcbin wbile i should have been pushing against the appsrc. these are different units.
so i gave the appsrc a name:
"webrtcbin name=webrtcbin stun-server=stun://stun.l.google.com:19302 "
"appsrc name=CaliCam !"
"video/x-raw, format=BGR, width=640, height=480, framerate=10/1 !"
And then stored the bin for reference
GstElement *appsrc = gst_bin_get_by_name( GST_BIN( pipeline), "CaliCam");
with that i could push the signal
g_signal_emit_by_name(appsrc, "push-buffer", gst_ImageBuffer, &ret);
the memory copy workes with both versions. I am not sure yet if allocating the memory beforehand (the way i did it) and securing its existance is less CPU and Memory efficient or not compared to the suggestion of tomaszmi. but that was not the point in the post
|
70,841,664 | 70,842,719 | Best way to group string members of object in a vector | I am trying to store a vector of objects and sort them by a string member possessed by each object. It doesn't need to be sorted alphabetically, it only needs to group every object with an identical string together in the vector.
IE reading through the vector and outputting the strings from beginning to end should return something like:
string_bulletSprite
string_bulletSprite
string_bulletSprite
string_playerSprite
string_enemySprite
string_enemySprite
But should NEVER return something like:
string_bulletSprite
string_playerSprite
string_bulletSprite
[etc.]
Currently I am using std:sort and a custom comparison function:
std::vector<GameObject*> worldVector;
[...]
std::sort(worldVector.begin(), worldVector.end(), compString);
And the comparison function used in the std::sort looks like this:
bool compString(GameObject* a, GameObject* b)
{
return a->getSpriteNameAndPath() < b->getSpriteNameAndPath();
}
getSpriteNameAndPath() is a simple accessor which returns a normal string.
This seems to work fine. I've stress tested this a fair bit and it seems to always group things together the way I wanted.
My question is, is this the ideal or most logical/efficient way of accomplishing the stated goal? I get the impression Sort isn't quite meant to be used this way and I'm wondering if there's a better way to do this if all I want to do is group but don't care about doing so in alphabetic order.
Or is this fine?
| Seems like Functor or Lambda is the way to go for this particular program, but I realized some time after posting that I could just create an ID for the images and sort those instead of strings. Thanks for the help though, everyone!
|
70,841,798 | 70,842,170 | What is the best way to implement mehtods of generic class (c++) | I want to implement a class of dynamic array in c++, and I want this implementation to be generic.
Consider the following definition:
ef DYNAMICARRAY_H
#define DYNAMICARRAY_H
template<class T>
class DynamicArray
{
public:
DynamicArray();
virtual ~DynamicArray();
protected:
private:
};
#endif // DYNAMICARRAY_H
(I did not wrote any methods yet).
Usually, we implement the methods in another cpp file. But since it is a generic class, we'll have problem with the linker after compilation with methods that use the generic types.
On the other hand, as I understand, implementing such a function in the header file might cause the compiler to make the function an inline function.
So what would be the best way to implement such functions? should it be inside the class definition? (case1)
should it be in outside the class definition but inside the header file? (case2)
#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
template<class T>
class DynamicArray
{
public:
DynamicArray();
virtual ~DynamicArray();
protected:
private:
//Should I implement here right after decleration? (case 1)
};
//Or should I implement here outside of the class definition? (case2)
#endif // DYNAMICARRAY_H
Or maybe in the cpp file and to include the line:
#include "DynamicArray.cpp"
above the main function?
Thanks in advance.
|
On the other hand, as I understand, implementing such a function in the header file might cause the compiler to make the function an inline function.
Note 1: All functions defined in the class are "inline".
Note 2: All functions in the header files (not in the class) should have the inline keyword added by the engineer manually to prevent linker errors.
Note 3: An "inline" function/method has very little to do with "inlineing" the code in modern compilers. This is a holdover from ancient times when engineers were expected to be more knowledgeable than the compiler about the underlying hardware. Nowadays, this does not hold (usually).
So what would be the best way to implement such functions? should it be inside the class definition? (case1) should it be in outside the class definition but inside the header file? (case2)
Case 1: Yes that is valid.
Case 2: Yes that is also valid.
Which you should do is personal preference (depends on your coding standard). What is best is situational and dependent on circumstance.
Or maybe in the cpp file and to include the line:
Case 3: No. That is a bad idea.
Though I have seen people put the code in a "*.tpp" file that is included at the bottom of the "*.h" file. Probably best avoided.
above the main function?
Case 4: If your project is self-contained only has one source file, and you don't plan using the header file anywhere else, then sure. Otherwise, no.
|
70,841,978 | 70,842,114 | Retrieving the file path of a dynamic library loaded by a process on MacOS | Goal:
I want to retrieve the file paths of dynamic libraries loaded by a process.
My code:
struct task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
struct dyld_image_info dyld_image_info;
char path[PATH_MAX];
if (task_info(task, TASK_DYLD_INFO, (task_info_t) & dyld_info, & count) == KERN_SUCCESS) {
printf("dyld_all_image_infos: %p\n", dyld_info.all_image_info_addr);
printf("%d\n", dyld_info.all_image_info_size);
struct dyld_all_image_infos * dyld_all_image_infos = (struct dyld_all_image_infos * ) dyld_info.all_image_info_addr;
for (int i = 0; i < dyld_all_image_infos -> infoArrayCount; i++) {
dyld_image_info = dyld_all_image_infos -> infoArray[i];
printf("%s\n", dyld_image_info.imageFilePath);
if (dyld_image_info.imageFilePath != NULL) {
if (strstr(dyld_image_info.imageFilePath, "GameCore_XP2.dll") != NULL) {
printf("Found GameCore_XP2.dll\n");
printf("%s\n", dyld_image_info.imageFilePath);
printf("%p\n", dyld_image_info.imageLoadAddress);
}
}
}
}
Unfortunately Xcode gives me the following error at runtime:
"Thread 1: EXC_BAD_ACCESS (code=1, address=0x4002e2804002d54)"
| According to https://gist.github.com/xcxcxc/989018646b1f0f2f31f0873a32c4a658, you need to use vm_read to get that data.
|
70,842,288 | 70,842,660 | OpenGL: Segmentation Fault (Core Dumped) when running | I am writing a game engine in C++ and OpenGL and when I open my first test window i receive this issue:
Segmentation fault (core dumped)
There is no error when compiling, and it compiles just fine. The problem lies when I go to open the window.
HOW TO REPRODUCE:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main()
{
typedef void (*GL_GENBUFFERS) (GLsizei, GLuint*);
GL_GENBUFFERS glGenBuffers = (GL_GENBUFFERS) glfwGetProcAddress("glGenBuffers");
unsigned int buffer;
glGenBuffers(1, &buffer);
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800, 600, "BloodBunny", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
while(!glfwWindowShouldClose(window))
{
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glViewport(0,0,800,600);
glfwTerminate();
return 0;
}
| glfwGetProcAddress() will only (potentially, depending on the name requested and the GL version of the current context) return usable, non-NULL function-pointers if a GL context is current.
With GLFW you make a window's context current via glfwMakeContextCurrent() so if you truly want to grab your own pointer to glGenBuffers() you need to move the glfwGetProcAddress() call to after a successful glfwMakeContextCurrent():
...
glfwMakeContextCurrent(window);
...
typedef void (*GL_GENBUFFERS) (GLsizei, GLuint*);
GL_GENBUFFERS glGenBuffers = (GL_GENBUFFERS) glfwGetProcAddress("glGenBuffers");
unsigned int buffer;
glGenBuffers(1, &buffer);
...
...though honestly there's little point since you're calling gladLoadGLLoader() right after glfwMakeContextCurrent() which will populate a perfectly usable glGenBuffers() pointer at global scope all on its own.
|
70,842,697 | 70,848,219 | Problem with inheritance from abstract class which is also template (c++) | I defined the following abstract List class:
#ifndef LIST_H
#define LIST_H
template <class T>
class List
{
public:
List();
virtual bool isEmpty() const=0;
virtual void Set(int index, T value)=0;
virtual int getSize() const=0;
virtual void add(T value)=0;
virtual T Remove(int index)=0;
virtual ~List();
protected:
int m_size;
private:
};
#endif // LIST_H
And then I defined a succesor DynamicArray:
#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include <iostream>
#include "List.h"
#define CAPACITY 15
template<class T>
class DynamicArray : public List<T>
{
public:
//|========================Constructors============================
DynamicArray(): m_size(0), m_capacity(CAPACITY) { //|Default constructor
m_data = new T[CAPACITY];
}
protected:
private:
//|========================Private Fields=========================
int m_capacity;
T* m_data;
};
(This is not the full class definition, of course I implemented a destructor and more methods but it does not concern my problem).
For some reason I get the following error:
'm_size' was not declared in this scope|
But m_size is defined in the base abstract class "List" and DyanamicArray inherits from List. So what went wrong here?
Thanks in advance.
| Add a constructor List(int) to the base class which initializes the m_size field.
template <class T>
class List
{
public:
List();
List(int _size): m_size(_size) {};
// ....
protected:
int m_size;
};
Add this constructor to the initializers of DynamicArray:
template<class T>
class DynamicArray : public List<T>
{
public:
DynamicArray(): List<T>(CAPACITY), m_capacity(CAPACITY) {
m_data = new T[CAPACITY];
}
private:
int m_capacity;
T* m_data;
};
Base initializers can set const fields.
What DynamicArray(): m_size(0) is trying to do is:
initialize DynamicArray
initiatlize List with default constructor
set m_size
Step 3 is not allowed (what if m_size is const?).
In terms of Software Architecture, classes should be responsible for initializing their own fields. Otherwise making changes to the internals of a base class will break child classes.
|
70,843,269 | 70,844,276 | In C + + singleton mode, if I modify a member variable in two member functions, will it conflict? | In C + + singleton mode, if I modify a member variable in two member functions, will it conflict?Do I need a mutex?
for example:
class Teacher
{
int var;
int func1(int a)
{
var = a;
}
int func2(int b)
{
var = b;
}
...
}
what is "singleton mode" in c++? I define a class to explain this question.The purpose is to make the whole program have only one object of this class.
for example:
class terminal485{
public:
~terminal485();
terminal485(const terminal485&)=delete;
terminal485& operator=(const terminal485&)=delete;
static terminal485& Instance(){
static terminal485 instance;
return instance;
}
void setPointer(AxesGroupRef *axes){
if(axes != nullptr && this->p_axes == nullptr){
this->p_axes = axes;
printf("[%s] %p\n",__FUNCTION__,axes);
}
}
int recvTerminal485Message(char *readbuf);
int getIndex();
int getBuf(char *readbuf);
private:
terminal485():p_axes(nullptr), m_bufLen(0){
printf("[%s] construct this class \n\n\n\n\n",__FUNCTION__);
}
AxesGroupRef *p_axes;
Terminal485Protocol m_protocol;
char m_recvBuf[200];
int m_bufLen;
std::mutex m_mutex;
};
| First off: 'Singleton' is a design pattern, not a 'mode'. (Personally I prefer using a namespace and static variables in the compile unit to represent 'only one instance', but that's a matter of taste).
Regarding your actual questions, unless threads (or interrupts) are involved, all accesses are sequential, which means that it is impossible for the two methods to access the shared variable at the same time, making the behaviour perfectly well defined.
Of course calling either will always overwrite whatever the other method may have done to the variable, changing the state of the object, but this is intended behaviour.
As such: No, there is no 'conflicts' or even 'undefined behaviour' in this scenario. Whether the code will do what you intend it to do however I cannot say.
Assuming you are to incorporate threads, you need to pay better attention, because multiple threads may access the resource concurrently (for example thread A could read the variable, while thread B writes to it, leading to 'A' getting garbage values). This can also happen if there is only one accessor to the internal variable.
To avoid this from happening either:
Declare/Ensure that your access is 'atomic' (for C++11 and beyond there's a family of classes that ensure that for you)
Use a mutex to protect access.
|
70,843,689 | 70,854,890 | How to refresh a Groupbox control in MFC (C++) | I created a Groupbox in my MFC view class. But failed in refresh it while Restore Down from Maxmize as well as Maxmize from Restore Down.
I create the Groupbox in View::OnCreate:
int Cmfc_gui_test3View::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
...
CRect mybox( 0, 0,350, 1000);
pmyGroupBox->Create(_T("Test GroupBox"), WS_CHILD | WS_VISIBLE | BS_CENTER | BS_GROUPBOX|WS_BORDER, mybox, this, IDG_GROUPBOX1);
...
}
And I am using pmyGroupbox->ShowWindow(SW_HIDE) and pmyGroupbox->ShowWindow(SW_SHOW) in OnPaint method. I also tested pmyGroupbox->ShowWindow(SW_RESTORE) but no lucky. The control always failed in refreshing itself.
Hope someone can help me. Thanks in advance.
| This question (Can a MFC dialog resource be attached to a CChildView?) should provide useful information.
You need to use the CFormView class if you want to create a form that has controls on it, like combo boxes.
There are some other useful articles on this subject:
Q98598: HOWTO: Use CFormView in SDI and MDI Applications
The linked article provides sample code and instructions. The summary reads:
SUMMARY
The CFormView class provides a convenient method to place controls
into a view that is based on a dialog box template. The general
procedure to use a CFormView is described in the documentation for the
class and is illustrated in the VIEWEX and CHKBOOK sample applications
provided with Microsoft Foundation Classes (MFC) versions 2.x and
above. However, these applications do not demonstrate making the
initial size of the frame window to be the same as the initial size of
the form.
The following section lists the steps required to support creating a
single document interface (SDI) or multiple document interface (MDI)
application based on a CFormView, sizing the initial frame window
around the form, changing the style of the frame, and closing an MDI
document using a button in the form.
The instructions are for older versions of Visual Studio so you might have to tweak a little.
|
70,843,952 | 70,848,455 | Do modern c++ compilers optimize assignments after type casting? | Take the following code:
char chars[4] = {0x5B, 0x5B, 0x5B, 0x5B};
int* b = (int*) &chars[0];
The (int*) &chars[0] value is going to be used in a loop (a long loop). Is there any advantage in using (int*) &chars[0] over b in my code? Is there any overhead in creating b? Since I only want to use it as an alias and improve code readability.
Also, is it OK to do this kind of type casting as long as I know what I'm doing? Or should I always memcpy() to another array with the correct type and use that? Would I encounter any kind of undefined behavior? because in my testing so far, it works, but I've seen people discouraging this kind of type casting.
|
is it OK to do this kind of type casting as long as I know what I'm doing?
No, this is not OK. This is not safe. The C++ standard does not allow that. You can access to an object representation (ie. casting an object pointer to char*) although the result is dependent of the target platform (due to the endianess and padding). However, you cannot do the opposite safely (ie. without an undefined behaviour).
More specifically, the int type can have different alignment requirements (typically aligned to 4 or 8 bytes) than char (not aligned). Thus, your array is likely not aligned and the cast cause an undefined behaviour when b will be dereferenced. Note that it can cause a crash on some processors (AFAIK, POWER for example) although mainstream x86-64 processors supports that. Moreover, compilers can assume that b is aligned in memory (ot alignof(int)).
Or should I always memcpy() to another array with the correct type and use that?
Yes, or alternative C++ operations like the new std::bit_cast available since C++20. Do not worry about performance: most compilers (GCC, Clang, ICC, and certainly MSVC) does optimize such operations (called type punning).
Would I encounter any kind of undefined behavior?
As said before, yes, as long as the type punning is not done correctly. For more information about this you can read the following links:
What is the Strict Aliasing Rule and Why do we care?
reinterpret_cast conversion
Objects and alignment
because in my testing so far, it works, but I've seen people discouraging this kind of type casting.
It often works on simple examples on x86-64 processors. However, when you are dealing with a big code, compilers does perform silly optimizations (but totally correct ones regarding the C++ standard). To quote cppreference: "Compilers are not required to diagnose undefined behaviour (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.". Such issue are very hard to debug as they generally only appear when optimizations are enabled and in some specific cases. The result of a program can change regarding the inlining of functions which is dependent of compiler heuristics. In your case, this is dependent of the alignment of the stack which is dependent of compiler optimizations and declared/used variables in the current scope. Some processors does not support unaligned accesses (eg. accesses that cross a cache line boundary) which resulting in an hardware exception of data corruption.
So put it shortly, "it works" so far does not means it will always work everywhere anytime.
The (int*) &chars[0] value is going to be used in a loop (a long loop). Is there any advantage in using (int*) &chars[0] over b in my code? Is there any overhead in creating b? Since I only want to use it as an alias and improve code readability.
Assuming you use a correct way to do type punning (eg. memcpy), then optimizing compilers can fully optimize this initialization as long as optimization flags are enabled. You should not worry about that unless you find that the generated code is poorly optimized. Correctness matters more than performance.
|
70,844,568 | 70,886,709 | free'ing pointers inside a container before clear() | I have a container such as this:
std::unordered_set<char*, Hash, Equal> my_set;
I want to free the char*'s inside this container before I .clear() it, so I do,
for(auto i : my_set){
free(i);
}
my_set.clear();
But this means, before the .clear(), the container is corrupted. I am inclined to think that this is normal, given that I am going to clear it anyway. But I should know if this is undefined behavior, or can it be used ?
|
But this means, before the .clear(), the container is corrupted.
The container is not corrupted. It stores char*s, which can be thought of as numerical addresses at which text might be stored. If valid text is no longer stored at those addresses, that's perfectly fine as long as no attempt is made to follow/dereference the pointer to access that memory. unordered_map<char*> treats the char* as values/numbers and is effectively unaware that they might point at anything - it will never dereference the pointers even if the container was resized/rehashed. And anyway, the container will never resize unless you do more insertions that cross the max_load_factor().
What it does mean is that you've - momentarily - got a container full of dangling pointers. That's not undefined behaviour - it's perfectly fine, the same way that this is fine:
{
char* p = strdup("boo");
free(p);
}
There, p is a dangling pointer after the free(), but nothing nasty happens as the scope exists - there is no hidden/implicit destructor to run for char* objects.
That said, it would be better to use RAII semantics - a type wrapping the char* that will free it in the destructor: this answer shows one way to do that with std::unique_ptr.
|
70,844,884 | 70,845,237 | Why most of C++ STL library functions use iterator as parameter? | I not getting a clear difference between pointers and iterators.
Can anyone help?
Thank you in advance.
|
I not getting a clear difference between pointers and iterators.
Iterator is a concept of a type whose instance that can point to an object, and that can be incremented to point to the next sibling element.
A pair of iterators pointing to the same container represent a range of objects within the container.
Pointers can point to an object and if the pointed object is an element of an array, then the pointer can be incremented to point to the next element of the array. Pointers are an example of an iterator for array types. There are other iterator types besides pointers, for other container types.
Why most of C++ STL library functions use iterator as parameter?
Those functions are implementations of algorithms that operate on sequences of objects, and they remain fundamentally the same regardless of the data structure that hold the objects.
If you have an array of objects, you can use the function by passing a pair of pointers into a range of objects within the array, and if you have another container, then you can use a pair of iterators pointing to elements of that container.
Being able to call the function with any (restrictions apply) iterator, allows us to use those functions with any container.
|
70,844,982 | 70,845,022 | C++ class does not output correct data? | No compilation error but the output is this:
g++ class.cpp && ./a.out
is -1003073000 years old.
It does not output the string and int as it supposed to be.
I don't know what is wrong, I would really appreciate if someone point out my mistake, thanks!.
Here is the code:
#include<iostream>
class Student{
private:
std::string name;
int age;
public:
Student(std::string name, int age){
name = name;
age = age;
}
void setName(std::string name){
name = name;
}
std::string getName(){
return name;
}
void setAge(int age){
age = age;
}
int getAge(){
return age;
}
};
int main(){
Student student1 = Student("Clayton",20);
std::cout<<student1.getName();<<" is "<< student1.getAge()<<" years old."<<std::endl;
}
| In the constructor
Student(std::string name, int age){
name = name;
age = age;
}
The names name and age are the argument variables of those names. Which means you assign the variables to themselves.
That will leave the Student::name member default constructed and empty, but the Student::age variable will be uninitialized, and have an indeterminate value, and using such values (even printing them) is undefined behavior.
You have two solutions:
Use this to explicitly reference the current object and use its member variables:
Student(std::string name, int age){
this->name = name;
this->age = age;
}
Or use a member initializer list to initialize (rather than assign to) the member variables:
Student(std::string name, int age) : name(name), age(age) {
// Empty
}
For this the language knows the difference between the member and argument variables.
I highly recommend the second alternative.
|
70,845,208 | 70,854,660 | Im trying to convert a hexadecimal number to decimal number in C++ | This is what I have so far:
#include <iostream>
#include <cmath>
#include <string.h>
using namespace std;
int main() {
string hexa = "1A";
// cout<<"HEXADECIMAL TO DECIMAL\n";
// cout<<"ENTER HEXADECIMAL: ";
// cin>>hexa;
// int inc1 = 0, hex1, ans, total = 0;
int a=0, b=1, ans, count=0, total, size=hexa.length();
//count also increment
for (int i=0; i<hexa.length(); i++){
if(hexa[i] == 'A'){
ans = 10 * pow(16, i);
} else {
ans = hexa[i] * pow(16, i);
}
total = total + ans;
}
cout<<"ANSWER IS: " <<total;
/**
do{
hex1 = hexa % 10;
ans = hex1 * pow(16, inc1);
inc1++;
total = total + ans;
hexa = hexa / 10;
} while (hexa!=0);
**/
}
I could just steal some codes online but I don't want to cheat this one (my teachers are getting suspicious of me). The code inside the comment works, the one with the do-while loop but it only works with numbers-only input. Im struggling to create a code that accepts input with letters. Also, Im not permitted to use those fancy functions and whatnot.
| #include <iostream>
#include <string>
using namespace std;
int main(){
string s;
cin>>s;//input string
int ans=0;//for storing ans
int p=1;
int n=s.size();//length of the string
//travarsing from right to left
for(int i=n-1;i>=0;i--){
//if the character is between 0 to 9
if(s[i]>='0'&&s[i]<='9'){
ans=ans+p*(s[i]-'0');
}
//if the character is between A to F
else{
ans=ans+p*(s[i]-'A'+10);
}
p=p*16;
}
cout<<ans;
return 0;
}
|
70,845,475 | 70,845,528 | How long does a non capturing lambda live? | If I have some c++ code that looks roughly like this:
void (*fun_ptr)(int);
void Test()
{
fun_ptr = [](int i) { /* do stuff */ };
}
int main()
{
Test();
/* do stuff */
fun_ptr(0);
return 0;
}
Can I expect that function pointer to live forever? Or is it like structs and it's only valid for as long as the lambda declaration is within scope?
The answer in What is the lifetime of the target of pointer-to-function pointing to a lambda? does not fully adress this question, the linked answer does not explain why scoped lambdas can outlive the scope of the code that created them.
| fun_ptr doesn't point to a lambda.
It effectively points to a static function (defined in the lambda class), and this function doesn't need a living lambda to work.
|
70,846,124 | 70,846,185 | How to deduce order of two variables store/load with acq/rel order? | I am trying to learn about execution order involving atomic variables in C++, and I have the following code.
According to cppreference, I have the following reasoning:
C++ enforce 1->2 order when executing
Because no load/store can be moved before an acquire-load within the same thread.
C++ enforce 3->4 order when executing
The same reason as 1
C++ enforce 2->3 order when executing
Because 2 is a release-store to y, and 3 is an acquire-load from y.
So 2 should be visible to 3.
Thus, 2 should be executed before 3, and 3 will read the result of 2's write.
C++ enforce 4->1 order when executing
The same reason as 3
From reasoning 1/2/3, we can deduce a execution order of 1 -> 2 -> 3 -> 4, and it will break reasoning 4.
From reasoning 1/2/4, we can deduce a execution order of 3 -> 4 -> 1 -> 2, and it will break reasoning 3.
Seems there are conflicts here.
int main() {
while(true) {
std::atomic<int> x, y;
x.store(10);
y.store(20);
auto f1 = [&]() {
int r1 = x.load(std::memory_order_acquire); // 1
y.store(r1, std::memory_order_release); // 2
};
auto f2 = [&]() {
int r2 = y.load(std::memory_order_acquire); // 3
x.store(r2, std::memory_order_release); // 4
};
std::thread t1(f1);
std::thread t2(f2);
t1.join();
t2.join();
printf("%d %d\n", x.load(), y.load());
}
}
-- EDIT --
My reasoning about why 2 must happens before 3:
From preshing, y.store(rel) syncs-with y.load(acq).
Then according to cppreference, we can have y.store(rel) Inter-thread happens-before y.load(acq).
Then y.store(rel) happens-before y.load(acq).
So y.store(rel) must happens before y.load(acq)
| 1 will "happen before" 2, and 3 will "happen before" 4. This part is correct.
However, for 3 to "synchronize with" (and "happen after") 2, it must successfully read the value written by 2.
If it doesn't read that value (because it ended up running before 2), then no synchronization happens, and no ordering is imposed on 4 relative to 1. In this case, 3 is said to be "coherence-ordered before" 2.
The same applies to 1 reading the value from 4.
|
70,846,440 | 70,869,591 | How to call a python function from C++ with pybind11? | Please consider the following C++ pybind11 program:
#include <pybind11/embed.h>
namespace py = pybind11;
int main() {
py::scoped_interpreter guard{};
py::dict locals;
py::exec(R"(
import sys
def f():
print(sys.version)
)", py::globals(), locals);
locals["f"](); // <-- ERROR
}
The py::exec call and the enclosed import sys call both succeed, but the call locals["f"]() throws an exception:
NameError: name 'sys' is not defined
on the first line of function f.
Expected behaviour is that the program prints the python system version.
Any ideas?
Update:
I modified the program as suggested by @DavidW:
#include <pybind11/embed.h>
namespace py = pybind11;
int main() {
py::scoped_interpreter guard{};
py::dict globals = py::globals();
py::exec(R"(
import sys
def f():
print(sys.version)
)", globals, globals);
globals["f"](); // <-- WORKS NOW
}
and it now works.
I'm not 100% sure I understand what is going on, so I would appreciate an explanation.
(In particular does the modification of the common globals / locals dictionary impact any other scripts. Is there some global dictionary that is part of the python interpreter that the exec script is modifying? or does py::globals() take a copy of that state so the execed script is isolated from other scripts?)
Update 2:
So it looks like having globals and locals be the same dictionary is the default state:
$ python
>>> globals() == locals()
True
>>> from __main__ import __dict__ as x
>>> x == globals()
True
>>> x == locals()
True
...and that the default value for the two is __main__.__dict__, whatever that is (__main__.__dict__ is the dictionary returned by py::globals())
I'm still not clear what exactly __main__.__dict__ is.
| So the initial problem (solved in the comments) was that having different globals and locals causes it to be evaluated as if it were in a class (see the Python documentation for exec - the PyBind11 function behaves basically the same):
Remember that at the module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
A function scope doesn't look up variables defined in its enclosing class - this wouldn't work
class C:
import sys
def f():
print(sys.version)
# but C.sys.version would work
and thus your code doesn't work.
pybind11::globals returns a dictionary that's shared in a number of places:
Return a dictionary representing the global variables in the current execution frame, or __main__.__dict__ if there is no frame (usually when the interpreter is embedded).
and thus any modifications to this dictionary will be persistent and stay (which probably isn't what you want!). In your case it's probably __main__.__dict__ but in general "the current execution frame" might change from call-to-call, depending on how much you're crossing the C++-Python boundary. For example, if a Python function calls a C++ function that modifies globals() then exactly what you modify depends on the caller.
My advice would be to create a new, empty dict instead and pass that to exec. This ensures that you run in a fresh, non-shared namespace.
__main__ is just a special module that represents the "top level code environment". Like any module is has a __dict__. When running in the REPL it's the global scope there. From the pybind11 point of view it's just a module with a dict, and you probably shouldn't be writing into it casually (unless you've really decided that you want to deliberately put something there to share it globally).
Regarding the __builtins__: the documentation for the Python exec function says
If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().
and looking at the code for the PyRun_String that Pybind11 exec calls, the same applies there.
This dictionary seems to be sufficient for the builtin functions to be looked up correctly. (If that isn't the case then you can always do pybind11::dict(pybind11::module::import("builtins").attr("__dict__")) to make a copy of the builtin dict and use that instead. However, I don't believe it's necessary)
|
70,846,881 | 70,846,986 | Why c++ .find() method is not working properly? | I am writing a code to determine how many characters in string s are also in j
Here is my code:
string j,s;
cin >> j >>s;
int count=0;
for(int i=0;i<j.size();++i){
if(s.find(j[i])){
++count;
}
}
cout << count+1 << endl;
The problem is that s.find is not work for j[0] and
When a user enters none as string s it perceives it to be the keyword none.
How can I fix this?
I am using clang 13.0.0
GNU nano 6.0 as my editor
| string::find does not return a boolean, but the position of the matching character (from 0 to size()-1) or string::npos if it doesn't find anything.
https://en.cppreference.com/w/cpp/string/basic_string/find
Use if(s.find(j[i]) != std::string::npos) instead.
|
70,846,942 | 70,847,902 | Creating a filesystem file in C++ | Is there a way to create a filesystem file that can be mounted in C++? I want to make a file containing a NTFS filesystem and mount it to a new partition. I want this done in C++ in Windows. Is there a library and perhaps some code examples that does this? I know windows has the diskpart tool which does exactly that but does it have a C++ API or something like that?
| To really "mount" the filesystem (ie. to be able to just "fopen" something inside that filesystem) you need support from the kernel. Either you let your operating system take care of it completely (e.g the VHD commands on windows; example use on stackoverflow). Alternatively can use libfuse/winfsp to interact with the kernel more directly, but afaik that requires a custom kernel driver.
If you have an image file with some filesystem inside and you just want to look whats inside, but don't need the C/C++ standard library commands (fopen, ifstream, etc.) to work, then something that can specifically read/write that combination of image file format and filesystem would also suffice.
For C# there would be the DiscUtils library which might do what you want, but I'm not aware of a similar c/c++ library with NTFS support.
|
70,847,346 | 70,848,255 | Difference between returning and not returning in recursion | I have written a program to print the Kth node from root of a binary tree.
// PRINT KTH NODE FROM ROOT (FUNCTION 1)
void printKth(node *root, int k){
if (root == NULL){
return;
}
if (k == 0){
cout<<root -> data<<" ";
return;
}
printKth(root -> left, k-1);
printKth(root -> right, k-1);
}
For the below binary tree, The code prints
// 100
// / \
// 80 120
// / \
// 40 60
//
// OUTPUT - 80 120
The above function works fine until I add a return statement in the second and third last lines.
// PRINT KTH NODE FROM ROOT (FUNCTION 2)
void printKth(node *root, int k){
if (root == NULL){
return;
}
if (k == 0){
cout<<root -> data<<" ";
return;
}
return printKth(root -> left, k-1); // ADDED RETURN STATEMENT
return printKth(root -> right, k-1); // ADDED RETURN STATEMENT
}
For the below binary tree, The code prints
// 100
// / \
// 80 120
// / \
// 40 60
//
// OUTPUT - 80
I can't understand what's happening when adding the return statement.
| There is nothing special about recursive functions. The second you return you are no longer evaluating the rest. You see that in your base cases since they don't evaluate the rest. When you add return the result of the call is returned and the last statement is never reached.
You function doesn't print the kth node but every node in the kth level in your first version. If you were to print the kth node you would have to return the current k and if it is still positive continue to recurse into the right tree.
|
70,847,581 | 70,847,656 | Error while using a static data member template | I am trying understand the concept of static data member templates. And i came across the following example in a book:
class Collection {
public:
template<typename T>
static T zero = 0;
};
When i try to execute the program it gives the error that:
undefined reference to `Collection::zero<int>'
To solve the above error i tried added the following code in the above program but it still gives error:
template<typename T> T Collection::zero = 0; //even after adding this it still gives error
Error now says:
duplicate initialization of 'Collection::zero'
My question is that is this a mistake(typo) in this example of the book. If yes, then what is the problem and how can i solve it?
| Yes this is a typo in the book. The problem is that you've specified an initializer for the static data member template even though it is not inline.
Solution
There are 2 ways to solve this problem both of which are given below.
Method 1: C++17
In C++17, you can make use of the keyword inline.
class Collection {
public:
template<typename T>
inline static T zero = 0; //note the keyword inline here
};
//no need for out of class definition of static data member template
int main(){
int x =Collection::zero<int>;
}
Method 2: C++14
In this case you need to remove the initializer 0 from the in-class declaration of the static data member template.
class Collection {
public:
template<typename T>
static T zero ; //note initializer 0 removed from here since this is a declaration
};
template<typename T> T Collection::zero = 0;
int main(){
int x =Collection::zero<int>;
}
|
70,848,303 | 70,848,588 | Why is the boost server class throwing runtime error | I am getting a runtime error in the following code:
boost::asio::io_context io_context;
server server1(io_context, 1980);
boost::thread t(boost::bind(&boost::asio::io_context::run, &io_context));
Where the definition of the server class is:
using boost::asio::ip::tcp;
class server
{
public:
server(boost::asio::io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](boost::system::error_code ec, tcp::socket socket)
{
if (!ec)
{
std::make_shared<session>(std::move(socket))->start();
}
do_accept();
});
}
tcp::acceptor acceptor_;
};
The error is at the point:
server(boost::asio::io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
Exception thrown at 0x00007FFE9D804F69 in Everest.exe: Microsoft C++
exception: boost::wrapexceptboost::system::system_error at memory
location 0x0000003AA613BDB0.
| It seems your code is missing a listen. On my Linux box this simply doesn't do anything, but perhaps on Win32 it throws an error due to invalid state of the acceptor when doing async_accept?
Here's a simple tester that does what is expected on linux:
#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;
struct session : std::enable_shared_from_this<session> {
tcp::socket _socket;
session(tcp::socket&& s) : _socket(std::move(s)) {
std::cerr << "new session " << _socket.remote_endpoint() << std::endl;
}
void start() {}
};
class server {
public:
server(boost::asio::io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
{
acceptor_.listen();
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](boost::system::error_code ec, tcp::socket socket) {
std::cerr << "accept " << ec.message() << std::endl;
if (!ec) {
std::make_shared<session>(std::move(socket))->start();
do_accept();
}
});
}
tcp::acceptor acceptor_;
};
int main()
{
boost::asio::io_context io_context;
server server1(io_context, 1980);
io_context.run();
}
|
70,848,803 | 70,848,849 | explicit template instantiation of explicit operator bool | I'm trying to understand why I get a linker error
( error LNK2001: unresolved external symbol "public: __cdecl Foo<int>::operator bool(void)const_ )
With the following code. If I move the definition of Foo::operator bool() to the header, it builds fine. Apparently there is a problem with the explicit template instantiation, but I'm not seeing it. Please help me understand why.
Foo.hpp:
/* Foo.hpp */
template<class T>
struct Foo {
T x;
explicit operator bool() const;
};
Foo.cpp:
/* Foo.cpp */
#include "Foo.hpp"
template <class T>
Foo<T>::operator bool() const {
return true;
}
main.cpp:
/* main.cpp */
#include "Foo.hpp"
#include <iostream>
int main(int argc, char* argv[]) {
Foo<int> foo;
if (foo)
std::cout << "works" << std::endl;
}
template Foo<int>::operator bool() const;
| An explicit template instantiation must have the template definition visible.
So you have to put
template Foo<int>::operator bool() const;
in Foo.cpp, not main.cpp.
Demo
|
70,848,994 | 70,850,762 | Weird C2143 error with two consecutive if constexpr in the same function | I am compiling the following code with c++17:
#include <iostream>
struct A {
void barA() const {std::cout << "barA\n";}
};
struct B {
void barB() const {std::cout << "barB\n";}
};
template<typename T>
constexpr bool isBaseA() {
return std::is_base_of<A, T>::value;
}
template<typename T>
constexpr bool isBaseB() {
return std::is_base_of<B, T>::value;
}
template<typename... Args>
class K : public Args... {
public:
void foo() {
using MyK = K<Args...>;
if constexpr(isBaseA<MyK>()) {
using X = typename MyK::A;
X::barA();
}
if constexpr(isBaseB<MyK>()) {
using X = typename MyK::B;
X::barB();
}
}
};
int main()
{
K<A, B> k;
k.foo();
return 0;
}
Demo
When building with MSVC 2019 (version 16.8.30804.86, it should be the last available one), I am getting a weird C2143 error at the line
void foo() {
The complete C2143 error is :
<source>(24): error C2143: syntax error: missing ')' before ';'
<source>(24): note: while compiling class template member function 'void K<A,B>::foo(void)'
<source>(41): note: see reference to function template instantiation 'void K<A,B>::foo(void)' being compiled
<source>(40): note: see reference to class template instantiation 'K<A,B>' being compiled
<source>(24): error C2143: syntax error: missing ';' before ')'
<source>(24): error C2059: syntax error: ')'
I noticed that:
if I comment the second if constexpr block of the function foo, the error goes away;
if I don't define the alias using MyK = K<Args...>;, the error goes away.
The code works fine both on gcc and clang.
Is this just a MSVC bug, or am I breaking the c++17 standard somewhere in the code?
| Looks like a parser bug, as adding parentheses avoids the error. Adding parentheses should have no effect at all in this context:
template<typename... Args>
class K : public Args... {
public:
void foo() {
using MyK = K<Args...>;
// extra parentheses to overcome MSVC error
if constexpr((isBaseA<MyK>())) {
using X = typename MyK::A;
X::barA();
}
if constexpr(isBaseB<MyK>()) {
using X = typename MyK::B;
X::barB();
}
}
};
compiler explorer working example
|
70,849,136 | 70,849,299 | how to pass an array through to another function? c++ | so i am making a program that takes student data as objects and prints it, i am trying to store the data as an array so each student is a element in the array, i am having issues with printing the data though as i cannot pass the array into the print function, can anyone help? when i try and compile i get "studentarray: arrays of references are illegal". sorry if this is a stupid question i am new to coding, thankyou!
| You wrote student printstudent(student & studentarray); which looks more like a deceleration than a function call.
I'm guessing you wanted to write printstudent(studentarray)?
Your error is caused by declaring printstudent(student& studentarray[10]) , which declares the function argument to be an array of 10 student& i.e. references to students, which the c++ standard forbids:
There shall be no references to references, no arrays of references, and no pointers to references.
Some more details on why can be found here: Why are arrays of references illegal?
|
70,849,604 | 70,850,122 | How to efficiently handle incoming delayed events on a single timeline? | I want to implement the algorithm that awaits for some events and handles them after some delay. Each event has it's own predefined delay. The handler may be executed in a separate thread. The issues with the CPU throttling, the host overload, etc. may be ignored - it's not intended to be a precise real-time system.
Example.
At moment N arrives an event with delay 1 second. We want to handle it at moment N + 1 sec.
At moment N + 0.5 sec arrives another event with delay 0.3 seconds. We want to handle it at moment N + 0.8 sec.
Approaches.
The only straightforward approach that comes to my mind is to use a loop with minimal possible delay inbetween iterations, like every 10 ms, and check if any event on our timeline should be handled now. But it's not a good idea since the delays may vary on scale from 10 ms to 10 minutes.
Another approach is to have a single thread that sleeps between events. But I can't figure out how to forcefully "wake" it when there is a new event that should be handled between now and the next scheduled wake up.
Also it's possible to use a thread per event and just sleep, but there may be thousands of simultanious events which effectively may lead to running out of threads.
The solution can be language-agnostic, but I prefer the C++ STD library solution.
|
Another approach is to have a single thread that sleeps between events. But I can't figure out how to forcefully "wake" it when there is a new event that should be handled between now and the next scheduled wake up.
I suppose solution to these problems are, at least on *nix systems, poll or epoll with some help of timer. It allows you to make the thread sleep until some given event. The given event may be something appearing on stdin or timer timeout. Since the question was about a general algorithm/idea of algorithm and the code would take a lot of space I am giving just pseudocode:
epoll = create_epoll();
timers = vector<timer>{};
while(true) {
event = epoll.wait_for_event(timers);
if (event.is_timer_timeout()) {
t = timers.find_timed_out();
t.handle_event();
timers.erase(t);
} else if (event.is_incoming_stdin_data()) {
data = stdin.read();
timers.push_back(create_timer(data));
}
}
|
70,849,892 | 70,851,101 | Why does std::basic_string_view have two equality comparison operators? | A quote from the standard regarding std::basic_string_view equality comparison operators (see http://eel.is/c++draft/string.view#comparison):
[Example 1: A sample conforming implementation for operator== would be:
template<class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept {
return lhs.compare(rhs) == 0;
}
template<class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
type_identity_t<basic_string_view<charT, traits>> rhs) noexcept {
return lhs.compare(rhs) == 0;
}
— end example]
Won't the second comparison operator be sufficient for all use cases? If the answer is no please provide the example code that will stop working (or will work differently) if the first comparison operator is removed. If the answer is yes then why does the C++ standard explicitly require the first operator to be defined?
| I think this is insufficient reduction as a result of the adoption of <=> in P1614. Before that paper, there were three ==s in the example:
template<class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept {
return lhs.compare(rhs) == 0;
}
template<class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
type_identity_t<basic_string_view<charT, traits>> rhs) noexcept {
return lhs.compare(rhs) == 0;
}
template<class charT, class traits>
constexpr bool operator==(type_identity_t<basic_string_view<charT, traits>> lhs,
basic_string_view<charT, traits> rhs) noexcept {
return lhs.compare(rhs) == 0;
}
At the time, we needed three operators. The type_identity ones handle stuff like sv == literal and literal == sv, and then you need the homogeneous one to disambiguate sv == sv.
With the <=> adoption (or, more precisely, the == changes from P1185), == becomes symmetric so you don't need both type_identity operators to handle literal == sv, just the one suffices. I was basically mechanically going through and dropping unnecessary == and != overloads, so I removed that second.
But what I did not realize is with the other one gone, we now no longer need the homogeneous comparison to disambiguate from the other two (we don't have other two anymore, just other one) - it's enough to just have the one type_identity overload.
You could open an editorial issue to remove the homogeneous one. Or not, it's just an example anyway.
|
70,850,115 | 70,854,390 | What is a pre-allocated buffer, and how should you use one? | I am studying FreeRTOS, and in their tutorial book they talk about using "a pool of pre-allocated buffers" for holding pointers to char[] arrays (to pass between tasks via a queue).
In the example found in Chapter 4.5 Working with Large or Variable Sized Data, they reference this sudo function called prvGetBuffer() and state "The implementation of prvGetBuffer() is not shown – it might obtain the buffer from a pool of pre-allocated buffers, or just allocate the buffer dynamically.". This seems like a funciton I would like to take a look at, but its nowhere to be found in their docs / examples.
What exactly is "a pool of pre-allocated buffers", and what does an implementation look like in C/C++? I can't find much on the internets about this.
I want to assume it is perhaps a 2-dimensional array that is "statically" allocated prior to run-time. Maybe it gets declared like char strBuffer[5][50]; or something - idk.
| A pool is a collection of shared items such as a secretarial pool or motorpool.
A pool of pre-allocated buffers is a pool of chunks of memory. Typically all the chunks in the pool are the same size. The application can allocate a chunk from the pool, use the memory as needed, and then return the chunk to the pool when it is no longer needed. "Pre-allocated" means that the chunks are not dynamically allocated from the heap repeatedly over the life of the program. Typically, the chunks are statically allocated and assigned to the pool during initialization.
A memory pool is usually implemented as a FIFO queue, often using a linked list data structure. Allocation from the pool is getting the next chunk from the beginning of the queue. Returning a chunk to the pool is adding the chunk to the end of the queue. A linked list is nice because the order of the items in the queue can change over the life of the program because items are not necessarily returned to the queue in the same order that they were allocated from the queue.
Using a pool of pre-allocated buffers is a great way to avoid dynamic memory allocation, which is undesirable in embedded systems.
|
70,850,583 | 70,853,606 | Program to evaluate postfix expressions but there is a wierd problem with this program-it does not gives output and instead gives a long error | I was writing a code for postfix expression evaluation and encountered a weird error. it shows a big error which is really difficult for me to understand what is wrong in the code.
it would be really helpful if you please have a look and tell me what's wrong with it or what mistake I have made.
I have listed the code below to have a look.
thank you in advance
here is the code :
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int evaluate(string expression);
bool Isdigit(char c);
bool IsOprator(char c);
int performcalc(char opration,int op2,int op1);
int main(){
string expression;
cout<<"Start of the program ! "<<endl;
cout<<"Enter a postfix expression to evaluate: ";
cin>>expression;
int result = evaluate(expression);
cout<<"Result ="<<result<<endl;
cout<<"End of the program !!";
return 0;
}
int evaluate(string expression){
stack <char> S;
for (int i = 0; i < expression.length(); i++)
{
if (expression[i] == ' ' || expression[i] == ',')
{
continue;
}
else if (Isdigit(expression[i]))
{
int a = stoi(expression[i]);
S.push(a);
}
else if (IsOprator(expression[i]))
{
int op2 = S.top(); S.pop();
int op1 = S.top(); S.pop();
int result = performcalc(expression[i],op2,op1);
S.push(result);
}
}
return S.top();
}
bool Isdigit(char c){
if (c >= '0' && c<='9')
{
return true;
}
else
{
return false;
}
}
bool IsOprator(char c){
if (c == '+' || c == '*' || c == '/' || c == '-' )
{
return true;
}
else
{
return false;
}
}
int performcalc(char opration,int op2,int op1){
if (opration == '+')
{
return op1+op2;
}
else if (opration == '-')
{
return op1-op2;
}
else if (opration == '*')
{
return op1*op2;
}
else if (opration == '/')
{
return op1/op2;
}
return -1;
}
Error :
Postfix_evaluation_using_stack.cpp: In function 'int evaluate(std::string)':
Postfix_evaluation_using_stack.cpp:37:39: error: no matching function for call to 'stoi(__gnu_cxx::__alloc_traits<std::allocator<char>, ch
ar>::value_type&)'
37 | int a = stoi(expression[i]);
| ^
In file included from c:\ming\mingw\include\c++\9.2.0\string:55,
from c:\ming\mingw\include\c++\9.2.0\bits\locale_classes.h:40,
from c:\ming\mingw\include\c++\9.2.0\bits\ios_base.h:41,
from c:\ming\mingw\include\c++\9.2.0\ios:42,
from c:\ming\mingw\include\c++\9.2.0\ostream:38,
from c:\ming\mingw\include\c++\9.2.0\iostream:39,
from Postfix_evaluation_using_stack.cpp:1:
c:\ming\mingw\include\c++\9.2.0\bits\basic_string.h:6503:3: note: candidate: 'int std::__cxx11::stoi(const string&, std::size_t*, int)'
6503 | stoi(const string& __str, size_t* __idx = 0, int __base = 10)
| ^~~~
c:\ming\mingw\include\c++\9.2.0\bits\basic_string.h:6503:22: note: no known conversion for argument 1 from '__gnu_cxx::__alloc_traits<st
d::allocator<char>, char>::value_type' {aka 'char'} to 'const string&' {aka 'const std::__cxx11::basic_string<char>&'}
6503 | stoi(const string& __str, size_t* __idx = 0, int __base = 10)
| ~~~~~~~~~~~~~~^~~~~
c:\ming\mingw\include\c++\9.2.0\bits\basic_string.h:6609:3: note: candidate: 'int std::__cxx11::stoi(const wstring&, std::size_t*, int)'
6609 | stoi(const wstring& __str, size_t* __idx = 0, int __base = 10)
| ^~~~
c:\ming\mingw\include\c++\9.2.0\bits\basic_string.h:6609:23: note: no known conversion for argument 1 from '__gnu_cxx::__alloc_traits<st
d::allocator<char>, char>::value_type' {aka 'char'} to 'const wstring&' {aka 'const std::__cxx11::basic_string<wchar_t>&'}
6609 | stoi(const wstring& __str, size_t* __idx = 0, int __base = 10)
| Your problem is that you're trying to compare a std::string with a char:
if (expression == ' ' || expression == ',')
Change it to:
if (expression == " " || expression == ",")
The string class doesn't support comparisons with single characters, hence the error.
Also, this is wrong:
int a = stoi(expression[i]);
stoi needs a string, you are passing a char. Change it to:
int a = stoi(expression);
And your stack is wrong:
stack <char> S;
It should be a stack of integers, not char:
stack <int> S;
|
70,850,760 | 70,888,236 | parallel programming multiplying two arrays of numbers | I have the following C++ code that multiply two array elements of a large size count
double* pA1 = { large array };
double* pA2 = { large array };
for(register int r = mm; r <= count; ++r)
{
lg += *pA1-- * *pA2--;
}
Is there a way that I can implement parallelism for the code?
| Here is an alternative OpenMP implementation that is simpler (and a bit faster on many-core platforms):
double dot_prod_parallel(double* v1, double* v2, int dim)
{
TimeMeasureHelper helper;
double sum = 0.;
#pragma omp parallel for reduction(+:sum)
for (int i = 0; i < dim; ++i)
sum += v1[i] * v2[i];
return sum;
}
GCC ad ICC are able to vectorize this loop in -O3. Clang 13.0 fail to do this, even with -ffast-math and even with explicit OpenMP SIMD instructions as well as a with loop tiling. This appears to be a bug of the Clang's optimizer related to OpenMP... Note that you can use -mavx to use the AVX instruction set which can be up to twice as fast as SSE (default). It is available on almost all recent x86-64 PC processors.
|
70,850,875 | 70,851,169 | C++ OOP divide fractions | it is my first post here sorry if it is irrelevant I will delete it.
I started learning C++, and I am currently learning OOP with OpenClassrooms.
It asked us at some point to overload some operators on our own to go further...
Here's the thing, I could do it, but I'm not sure to fully understand what happens(And I would like to be able to comment it in order to understand)
here's my code;
ZFraction.h
class Zfraction
{
public:
//Constructor
ZFraction(int num = 0, int denom = 1);
ZFraction& operator/=(ZFraction const& a);
//Other methods and operators
};
ZFraction operator/(ZFraction const& a, ZFraction const& b);
//Other prototypes
ZFraction.cpp
ZFraction& ZFraction::operator/=(const ZFraction& a)
{
m_denom *= a.m_num;
m_num *= a.m_denom;
simplify(); //simplifies the fraction
return *this;
}
ZFraction operator/(ZFraction const& a, ZFraction const& b)
{
ZFraction copy(a);
copy /= b;
return copy;
}
and main.cpp
ZFraction a(8, 12);
ZFraction b(7, 4);
ZFraction c,d,e,f;
////////
f = a/b;
Output : 2/3 / 7/4 = 8/21
I had searched on the internet a lot in order to find a solution, didn't find anything and then end up finding it myself.
So my question is... How does that work exactly ? I'm really unsure...
Thank's for answering, let me know if this post is not relevant.
| The operator overloads are regular functions with funky names, and they are used through a simple transformation.
a / b is transformed into operator/(a, b), since operator/ is a free function.
copy /= b is transformed into copy.operator/=(b), since operator/= is a member function.
That's all there is to it.
(As far as I know, this transformation idea came from CLU - the most influential programming language nobody's heard of.)
You can even use the functions directly in those forms.
It's not readable, but sometimes it helps when you need to figure out why things aren't evaluated in the way you expect.
|
70,851,009 | 70,851,231 | I don't exactly understand why my while loop is not catching any of these conditions | I'm trying to output the input string in reverse and when the user inputs "done", "Done", or "d" it will stop. With this, the while loop does not catch any of these conditions to stop the loop.
#include`<iostream>
using namespace std;
int main() {
string userInput;
int i;
char output;
getline(cin, userInput);
while (userInput != "done" || userInput != "Done" || userInput != "d") {
for (i = userInput.size() - 1; i >= 0; --i) {
output = userInput.at(i);
cout << output;
}
cout << endl;
getline(cin, userInput);
}
return 0;
}
| replace
while (userInput != "done" || userInput != "Done" || userInput != "d")
with
while ( ! (userInput == "done" || userInput == "Done" || userInput == "d") )
|
70,851,015 | 70,851,199 | `LL` vs `i64` suffix in C++ Visual Studio compiler | I'm trying to refactor an old C++ code. At some point I've something like:
#if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__))
# define I64_CONST(X) X ## i64
#else
# define I64_CONST(X) X ## LL
#endif
So for defining a 64-bit literal in the code there's something like:
(uint32_t)((data_in >> 32) & I64_CONST(0x00000000ffffffff));
This is for using i64 suffix with Microsoft compilers and LL with other ones. Since I'm adapting it for C++17 and the minimum requirement that we have is to use Visual Studio 2019, is it possible to remove this and use LL everywhere, or is there some issue and it's better to maintain the distinction between compilers?
| Yes, long long is a new type since C++11 which contains at least 64 bits, so it can be used for your literals (unless the source code is using two's complement and the compiler is using one's complement/sign-magnitude then -263 won't fit)
Another way is to use the INT64_C in <cstdint> which was also introduced in C++11
#define I64_CONST INT64_C
auto v = INT64_C(0xFFFF0000FFFF0000);
See Purpose of using UINT64_C?
|
70,852,103 | 70,852,688 | Ambiguous overload error when using conversion function | I am trying to understand overloading resolution in C++ through the books listed here. One such example that i wrote to clear my concepts whose output i am unable to understand is given below.
#include <iostream>
struct Name
{
operator int()
{
std::cout<<"Name's int version called"<<std::endl;
return 4;
}
operator float()
{
std::cout<<"Name's float version called"<<std::endl;
return 1.1f;
}
};
int main()
{
double a = Name(); //this works and calls Name's float version. But WHY ISN'T THIS AMBIGIOUS?
long double b = Name(); //this does not work. WHY IS THIS AMBIGIOUS?
bool c = Name(); //this does not work. WHY IS THIS AMBIGIOUS?
return 0;
}
As you can see here the program works when creating double a. But when i try to create objects b and c it gives error.
My questions are:
Why don't we get the ambiguity error for object a. That is, among the two conversion operators in class Name, why the float version is chosen over the int version.
Why/how do we get the ambiguity error for object b which is a long double. That is just like for a, i suspected that the float version should have been called but instead we get the error. How is this different from the double a case above.
Why/how do we get the ambiguity error for object c which is bool. In this case, I suspected that the int version could have been chosen but instead we get an error. How is this different than the double a version which works and uses float version of conversion function.
I just want to understand why/how the first version works but the other two don't.
| Essentially, skipping over some stuff not relevant in this case, overload resolution is done to choose the user-defined conversion function to initialize the variable and (because there are no other differences between the conversion operators) the best viable one is chosen based on the rank of the standard conversion sequence required to convert the return value of to the variable's type.
The conversion int -> double is a floating-integral conversion, which has rank conversion.
The conversion float -> double is a floating-point promotion, which has rank promotion.
The rank promotion is better than the rank conversion, and so overload resolution will choose operator float as the best viable overload.
The conversion int -> long double is also a floating-integral conversion.
The conversion float -> long double is not a floating-point promotion (which only applies for conversion float -> double). It is instead a floating-point conversion which has rank conversion.
Both sequences now have the same standard conversion sequence rank and also none of the tie-breakers (which I won't go through) applies, so overload resolution is ambigious.
The conversion int -> bool is a boolean conversion which has rank conversion.
The conversion float -> bool is also a boolean conversion.
Therefore the same situation as above arises.
See https://en.cppreference.com/w/cpp/language/overload_resolution#Ranking_of_implicit_conversion_sequences and https://en.cppreference.com/w/cpp/language/implicit_conversion for a full list of the conversion categories and ranks.
Although it might seem that a conversion between floating-point types should be considered "better" than a conversion from integral to floating-point type, this is generally not the case.
|
70,852,472 | 70,852,666 | How to deduce template type based on another template type | I have a templated class, whose type is to be determined by another sub templated constructor.
template <typename V, typename I>
class Text{
public:
template <typename Container, typename V = typename Container::value_type, typename I = typename Container::size_type>
Text(Container& c) {}
};
So usage would be something like:
std::vector<int> v;
Text(v) //Deduces to Text<int, std::size_t>
Unfortunately, I get an error that V and I are being shadowed. This is because it is trying to create a new V and I.
I have seen a solution with using V = typename Container::value_type; but that gives the same error.
| Your probably want to write your own deduction guide:
template <typename Container>
Text(Container&) -> Text<typename Container::value_type,
typename Container::size_type>;
Demo
|
70,852,595 | 70,852,802 | Making libcurl json post request in C/C++ | I am writing a Qt application, and I have a button which is supposed to register a user. I'm using the following libraries:
https://github.com/nlohmann/json <- for json
serialization/deserialization
libcurl
My goal is to be able to make a post request to the following endpoint:
http://localhost:8000/api/register
It is expecting a POST of Content-Type: application/json, of utf-8, with a json body like this:
{
"username": "test",
"password": "test"
}
The post request goes through, but the response is giving errors. I'm trying to pinpoint if this is an issue with my libcurl code, or if it's an error with my python django application.
Here is the verbose output of the libcurl code:
E0125 08:52:00.886679 5816 API.h:43] {"password":"test2","username":"test"}
* STATE: INIT => CONNECT handle 0x2489d6b0bf8; line 1835 (connection #-5000)
* Added connection 0. The cache now contains 1 members
* family0 == v4, family1 == v6
* Trying 127.0.0.1:8000...
* STATE: CONNECT => CONNECTING handle 0x2489d6b0bf8; line 1896 (connection #0)
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
* STATE: CONNECTING => PROTOCONNECT handle 0x2489d6b0bf8; line 2030 (connection #0)
* STATE: PROTOCONNECT => DO handle 0x2489d6b0bf8; line 2051 (connection #0)
> POST /api/register HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: Jellybean-Launcher
Content-Type: application/json; charset: utf-8
Accept: application/json
Content-Length: 8
* STATE: DO => DID handle 0x2489d6b0bf8; line 2147 (connection #0)
* STATE: DID => PERFORMING handle 0x2489d6b0bf8; line 2266 (connection #0)
* Mark bundle as not supporting multiuse
* HTTP 1.1 or later with persistent connection
< HTTP/1.1 400 Bad Request
< Date: Tue, 25 Jan 2022 16:52:00 GMT
< Server: WSGIServer/0.2 CPython/3.9.7
< Content-Type: application/json
< Vary: Accept, Cookie
< Allow: POST, OPTIONS
< X-Frame-Options: DENY
< Content-Length: 109
< X-Content-Type-Options: nosniff
< Referrer-Policy: same-origin
<
{"detail":"JSON parse error - 'utf-8' codec can't decode byte 0xdd in position 0: invalid continuation byte"}* STATE: PERFORMING => DONE handle 0x2489d6b0bf8; line 2465 (connection #0)
* multi_done: status: 0 prem: 0 done: 0
* Connection #0 to host 127.0.0.1 left intact
* Expire cleared (transfer 0x2489d6b0bf8)
Here is the libcurl code itself:
void RegisterUser(std::string username, std::string password)
{
curl_global_init(CURL_GLOBAL_ALL);
nlohmann::json json_data;
json_data["username"] = "test";
json_data["password"] = "test2";
CURL* curl = curl_easy_init();
CURLcode res;
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, GetRegistrationURL().c_str());
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
struct curl_slist* chunk = NULL;
chunk = curl_slist_append(chunk, "Content-Type: application/json; charset: utf-8");
chunk = curl_slist_append(chunk, "Accept: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* Set the expected POST size. */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sizeof(json_data.dump().c_str()));
LOG(ERROR) << json_data.dump().c_str();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Jellybean-Launcher");
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
//res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
}
curl_easy_cleanup(curl);
curl_slist_free_all(chunk);
}
curl_global_cleanup();
}
GetRegistrationURL() Returns an std::string which is scoped based on if you're in a development build or not. During development builds, it always passes localhost, and in release builds it passes the live web url.
Does anyone have any idea of what I may be doing wrong here?
| The first error is in the line curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sizeof(json_data.dump().c_str()));. sizeof does not do what you suppose it does.
Yet another error is in the line curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str()); stores a
pointer to an inside of a temporary data json_data.dump(), it causes undefined behavior, possibly sending a garbage. The error 'utf-8' codec can't decode byte 0xdd hints about the Microsoft C runtime marker 0xdddddddd of a deleted memory region.
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)json_data.dump().size()));
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, json_data.dump().c_str());
should fix the issue. Setting CURLOPT_POSTFIELDSIZE may be omitted, if the size has not been set prior to CURLOPT_COPYPOSTFIELDS, the data is assumed to be a null-terminated string - it is your case.
|
70,852,892 | 70,853,152 | Why does Incrementing a size_t default value giving garbage value? | Why does Incrementing a size_t default value giving garbage value?
#include <iostream>
using namespace std;
struct Test {
size_t a;
size_t b;
};
int main() {
Test wrong;
cout << (wrong.a) ++;
cout << endl;
cout << (wrong.b) ++;
cout << endl;
Test right {};
cout << (right.a) ++;
cout << endl;
cout << (right.b) ++;
return 0;
}
For the above code getting output
Output:
93937114642880
93937114642304
0
0
Is this because size_t not a POD? Also why does the Test wrong; not calling the default constructor and initialises the fields to default values?
|
Why does Incrementing a size_t default value giving garbage value?
You need to be very careful with your terminology. default has specific meaning in C++.
In your first case, the size_t variables in wrong are NOT being given default values. You are incrementing uninitialized variables that have indeterminate values. This is undefined behavior. So, you get garbage output because you are acting on garbage values to begin with.
In your second case, you are value-initializing the size_t variables in right to 0 before then incrementing them, which is well-defined behavior. And since you are using the post-increment ++ operator, which returns the previous value before it is incremented, that is why the output is 0 rather than 1.
Is this because size_t not a POD?
No. size_t is a POD type.
Also why does the Test wrong; not calling the default constructor and initialises the fields to default values?
Test wrong; performs default initialization. It does call the default constructor, but you simply didn't implement that constructor yourself, so the compiler auto-generates one for you. And since all of the members are PODs, there is nothing for the generated constructor to do, so it doesn't initialize the members at all.
Test right{}; performs value initialization, which in this case will zero out the size_t members.
|
70,853,041 | 70,858,781 | C++ - running on VS code with code runner | I am trying to compile and run C++ programs on VS code. I have my compiler set up, and I am trying to use the terminal for taking the user input. I tried to change the settings config for code runner by updating the
"code-runner.runInTerminal": true
After this, the terminal refuses to run the code. I understand the error that I am getting, but I have no clue on how I can fix it. Here is the program I am trying to run:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x;
cin >> x;
cout << "Output:" << x;
}
The output I get after I try to run it is:
cd "d:\Github\problem-solving\HackerRank\Cpp\" && g++ pointers.cpp -o pointers && "d:\Github\problem-solving\HackerRank\Cpp\"pointers
bash: cd: d:\Github\problem-solving\HackerRank\Cpp" && g++ pointers.cpp -o pointers && d:Githubproblem-solvingHackerRankCpp"pointers: No such file or directory
Any kind of help would be appreciated, thank you.
| Looks like you have not set up your terminal root. Essentially, the code runner will try to look for a terminal root in contexts like these, and thus if it does not get one, it misreads the input file's name when you execute it. Essentially, set the value for "code-runner".terminalRoot to "/" (without the quotes). Here is a screenshot for reference.
This should get your code running in no time!
|
70,853,587 | 70,853,674 | How to deal with ctime includes within the scope of a class in CPP? | I want to use <ctime> inside the scope of a class in C++. However, whenever I try to compile the following class, I get the error:
error: 'time' cannot be used as a function
time_t now = time(0);
I think it may be something related to the fact that I am trying to call that function inside of the Session class, because I have managed to call the time() function inside the main() function.
What am I doing wrong?
Session.h
#ifndef _SESSION_H_
#define _SESSION_H_
#include <string>
#include <ctime>
class Session
{
private:
std::string language;
time_t date;
time_t time;
public:
Session(std::string language, time_t date = NULL, time_t time = NULL);
~Session();
};
#endif
Session.cpp
#include <ctime>
#include "Session.h"
Session::Session(std::string language, time_t date, time_t time) : language{language}, date{date}, time{time}
{
if (date == NULL)
{
time_t now = time(0);
tm *ltm = localtime(&now);
}
}
Session::~Session() {}
| You declared a constructor parameter with the same name time as the function name:
Session::Session(std::string language, time_t date, time_t time)
^
Within the constructor block scope, the parameter hides the function with the same name (and also the data member with the same name declared in the class definition).
So, use the qualified name for the function:
time_t now = ::time(0);
To access the data member, use an expression with the pointer this, like this->time.
|
70,853,598 | 70,853,848 | Is this implementation of a graph effectively linear in the number of edges? | I have a class which resembles an adjacency matrix representation of a weighted, directed graph. Let's suppose the graph has n vertices. Here is how it works:
At first, allocate n2 slots to hold integers (stored in a variable named graph), in the form of n arrays each having n integers.
Assign weights to the edges, where graph[i][j] represents the weight of the edge going from vertex i to vertex j.
Deallocate any unused slots in the graph
Sample code:
class DiGraph {
public:
Graph() {}
Graph(size_t n) {
graph.resize(n);
for (size_t i = 0; i < n; i++) {
graph[i] = new int[n]{-1};
}
}
void addEdge(int from, int to, int weight) {
graph[from][to] = weight;
}
int& getEdge(int from, int to) {
return *(graph[from] + to);
}
void finalizeGraph() {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
if (graph[i][j] == -1) {
delete &graph[i][j];
}
}
}
}
private:
vector<int*> graph;
};
Now I want to implement an algorithm that is only supposed to work on the existing edges of the graph. In other words, the algorithm is not supposed to create new edges other than the ones that already exist in the input graph. I want to efficiently use memory and at the same time achieve the O(1) access to any edge between two vertices.
Is the space complexity of the above implementation of the graph effectively linear in the number of edges?
| No it is not, unless you can prove that the way you allocate and deallocate the edges is independent from n, which based on your description is unlikely.
Remember that Big O notation considers the worst case of your algorithm. Since you first allocate n^2 slots and then remove the non-existing edges, your algorithm runtime in the worst case is O(n^2), not O(n). In other words as n grows, your algorithm runtime also grows with O(n^2) since you have to allocate and deallocate edges that don't exists. This is true, unless you can prove that the way you allocate and deallocate the edges is independent from n.
In order to get to a liner runtime in terms of edges, you need a different data structure that in which the amount of work for edges is O(m), where m is the number of edges.
However, you can argue that if such a graph is given, i.e. the non-existing edges are removed, then the access time for each edge can be O(1), assuming your data structure supports it.
|
70,853,895 | 70,854,112 | Can't use std::source_location in VS2019 | Although I am using VS2019 with compiler flag /std:c++latest, but I am not able successfully include the header <source_location>. The following compile error appears:
fatal error C1083: Cannot open include file: 'source_location': No such file or directory
| Compiler support for C++20 - cppreference.com
C++20 feature
Paper(s)
GCC libstdc++
Clang libc++
MSVC STL
Apple Clang
std::source_location
P1208R6
11
19.29 (16.10)*
Verified on godbolt
|
70,853,973 | 70,854,021 | How to fix const char* must match previous return type error? | int plugin::feature(const InstanceInput &input) {
auto parse_word=[](const string input_text){
string text = input_text;
int i=text.find("%");
if(i!=-1){
return text.substr(0, i);
}
return "";
};
....
}
I am in Clion and it displays an error message at the 'return' statement saying that:
return type const char* must match previous return type std:basic_string<char> when lambda expression has unspecified specific return type
How to fix this?
| Instead of:
if(i!=-1){
return text.substr(0, i);
}
return "";
Try
if(i!=-1){
return text.substr(0, i);
}
return std::string();
auto return type for your lamda has been determined as string in the first case, and as char* in the second, which is a mismatch.
|
70,854,041 | 70,893,591 | Chromium Embedded Framework (CEF)- unresolved external symbol | Please tell me, I'm trying to figure out CEF in the simplest example.
I downloaded precompiled CEF binaries for windows:https://cef-builds.spotifycdn.com/index.html
There was an example inside - I launched and built it, compiled an exe file, it starts and works.
1.Now I have created a new project in VS2019 - connected to it the cef_sandbox.lib file and the header files that were in the example.
2.Compiled an empty main() - everything was compiled.
3.Now I'm adding just one CEF function from the example:
#include <iostream>
#include <windows.h>
#include "include/cef_command_line.h"
#include "include/cef_sandbox_win.h"
#include "tests/cefsimple/simple_app.h"
#pragma comment(lib,cef_sandbox.lib")
int main()
{
CefEnableHighDPISupport();
}
But an error occurs:
Error LNK2019 reference to an unresolved external symbol "void __cdecl
Cef Enable High DPI Support(void)" (?CefEnableHighDPISupport@@YAXXZ)
in the function main. CEF_my_example
C:\Users\Staxcel\source\repos\VS2019\Pak\CEF\CEF_my_example.obj 1
I can't figure out where and what I forgot to specify or include?
Why does this error occur in this case ?
| The function that you want to use is defined in the libcef.lib, so you need to include that one too.
Also you will need the libcef_dll_wrapper. Both are used by the cef-examples too.
Try to add them, and see if it loads then
#pragma comment(lib,"libcef.lib")
#pragma comment(lib,"libcef_dll_wrapper.lib")
|
70,854,987 | 70,855,291 | Finding the max lengths of strings to format a table output | I want to find the max length of specific attributes from a vector of Person objects.
Below is an example of a Person object:
Person::Person(string first_name, string last_name, int the_age){
first = first_name;
last = last_name;
age = the_age;
}
I have a vector that stores Person objects, and I must print all the people out in a table, like so:
First Name Last Name Age
---------- ------------ ----
John Cool-Johnson 15
Paul Bob 1000
2 people
I need to find the max length of each attribute of a Person in order to grow each column according to the maximum length of name or age. How can I do this?
So far, I have tried lambdas using this code:
unsigned int max_name = *max_element(generate(people.begin(),people.end(), [](Person a){return a.getFirstName()})).size();
But I am not sure if this even works at all.
I must use <iomanip>, but I have no clue how it works.
Is there a better way?
| Your use of std::max_element() is wrong. It takes 2 iterators for input, which you are not providing to it. It would need to look more like this:
auto max_name = max_element(
people.begin(), people.end(),
[](const Person &a, const Person &b){
return a.getFirstName().size() < b.getFirstName().size();
}
)->getFirstName().size();
Online Demo
Alternatively:
vector<string> names;
names.reserve(people.size());
for(const Person &p : people) {
names.push_back(p.getFirstName());
}
auto max_name = max_element(
names.begin(), names.end(),
[](const string &a, const string &b){
return a.size() < b.size();
}
)->size();
Online Demo
However, since you will probably also want to do the same thing for the Last Name and Age columns, I would suggest simply looping though the people vector manually, keeping track of the max lengths as you go along, eg:
string::size_type max_fname = 10;
string::size_type max_lname = 9;
string::size_type max_age = 3;
for(const Person &p : people)
{
max_fname = max(max_fname, p.getFirstName().size());
max_lname = max(max_lname, p.getLastName().size());
max_age = max(max_age, to_string(p.getAge()).size());
}
Then you can output everything in a table, eg:
cout << left << setfill(' ');
cout << setw(max_fname) << "First Name" << " " << setw(max_lname) << "Last Name" << " " << setw(max_age) << "Age" << "\n";
cout << setfill('-');
cout << setw(max_fname) << "" << " " << setw(max_lname) << "" << " " << setw(max_age) << "" << "\n";
cout << setfill(' ');
for(const Person &p : people)
{
cout << setw(max_fname) << p.getFirstName() << " " << setw(max_lname) << p.getLastName() << " " << setw(max_age) << p.getAge() << "\n";
}
cout << people.size() << " people\n";
Online Demo
|
70,855,214 | 70,855,271 | Why is the c++ program not outputting the modified pointer-to-pointer variable results in the caller function? | I am developing a tic-tac-toe board game in c++ for learning purposes, and I am passing a char** to a function that assigns the given parameter an array of pointers which stores a players name.
Upon variable assignment, I am able to print the results of the initialized variable in the function call to void initPlayerNames(char** playerNames) but when I return to the caller function the program does not print the results.
My understanding is that a pointer variable stores the address of another data structure, therefore I expect to print the results of the pointer variable after it has been modified in the function call.
Please help me understand where I am making a mistake
void initPlayerNames(char** playerNames) {
const int playerNameLength = 100;
cout << "Player one, enter your name: ";
char p1[playerNameLength];
cin.getline(p1, playerNameLength);
cout << "Player two, enter your name: ";
char p2[playerNameLength];
cin.getline(p2, playerNameLength);
char* names[2] = {p1, p2};
playerNames = names;
cout << "Player 1 = " << playerNames[0] << endl;
cout << "Player 2 = " << playerNames[1] << endl;
};
void game() {
char** playerNames = nullptr;
cout << "Welcome! \n";
initPlayerNames(playerNames);
cout << "Player 1 = " << playerNames[0] << endl;
cout << "Player 2 = " << playerNames[1] << endl;
};
Output
Player one, enter your name: Kevin Patel
Player two, enter your name: Steve Jobs
Player 1 = Kevin Patel
Player 2 = Steve Jobs
| The pointer playerNames is set like this:
char* names[2] = {p1, p2};
playerNames = names;
However, when the function initPlayerNames() exits, names, p1and p2 are all destroyed and thus playerNames points at unallocated memory.
Besides, playerNames itself in initPlayerNames() is a variable which is destroyed when the function exits (like in a function void func(int a), changes to a are not reflected in the caller function).
To fix this:
Declare the involved variables as static which means they will be allocated also when the function is not running. Note, however, that this is mostly to illustrate the lifetime issue, this solution is not without problems (not safe in multi-threaded applications and exposes seemingly local variables outside their function - it is like using global variables).
Pass a pointer or reference to playerNames. Being old-fashioned, I prefer a pointer so it is clearer that the passed argument may be changed:
void initPlayerNames(char*** playerNames) {
const int playerNameLength = 100;
cout << "Player one, enter your name: ";
static char p1[playerNameLength];
cin.getline(p1, playerNameLength);
cout << "Player two, enter your name: ";
static char p2[playerNameLength];
cin.getline(p2, playerNameLength);
static char* names[2] = {p1, p2};
*playerNames = names;
cout << "Player 1 = " << (*playerNames)[0] << endl;
cout << "Player 2 = " << (*playerNames)[1] << endl;
};
and call the function like this:
initPlayerNames(&playerNames);
|
70,855,282 | 70,855,593 | std::filesystem::recursive_directory_iterator with consistent path separation? | I just noticed that std::filesystem::recursive_directory_iterator uses different path separateors (i.e. / vs \) depending on whether it's on Windows or Linux, is there a way to make it return paths with '/' to make it consistent across systems?
This is how I am getting the paths:
for(auto& path: fs::recursive_directory_iterator(dir_path))
{
// Skip directories in the enumeration.
if(fs::is_directory(path)) continue;
string path_str = path.path().string();
}
What I mean is, the contents of path_str will be different between the two OSs (because the separators will be different), I would like them to be the same. I could just replace them on the final string, but that uses more cycles than if I can instruct the stl to use '/' for everything isntead.
| So, your problem has nothing to do with recursive_directory_iterator, which iterates on directory_entry objects, not paths. Your confusion probably stems from the fact that directory entries are implicitly convertible to paths, so you can use them as such.
Your problem is really about path::string(), which, as the documentation states, uses the native format (i.e. with a platform dependent separator). You would get the same problem regardless of how you get your path.
If you want to get / as the directory separator, use path::generic_string() instead to get the path in generic format.
for(auto& dir_entry: fs::recursive_directory_iterator(dir_path))
{
if(dir_entry.is_directory()) continue;
string path_str = dir_entry.path().generic_string();
}
|
70,855,489 | 70,855,563 | c++ function call - pass by reference calls pointer method / pass by value calls referense method | A function call is made in the code. In the first function call a pass by reference is performed calling the pointer function. In the second function call a pass by value is performed where the reference function is called.
Why is this so?
#include <iostream>
void f(int *p) { (*p)++; }
void f(int &p) { p-=10; }
int main() {
int x=0; f(&x); f(x); f(&x);
std::cout << x << "\n";
}
| x is an int variable. &x is taking the address of x, yielding an int* pointer.
f(&x) can't pass an int* pointer to an int& reference, but it can pass to an int* pointer, so it calls:
void f(int*)
f(x) can't pass an int variable to an int* pointer, but it can pass to an int& reference, so it calls:
void f(int&)
|
70,855,685 | 70,904,033 | compiler optimisations and threads | I have a program that performs a task in a thread and I wanted to have the option to terminate early with a key-press. Here is a MWE:
#include <chrono>
#include <iostream>
#include <thread>
int main(int argc, char *argv[]) {
char endChar = 0;// endChar is only written by keyboard thread
std::thread kbth([&endChar]() { std::cin >> endChar; });//this thread monitors the keyboard
kbth.detach();
std::chrono::seconds run_t{15};
bool running = true; // running could be written by main and task thread at
// same time (unlikely)
std::mutex task_mtx; // so protect with mutex
std::thread task([&running, &run_t, &task_mtx]() {
std::this_thread::sleep_for(run_t);
std::scoped_lock lock{task_mtx};
running = false;
}); //this thread performs the task
task.detach();
while (running) { //running is false when the task ends
if (endChar == 42) { // 42=*
std::cout << "key pressed" << std::endl;
std::scoped_lock lock{task_mtx};
running = false; //or when * is entered
break;
}
}
std::cout << "bye" << std::endl;
}
This works fine without compiler optimisations but fails with optimisations. Please can someone help me understand why this is happening? According to this compilers can optimise code as long as they don't change "the observable behavior of the program". So when this fails when optimisations are on doesn't this count as changing the observable behaviour? I tried with g++ and cl, summarised:
// clang-format off
// g++ version 11.2.1 fedora 64bit
// g++ -O0 -std=c++1z ../src/kbthread.cpp -o kbthread -l pthread //OK, exits gracefully when done or when key pressed
// g++ -O1 -std=c++1z ../src/kbthread.cpp -o kbthread -l pthread //fail, hang
// g++ -O2 -std=c++1z ../src/kbthread.cpp -o kbthread -l pthread //fail, hang
// cl version 19.29.30133 for x64 windows
// cl /EHsc -std:c++17 -Od -MD ../src/kbthread.cpp //OK, exits gracefully when done or when key pressed
// cl /EHsc -std:c++17 -O1 -MD ../src/kbthread.cpp // fail, immediately prints "key pressed\nbye"
// cl /EHsc -std:c++17 -O2 -MD ../src/kbthread.cpp // fail, immediately prints "key pressed\nbye"
// clang-format on
| OK, as comments below indicated threading issues @ François Andrieux I have "fixed" it using atomics with the code below:
int main(int argc, char *argv[]) {
std::atomic_char endChar{0};
std::thread kbth([&endChar]() { // this thread monitors the keyboard
char buff = 0;
std::cin >> buff;
endChar = buff;
});
kbth.detach();
std::chrono::seconds run_t{10};
std::atomic_bool running{true};
std::thread task([&running, &run_t]() { // this thread performs the task
std::this_thread::sleep_for(run_t);
running = false;
});
task.detach();
while (running.load()) { // running is false when the task ends, so the program ends
if (endChar.load() == 42) { // 42=*
std::cout << "key pressed" << std::endl;
running = false; // or when * is entered, so the program ends early
break;
}
}
std::cout << "bye" << std::endl;
}
Still not sure about the use of detach but seems to work OK now.
|
70,856,124 | 70,864,722 | What is the most efficient (or just best practice) way to set up a function that returns a reference to an std:vector but sometimes a default empty? | Take the following function (which obviously doesn't compile).
const std::vector<int>& getMyVector()
{
if (something)
return std::vector<int>();
if (somethingElse)
return m_myVector;
return std::vector<int>();
}
Assume that m_myVector is large or is otherwise not well suited to being returned by copy and so must be returned by reference.
What is the most efficient way to structure the code to allow this logic while also allowing a return by reference? I can see two options. The first would be to change this to return a pointer to the vector instead of a reference and then return null instead of an empty vector. The other would be to have a static const empty vector and return that. I don't particularly like either of those options, so I'm wondering if there's a better way.
Edit: Please don't use the example function as a literal representation of what I'm trying to illustrate. The point is that I have a function that can either return a real vector full of data or it can return a default empty vector based on certain conditions. Also, if it matters, my real code isn't even returning a simple member variable, it's a vector that's stored inside a hash_map.
| Despite your hesitations, I recommend defining a static empty result vector wherever you have defined m_myVector.
std::vector<int> m_myVector;
static const std::vector<int> m_emptyResult;
Your code can then both compile and avoid copies.
const std::vector<int>& getMyVector()
{
if (something)
return m_emptyResult;
if (somethingElse)
return m_myVector;
return m_emptyResult;
}
Or more tersely:
const std::vector<int>& getMyVector()
{
if ( !something && somethingElse )
return m_myVector;
return m_emptyResult;
}
|
70,856,298 | 70,856,423 | c++ passing template param by shared pointer | wanna ask one question: I have two classes A and B, few data types can only be defined in class B, but A as a higher level class also need use these data types defined in class B. So, I defined a template function in class A, named define_spline(), I can using robot_1 (i.e., class B) class's pointer to passing the type, but what I want is the class A can have a member object of these types defined in B class (robot_1 struct sp{}). I try to write a template class for whole A, named A2, but I got error 'rp1 is not a type name', why this is ok in class A define_spline() function, but not work for class A2 ? and what's the correct way to do so?
#include<Eigen/Dense>
#include<iostream>
#include <unsupported/Eigen/Splines>
#include <fstream>
#include<memory>
class robot_1
{
private:
static const int nState =9;
static const int nControl =3;
public:
// robot_1(int nx, int nu)
// printf("robot_1 constructor \n");
// }
~robot_1(){}
robot_1()
{
printf("empty robot_1 constructor \n");
}
struct sp
{
using SplineX = Eigen::Spline<double, nState>;
using SplineFittingX = Eigen::SplineFitting<SplineX>;
}sp_;
};
using robotPtr = std::shared_ptr<robot_1>;
class A
{
private:
std::string name = "class_a";
int nState;
int ncontrol;
// Ty::SplineX sp_memeber;
public:
A(){}
~A(){}
template <typename Ty>
void define_spline(const Ty, int a)
{
using SplineX_A = typename Ty::SplineX;
using SplineFittingX_A = typename Ty::SplineFittingX;
SplineX_A spA;
std::cout<<a<<std::endl;
}
robotPtr robotPtr_;
};
template <typename Type2>
class A2
{
private:
Type2::SplineX spx;
Type2::SplineFittingX spxF;
int nState;
int nControl;
public:
A2(){}
~A2(){}
A2(int nx, int nu){
nState = nx;
nControl = nu;
}
};
int main()
{
robotPtr rp1 = std::make_shared<robot_1>();
rp1 ->sp_;
A a;
a.robotPtr_ = std::make_shared<robot_1>();
a.define_spline(rp1->sp_, 6); // here no error
// A2
A2<rp1->sp_> a2(9,3); // error
}
Thanks in advance
| A2<rp1->sp_> a2(9,3); // error
Template parameters are always types (until very recently, but this is not material right now). rt1->sp_ is not a type. It is a discrete object. If you look where it appears, struct sp is the type in question. And sp_ is an instance of that type. Types, and objects, are two completely different things, in C++. They are not interchangeable with each other. When something must be a type, it has to be a type, and not an object. When something must be an object it has to be an object, and not a type. Template parameters are types (until very recently, but this is still not material right now).
You might get this to work by using A2<decltype(rp1->sp_)>. The expression decltype(...) resolves to whatever the reference type is. It basically "translates" an object, of some kind, to its type. There are a few rules, and several nuanced rules to decltype(), that your favorite C++ textbook will be happy to explain to you, which is where you can look for more information and examples.
|
70,856,484 | 70,856,533 | How to use find function on map/unordered_map in multi-thread programming | I read somewhere saying find() is not thread safe on STL map because when other thread is inserting to the map, the map itself is re-balancing, so find() may not return the proper iterator even the entry is indeed in the map. My observation tends to echo this. How about hash map (unordered_map)? I fear it may have the same issue, but not clear why.
So what is the proper way to call find() in a multithreaded context or is there any replacement?
example can be:
std::map<int, std::string> the_map;
in thread 1:
// Step1
_mutex.lock();
the_map[1] = "this";
_mutex.unlock();
...
// Step3
if (the_map.find(1) == the_map.end()) {
throw("Cannot find!");
}
in thread 2
// Step2
_mutex.lock();
the_map[2] = "that";
_mutex.unlock();
If step 2 and 3 are taking places concurrently, then step 3 could be disrupted.
| None of the standard library containers are threadsafe. If you want to do this kind of thing, you must protect all accesses (both read and write) by a mutex.
|
70,856,516 | 70,856,702 | Boolean check before variable declaration in if statement | I have this code:
#include <iostream>
int function() {
return 2;
}
int main( void )
{
int integer = 5;
if (integer == 5 && int i = function()) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
It's giving an error:
test.cpp: In function ‘int main()’:
test.cpp:10:23: error: expected primary-expression before ‘int’
10 | if (integer == 5 && int i = function()) {
| ^~~
test.cpp:10:22: error: expected ‘)’ before ‘int’
10 | if (integer == 5 && int i = function()) {
| ~ ^~~~
| )
The order of the parts in the if statement is important to me; I only want to call function() if the first check is true. Options I found to fix the error:
int i;
if (integer == 5 && (i = function())) {
And this, but this does not have the wanted behavior (it always calls function):
if (int i = function() && integer == 5) {
Any other options? I'm also unsure what rule I am violating with my first piece of code. Why isn't it ok?
| As an alternative to the other answers, since C++17 you can also declare a variable in the scope of the if in addition to the condition (rather than using a declaration directly in the condition):
if(int i; integer == 5 && (i = function()))
You might want to add an initializer to i for a default value.
|
70,856,563 | 70,856,902 | Vscode g++ it isn't finding .cpp definition files | I'm trying to compile a c++ example with multiple .cpp and .hpp files, but g++ doesn't find any member function definition.
main.cpp:
#include <iostream>
#include "Person.hpp"
int main()
{
std::cout << "HELL!\n";
Person a{"Jiraya"};
std::cout << a.getName() << "\n";
a.setName("Niko");
a.do_smt();
}
Person.hpp:
#pragma once
#include <string>
using std::string;
class Person
{
private:
string name;
public:
Person();
Person(const string &n);
void do_smt();
string getName(){return name;}
void setName(const string& n);
Person.cpp:
#pragma once
#include <iostream>
#include "Person.hpp"
Person::Person(const string &n) : name{n}
{
}
void Person::setName(const string &n)
{
name = n;
}
void Person::do_smt()
{
std::cout << "???";
}
Tasks.json:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"-iquote${workspaceFolder}/headers"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
Terminal output:
> Executing task: C/C++: g++ build active file <
Starting build...
/usr/bin/g++ -fdiagnostics-color=always -g /home/raijin/Documents/Code/C++/sandbox/main.cpp -o /home/raijin/Documents/Code/C++/sandbox/main -iquote/home/raijin/Documents/Code/C++/sandbox/headers
/usr/bin/ld: /tmp/ccN0pJKE.o: in function `main':
/home/raijin/Documents/Code/C++/sandbox/main.cpp:9: undefined reference to `Person::Person(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/usr/bin/ld: /home/raijin/Documents/Code/C++/sandbox/main.cpp:11: undefined reference to `Person::setName(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/usr/bin/ld: /home/raijin/Documents/Code/C++/sandbox/main.cpp:12: undefined reference to `Person::do_smt()'
collect2: error: ld returned 1 exit status
Build finished with error(s).
Terminal will be reused by tasks, press any key to close it.
Here is the project folder structure:
I did add "-iquote${workspaceFolder}/headers" arg in tasks.json to locate .hpp in a subdirectory. It doesn't seem to work with .cpp files. What do I do?(Even if I move Person.cpp to ${workspaceFolder} results the same terminal output)
| In your tasks.json you are using the default ${file} which means compile only the active file and not all source files in your folder structure.
The VSCode documentation explains how to fix this for the case of all source files in the same folder here: https://code.visualstudio.com/docs/cpp/config-linux#_modifying-tasksjson
The fix is to replace ${file} with "${workspaceFolder}/*.cpp"
In your case you have more than 1 folder containing source files. You can apply a similar fix to the second folder by adding: "${workspaceFolder}/classes/*.cpp"
so the whole tasks.json would be:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${workspaceFolder}/*.cpp",
"${workspaceFolder}/classes/*.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"-iquote${workspaceFolder}/headers"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
|
70,856,853 | 70,856,923 | Is it allowed to extend the std::numbers namespace with new definitions? | I have several mathematical numeric constants defined in a large codebase. Several of which (but not all) are now duplicated in the new C++20 <numbers> header. I'd like to have them all in one place; is it allowed to extend the std::numbers header to include the ones not already defined?
|
is it allowed to extend the std::numbers header to include the ones not already defined?
No, you may not add definitions to std namespace nor its subnamespaces (except for class template specialisations in cases where that isn't explicitly disallowed).
You can instead have them all in one place in your own namespace with using declartions:
namespace Casey
{
inline constexpr double missing_number = 123;
using std::numbers::e;
// ...
}
Instead of using each number individually, you could use using namespace std::numbers, but that has the caveat that future standard versions may add numbers whose names may potentially conflict with yours, breaking future compatibility of your header.
|
70,857,051 | 70,857,159 | What does this char string related piece of C++ code do? | bool check(const char *text) {
char c;
while (c = *text++) {
if ((c & 0x80) && ((*text) & 0x80)) {
return true;
}
}
return false;
}
What's 0x80 and the what does the whole mysterious function do?
| Rewriting to be less compact:
while (true)
{
char c = *text;
text += 1;
if (c == '\0') // at the end of string?
return false;
int temp1 = c & 0x80; // test MSB of c
int temp2 = (*text) & 0x80; // test MSB of next character
if (temp1 != 0 && temp2 != 0) // if both set the return true
return true;
}
MSB means Most Significant Bit. Bit7. Zero for plain ascii characters
|
70,857,171 | 70,857,271 | Why does my random function generate the same number every time I call it in a loop? | I have my random function generating a pseudo-random number in the range:
double Utils::randomNumber(int min, int max)
{
assert(min < max);
srand(time(nullptr));
return (max - min) * ((double)rand() / RAND_MAX) + min;
}
However, when I call it in a loop, I always get the very same number, although I seed the sequence:
for (int i = 0; i < m_inputs; ++i)
{
m_weights.push_back(Utils::randomNumber(0, 1));
}
Output:
Weights: [0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561]
| Seeding repeatedly with tight timings will generate the same initial result after-seed every time. If seeding once per process isn't an option due to caller locality, then you should provide an initial static-state instead. What may work for you is this:
#include <random>
double Utils::randomNumber(int min, int max)
{
static std::mt19937 rng{ std::random_device{}() };
std::uniform_real_distribution<double> dist(min, max);
return dist(rng);
}
Note there is an intrinsic problem on the potential ceiling of the uniform real range, and it may be applicable to your usage (not likely, but never say never). See the notes here for more information.
|
70,857,479 | 70,857,514 | How do you forward declare header files? | I'm trying to forward declare the header files #include<memory_resource> and #include<deque>. But the following doesn't seem to work. This is pseudo-code:
A.hpp
class memory_resource;
class deque;
class A
{
public:
...
private:
std::pmr::deque<index_t> tempQueue;
}
A.cpp
#include<memory_resource>
#include<deque>
...
| No, you cannot "forward declare header files".
In order to define a member of a given type, that type must first be defined. You can achieve that by including the header that defines it.
Since you define the class A in A.hpp and that class has a member of type std::pmr::deque<index_t>, you must include the definition of std::pmr::deque into A.hpp, before the definition of the class A.
Here is a working example:
// A.hpp
#include <deque>
#include <memory_resource>
using index_t = int;
class A
{
std::pmr::deque<index_t> tempQueue;
};
|
70,857,562 | 70,857,655 | Is this good enough to check an ascii string? | bool is_ascii(const string &word) {
if((unsigned char)(*word.c_str()) < 128){
return true
}
return false
}
I want to check whether a string is ascii string. I also saw such a function to detect whether a string is ascii chars or not:
bool is_ascii(const string &str){
std::locale loc;
for(size_t i = 0; i < str.size(); i++)
if( !isalpha(str[i], loc) && !isspace(str[i], loc))
return false;
return true;
}
Which one is better or more reliable?
| ASCII is a lot more than just alpha characters and spaces. If you want to accept all ASCII, just use your second example and change the if:
if(str[i] < 0 || str[i] > 0x7f)
return false;
|
70,857,634 | 70,858,614 | Generating random number until they repeat in C/CPP | I have a problem with a program in C or CPP. I need to make a program that will generate a random nubers in range of 1-365, but when the program generates the same number as it allredy did, the program will write the count of numbers and repeat it self again 100 times.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int lower = 1, upper = 365, count = 365;
srand(time(0));
printf("The random numbers are: ");
for (int i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
printf("%d ", num);
}
return 0;
}
I know how to make the generator for random numbers but i have problem with stopping it when the numbers reapeat.
| Based on what you want to do, this (not tested) code could give you into the right way:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// declare the lower and upper limits of the rand numbers
int lower = 1, upper = 365;
// number of repetitions of the process.
// this will repeat the same process 100 times.
int count = 100;
// set the random seed
srand(time(0));
// loop for the repetition of the process
for (int x = 0; x < count; x++) {
// value to count the quantity of random numbers of this execution
int sum = 0;
// flag to break the 'while' loop
bool canContinue = true;
// array of booleans. 365 because you have random numbers between 1 - 365
// when a random numbers is generated, the array in that position will be set to true
// when another random number is generated we check if the position of his value is true
// to validate is that number is already set.
bool numbers[365] = {};
// loop generates random numbers until a repeat number is found
while (canContinue) {
// retrieve a random number
int num = (rand() % (upper - lower + 1)) + lower;
// validate if the generated number position is already taken
if (numbers[num - 1] != true) {
// set position of array taken. num - 1 because positions in arrays start from 0
numbers[num - 1] = true;
// count +1 new random number not repeated of this exectution
sum++;
} else {
// the position of the random number is taken, means is a repeated number
canContinue = false;
}
}
// print the result of this loop and countinue until we have 100 repetitions of the process
printf("step %d: %d", x + 1, sum);
}
return 0;
}
In order to detect a random number is repeated, my approach was have an array of bools projecting that each number has an available position. [false, false... until 365 positions].
When a number is generated his position will be true (position = generated number - 1). In case the first number is 2 the array will have a representation like this: [false, true, false , false, ....and the others falses values].
When other number is generated we check his position, in the case of the repetition of number 2 the result of the array[2 - 1] will be true and I inmediatilly conclude the loop.
|
70,857,644 | 70,857,746 | Implicit conversion to templated struct? | template <typename T>
struct Foo {
T var;
Foo (const T& val){
var = val;
}
};
template <typename T>
void print(Foo<T> func){}
int main() {
Foo f=3;
print(f); // Works
print(3); // Doesn't work
}
f is a well defined instance of Foo, so obviously it works. But since 3 is convertible (implicitly, I believe) to Foo, why doesn't print(3); work?
If it's not an implicit conversion, how could I make it so?
I would really like to avoid print(Foo(3));
| Template argument deduction won't consider implicit conversions. To get the desired call syntax, you could add an overload for print like this
template <typename T>
void print(T a) // selected if T is not a Foo specialization
{
print(Foo{a}); // call print with a Foo explicitly
}
If the argument to print is already a specialization of Foo, the overload taking a Foo<T> will be selected.
Here's a demo.
|
70,857,663 | 70,863,332 | How to make a deep copy of an array of pointers | I am in the process of creating a chess engine and I am using a chess engine that can be found here for it's ChessBoard and Piece classes. as part of the engine I have to make a deep copy of an instance of the ChessBoard class and and I am having a great deal of difficulty doing this. I have tried editing the copy constructor in the class in multiple ways and changing the my own code but to no avail.
Here is the problematic part of my code:
move_list = j->data().board->getPossibleMoves(board->flip(colour));
for (auto k : move_list) {
print_board(j->data().board);
current_node.board = j->data().board;
current_node.board->moveTo(std::tuple<char, char>(std::get<0>(k), std::get<1>(k)), std::tuple<char, char>(std::get<2>(k), std::get<3>(k)));
std::cout << "After :" << std::endl;
print_board(j->data().board);
j->insert(current_node);
//"j" is a node in a tree class
//"k" is structured like this: std::vector<std::tuple<char, char, char, char>>
//"MoveTo" moves a chess piece to a location on the chess board
This yields an output like this:
Before :
R N B Q K B N R
P P P P P P P P
p p p p p p p p
R N B Q K B N R
After :
R N B Q K B N R
P P P P P P P P
p
p p p p p p p
R N B Q K B N R
As you can see, the value of "j->data()" changes even though I change the new "ChessBoard" therefore "j->data()" and the new board are pointing to the same location in memory.
Here are the copy constructors of ChessBoard and Piece:
//board.h
ChessBoard(const ChessBoard& rhs) { //Copy constructor
//This is the section that I'm concerned about ↓ (Until the other comment)
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = new Piece(rhs.squares[x][y]->colour);
piece->value = rhs.squares[x][y]->value;
piece->symbol = rhs.squares[x][y]->symbol;
piece->pieceType = rhs.squares[x][y]->pieceType;
piece->moveCount = rhs.squares[x][y]->moveCount;
ChessBoard::squares[x][y] = piece;
}
}
//This is the section that I'm concerned about ↑ (Until the other comment)
for (auto itr = rhs.promotedQueens.begin(); itr != promotedQueens.end(); ++itr) {
Piece piece = **(itr);
promotedQueens.push_back(&piece);
}
whiteCastled = rhs.whiteCastled;
blackCastled = rhs.blackCastled;
plyCount = rhs.plyCount;
allowIllegalMoves = rhs.allowIllegalMoves;
improvedDrawDetection = rhs.improvedDrawDetection;
ChessBoard::transpos_table.initializeHash(this, Colour::White);
initializeOriginalSquares();
}
//Pieces.h
Piece(const Piece& rhs) { //Copy constructor
value = rhs.value;
symbol = rhs.symbol;
pieceType = rhs.pieceType;
moveCount = rhs.moveCount;
colour = rhs.colour;
};
To summarize, how could I make a copy constructor that makes a deep copy of the ChessBoard class or create a deep copy of it in some other way?
| You are using runtime polymorphism for your pieces. I.e. you have a chess board of pointers to Piece, which can be of different types (Horse, Bishop and so on). And your problem is that, when you copy construct your chess board, you need to copy construct each piece, but you only hold a Piece* to a polymorphic object. You need a virtual copy constructor. As suggested in the link, you can:
add a pure virtual clone method to your Piece base class, and
override that method for each of your final classes, doing the copy construction there.
The code below uses smart pointers instead of raw pointers. Notice *this is passed to std::make_unique to invoke the copy constructor. If you passed nothing, you would be invoking the default constructor. The same applies when using raw pointers and new.
[Demo]
class Piece {
public:
virtual std::unique_ptr<Piece> clone() = 0;
};
class Horse : public Piece {
public:
virtual std::unique_ptr<Piece> clone() override {
return std::make_unique<Horse>(*this);
};
};
ChessBoard(const ChessBoard& cb) {
for (size_t x{0}; x < board_size; ++x) {
for (size_t y{0}; y < board_size; ++y) {
squares[x][y] = cb.squares[x][y]->clone();
}
}
}
Some other related links: another question asking about virtual copy constructors. And two useful answers to that question, 1, and 2.
|
70,857,677 | 70,858,076 | Is there a way to get ascii value of a string representing a special character? | I'm working on a compiler and I simply want to be able to read the literal '\n' as it's ascii value (10) in my language.
But there are actually more escape sequence like \n and I don't want to attempt to account for all of them by myself when C++ already is fully capable of that.
I basically need a way to take the array/string:
const char* s1 = {'\\'/* a simple slash */, 'n', '\0'}; // "\\n"
std::string s2 = "\\x002b"; // {'\\', 'x', '0', '0', '2', 'b', '\0'}
and treat it as the C/C++ compiler would have.
I'd like a std functions to do it or if at runtime I could interact with the C++ compiler and let it do the job, something like this:
char c1 = exec("'%s'", s1); // would return '\n' as one character (ascii 10)
char c2 = std::parse_char_literal(s2); // would return '+' (ascii 43)
Thanks.
| So after Remy Lebeau's comment and a rethink i decided to write my own code to handle most of the functionality of the C/C++ compiler.
Using the special characters table from here I decided to not implement special characters which are more than 1 character long because I'm lazy.
That leaves \n \t \v \b \r \f \a \\ \? \' \" \0.
That is my code:
char escSeqToChar(std::string v)
{
if (v[0] == '\\' && v.size() == 2)
{
switch (v[1])
{
case 'n':
v = "\n"; break;
case 't':
v = "\t"; break;
case 'v':
v = "\v"; break;
case 'b':
v = "\b"; break;
case 'r':
v = "\r"; break;
case 'f':
v = "\f"; break;
case 'a':
v = "\a"; break;
case '\\':
v = "\\"; break;
case '?':
v = "\?"; break;
case '\'':
v = "\'"; break;
case '\"':
v = "\""; break;
case '0':
v = "\0"; break;
default:
break;
}
}
if (v.size() > 1) printf("ERROR_CHAR_TOO_LONG"); exit(-1);
return v[0];
}
|
70,857,964 | 70,858,061 | Why does my code to USACO Silver Breed Counting not work? | This is my code:
#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("bcount.in", "r", stdin);
freopen("bcount.out", "w", stdout);
int n, q;
cin >> n >> q;
vector<int> holsteins(n);
vector<int> guernseys(n);
vector<int> jerseys(n);
for (int i = 0 ; i < n ; i++) {
holsteins[i+1]=holsteins[i];
guernseys[i+1]=guernseys[i];
jerseys[i+1]=jerseys[i];
int a;
cin >> a;
if (a==1) holsteins[i+1]++;
else if (a==2) guernseys[i+1]++;
else jerseys[i+1]++;
}
for (int i = 0; i < q ; i++) {
int a, b;
cin >> a >> b;
cout << holsteins[b]-holsteins[a-1] << " " << guernseys[b]-guernseys[a-1] << " " << jerseys[b]-jerseys[a-1] << "\n";
}
return 0;
}
When I run it, it fails to pass the sample case and the official grader says that there was a runtime error or memory fail. I suspected it had something w/ input output but there wasn't. What's wrong here?
| There are multiple bugs in the shown code, assuming that it even compiles, because:
#include <bits/stdc++.h>
This is a non-standard header file. On some C++ compilers the shown code won't even compile. Assuming that the shown code compiles:
cin >> n >> q;
vector<int> holsteins(n);
This input is not checked for validity. Invalid or negative input results in undefined behavior.
for (int i = 0 ; i < n ; i++) {
holsteins[i+1]=holsteins[i];
This results in undefined behavior when i is n-1, so i+1 is n, and this assigns to holsteins[n], which does not exist.
guernseys[i+1]=guernseys[i];
jerseys[i+1]=jerseys[i];
Same bug here, undefined behavior when accessing a nonexistent value in the vector.
int a;
cin >> a;
if (a==1) holsteins[i+1]++;
Continuation/variation of the first bug. Invalid or negative input results in undefined behavior.
int a, b;
cin >> a >> b;
cout << holsteins[b]-holsteins[a-1] << " " << guernseys[b]-
All of the above bugs, combined. Undefined behavior due to invalid or negative input, or due to access to nonexistent vector values (when b or a is n or greater).
Those are all the reason I could see why the shown code will not work correctly due to undefined behavior.
|
70,858,122 | 70,858,448 | Cannot find c++ boost header files on Ubuntu 20.04 LTS using apt installation | I have just upgraded my server to ubuntu 20.04 LTS.
I am now trying to various different code packages on it and receiving errors relating to the boost installation.
Rather than building from source, I have installed boost 1.71.0 using apt:
sudo apt-get install libboost-all-dev
However, when I try and compile code I am getting errors such as:
fatal error: boost/algorithm/string/trim.hpp: No such file or directory
15 | #include <boost/algorithm/string/trim.hpp>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
boost/log/sinks/text_ostream_backend.hpp: No such file or directory
6 | #include <boost/log/sinks/text_ostream_backend.hpp>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I have spent the last 3 hours trying to find those hpp files with no success. There is nothing in:
/usr/local/include/
/usr/local/lib/
/usr/lib/
/usr/include/boost *doesn't exist*
Any idea what could be wrong?
I'm trying to avoid installing boost from source, rather than the Ubuntu package but do I have to?
| Managed to resolve the issue.
Turns out that because I had a previous boost installation from a manual installation (before I upgraded to 20.04 LTS) and had deleted those files manually, further re-installs via apt were not recreating the files in usr/include/, due to other packages relating to boost still installed in the system.
The recovery was to run apt list --installed '*boost*' and then uninstall any of those linked packages.
After doing that running sudo apt install libboost-all-dev recreated the /usr/include/boost directory with all the header files.
This process was listed in the answer on: https://askubuntu.com/questions/1161393/i-deleted-usr-include-boost-installing-libboost-all-dev-wont-bring-headers-ba
|
70,858,271 | 70,858,479 | Is there a modern alternative to constructor chaining in C++? | I have a class Foo with 2 constructors, A and B.
Constructor B contains some important setup code and should always be run when an object is instantiated.
At the end of constructor A, I want to execute the important setup code that is inside B.
Below is an example of the described setup which involves connecting to a database.
class Foo {
public:
// Constructor A
Foo(std::string db_path) {
// ... Some input validation and retry logic for opening the database.
Database db = ...
// ...
Foo(db); // Impossible to directly call another constructor from the body of a constructor.
}
// Constructor B
Foo(Database db)
: db_(db) {
// ... Some important setup code.
}
private:
Database db_;
};
I believe it isn’t possible to call a constructor from another constructor’s body in C++ like you can in other languages such as C#.
I know that C++11 has the ‘delegating constructors’ feature, however I don’t believe I can make use of this because I have to perform tasks such as input validation and setting up retry logic in the body of constructor A.
One alternative that has been suggested here is to extract out the important setup code in constructor B into a private init method and have both constructors just call that init method.
This works well for my use case, however I am wondering if there is a modern way of accomplishing constructor chaining in C++.
Thanks!
| You could create a private function (or a free function with internal linkage) to initialize the parameters to your delegate constructor. For example:
class Foo {
private:
Database connect_to_db(const std::string& db_path) {
// Validation and retry logic
}
public:
Foo(const std::string& db_path)
: Foo{connect_to_db(db_path)}
{}
Foo(Database db)
: db_{db}
{
// Important setup code
}
private:
Database db_;
};
|
70,858,474 | 70,858,593 | C++ No matching member function for call to 'erase'? | Alright, so I am building a game that requires that I am able to add and remove a *Fighter object.
I first declare member variable fighter here
std::vector<Fighter*> fighter;
I then implement Add and Remove like this:
void Game::AddFighter(Fighter* f) {
fighter.push_back(f);
}
void Game::RemoveFighter(Fighter* f) {
if ( std::find(fighter.begin(), fighter.end(), f) != fighter.end() )
{
fighter.erase(f); //Error here
}
}
On the line indicated above, Im getting the error
No matching member function for call to 'erase'
I understand that the member calling erase must be an iterator, however I don't know how to do that in the context of what I am trying to achieve. I know that the above code works for detecting a Fighter* if the Fighter* has been added - how do I use the erase() function?
| You need take the iterator returned by std::find() and pass it to vector::erase(), eg:
void Game::RemoveFighter(Fighter* f) {
auto iter = std::find(fighter.begin(), fighter.end(), f);
if ( iter != fighter.end() ) {
fighter.erase(iter);
}
}
Alternatively:
void Game::RemoveFighter(Fighter* f) {
decltype(fighter)::iterator iter;
if ( (iter = std::find(fighter.begin(), fighter.end(), f)) != fighter.end() ) {
fighter.erase(iter);
}
}
Which can be re-written as this in C++17 or later:
void Game::RemoveFighter(Fighter* f) {
if ( auto iter = std::find(fighter.begin(), fighter.end(), f); iter != fighter.end() ) {
fighter.erase(iter);
}
}
Alternatively, if you are using C++20 or later, you can use std::erase() instead:
void Game::RemoveFighter(Fighter* f) {
std::erase(fighter, f);
}
|
70,858,604 | 70,858,696 | Howto call c++ member function as async call from QML | I'm calling a Q_INVOKABLE member function from a QML. The GUI freezes until the function is fully executed. I've some network operations going on in the invokable function therefore I want to GUI to continue exec and don't block for function to be completed.
QT documentation contains WorkerScript QML but that doesn't fulfill my requirement as I cannot call invokable function inside .mjs file.
Is their a QT way of how to deal with such problem ?
PS: I've exposed my C++ class to QML as below
Engine.rootContext()->setContextProperty("myClass", &obj);
And in the qml, I'm calling the member function as:
onTriggered: {
myClass.myFunction( ... ); // This function needs to be executed async
}
| The async model does not exist in qml, this is why workerscript has been added.
To get a similar behavior on the c++ side, you would have to use QThread. To pass the results of your computation back to QML once the worker thread finish, you can, on the QML side, connect a callback to a given signal emitted by your class once the worker thread is done. To create the connection in QML, you might have to use the connection class [ https://doc.qt.io/qt-5/qml-qtqml-connections.html ], depending on how your c++ class is exposed to qml.
|
70,858,735 | 70,881,749 | Delegates - What's the difference between Add() and AddUObject()? | When binding a Multi Cast Delegate, what is the use differences between Add() and AddUObject()?
I've been using AddUObject() on all of my bindings and they seems to work fine which has me wondering what the base Add() version is used for.
Ive read the information on this page :
Unreal Documentation - Multicast Delegates
But I'm not quite sure the appropriate place to use each one. In what scenario would I use Add() or AddUObject()?
Thanks!
| Add takes in an FDelegate.
AddUObject is syntactic sugar for creating a templated delegate and binding it to the provided UObject, then calling Add with the created delegate.
It is just this:
template <typename UserClass, typename... VarTypes>
inline FDelegateHandle AddUObject(const UserClass* InUserObject, typename TMemFunPtrType<true, UserClass, void (ParamTypes..., VarTypes...)>::Type InFunc, VarTypes... Vars)
{
return Add(FDelegate::CreateUObject(InUserObject, InFunc, Vars...));
}
|
70,859,082 | 72,334,487 | How to set version of a Qt application (made by QtIF)? | Just noticed a File version (4.2.0.0) from a Qt application, when mouse goes over the file. However that seems to be the QtIF version, not my application version.
How to set that (mouser over) version of a Qt application (made by QtIF)?
| This may be considered the expected behavior (f.ex. when used as an online installer), as the installer is able to install multiple versions of your program and/or upgrade your installation once a new version of your software becomes available. So, the installer is not directly related to a specific version of your software. See for example the Qt installer itself.
If you really want to control the version number, you should compile the installer from source and change the version string of the installer itself by slightly modifying the source code. In case you use the installer as a pure offline installer, this may indeed be appropriate.
|
70,859,130 | 70,859,902 | How to restore default setting in VS Code | I was playing with VS code settings (I wanted to explore VS Code) and suddenly the code editing got changed. Previously the code was more colourful and there were different colours for different keywords. Now my code is mostly white. Please help me to get back to default code formatting settings.
| To revert the settings completely, open the settings JSON file by bringing up the command palette (Ctrl+Shift+P) and running the command Preferences: Open Settings (JSON). Delete everything in there and save the file.
However, you might just have switched to a different theme by accident. To check that, open the theme chooser (Ctrl+K, T) and try the other themes.
|
70,859,260 | 70,863,113 | Passing vector by reference to another class/file | I have 2 sets of header+source files. One with the Main GUI class and the other with a Derived GUI class (Main window that opens a second window).
In the Main class I have a vector of strings. I can pass that vector by reference by calling a function in the Derived class and pass it by reference. I can use and update that vector in this function and the changes will be available in the Main class/file. So far so good.
The next thing I would like to do is use this passed by reference vector in all functions in the Derived class.
Up to now, I created and 'extern' vector in a "common" set of header+source.
This make it a global vector, and although its working, it is not the most elegant way.
Is there an alternative way to make the vector available to all functions in the Derived GUI class/file (and add/edit elements that are available in the Main GUI class/file later on)?
MainFrame.h
class wxMainFrame: public GUIFrame
{
public:
wxMainFrame(wxFrame *frame);
~wxMainFrame();
DerivedFrame *m_DerivedFrame;
private:
std::vector<wxString> vwsM3;
....etc
}
DerivedFrame.h
class DerivedFrame: public OtherFrane
{
public:
DerivedFrame( wxWindow* parent );
~DerivedFrame();
private:
std::vector<wxString> vwsM4;
void PassVector(std::vector<wxString> &vwsM);
void USEvwsM();
....etc
}
MainFrame.cpp
wxMainFrame::wxMainFrame(wxFrame *frame) : GUIFrame(frame)
{
m_DerivedFrame = new DerivedFrame(this);
m_DerivedFrame->PassVector(&vwsM3);
}
DerivedFrame.cpp
DerivedFrame::DerivedFrame ( wxWindow* parent ) : OtherFrame( parent )
{
//
}
void DerivedFrame::PassVector(std::vector<wxString> &vwsM)
{
vwsM.push_back("Something");
}
void USEvwsM()
{
// ??
}
OnInit() (The vector vwsM3 is not known here because its in a seperate header+source file)
IMPLEMENT_APP(wxMainApp);
bool wxMainApp::OnInit()
{
wxMainFrame* frame = new wxMainFrame(0L);
frame->SetIcon(wxICON(aaaa)); // To Set App Icon
frame->Show();
return true;
}
|
To derived class add one more pointer field:
class DerivedFrame: public OtherFrame {
.......
private:
std::vector<wxString> * pvwsM3 = nullptr;
.......
};
Modify PassVector() method to fill pointer:
void DerivedFrame::PassVector(std::vector<wxString> & vwsM) {
pvwsM3 = &vwsM;
}
Use pointer now:
void DerivedFrame::USEvwsM() {
assert(pvwsM3); // Check that we don't have null pointer, you may throw exception instead.
pvwsM3->push_back("Something");
}
Remaining code is same as you have. Alternatively you may pass vector to constructor of DerivedFrame, which is more reliable than calling PassVector() separately (which you may forget to call, while constructor you always call):
DerivedFrame::DerivedFrame(wxWindow* parent, std::vector<wxString> & vwsM)
: OtherFrame( parent ) {
this->PassVector(vwsM);
}
If you pass vector of strings to constructor only then you don't need a pointer, but reference in derived class, so instead of pointer field
class DerivedFrame: public OtherFrame {
std::vector<wxString> * pvwsM3 = nullptr;
.......
};
make reference field
class DerivedFrame: public OtherFrame {
std::vector<wxString> & rvwsM3;
.......
};
then remove PassVector() method and add reference initialization in constructor:
DerivedFrame::DerivedFrame(wxWindow* parent, std::vector<wxString> & vwsM)
: OtherFrame( parent ), rvwsM3(vwsM) {}
and use it as a reference (unlike pointer reference doesn't need to be checked for null):
void DerivedFrame::USEvwsM() {
rvwsM3.push_back("Something");
}
Reference compared to pointer has two advantages - it can't be forgotten to be initialized, because with reference you don't need to call PassVector(), and you don't need to check if it is null unlike checking pointer (reference is never null). But reference can be initialized only in constructor, while pointer can be initialized later, far later after object was constructed.
|
70,859,738 | 70,867,416 | Writing a specific Clang-tidy check to avoid passing an expression into std::vector::reserve() | In our codebase, we always use std::vector::reserve() to achieve higher performance. Most of the time they work well.
Also, sometimes we might pass an expression into the reserve() function.
For example,
const double length = GetLength();
const double step = GetStep();
v.reserve(static_cast<std::size_t>(length / step));
However, due to some algorithm bugs, length might be a negative number, and it's almost impossible to know this problem without running the program. Every time this problem happens, it will through an error and then a crash is inevitable:
terminate called after throwing an instance of 'std::length_error'
terminate called recursively
what(): vector::reserve
Fortunately, We are now using clang-tidy, so I'm wondering if I can apply some custom rules like avoid passing an expression into std::vector::reserve() function and manually check every variable if it might overflow.
Is there a way to write a clang-tidy rule to do this?
| First, you'll have to decide exactly what you want reported. For simplicity, I am interpreting your question as wanting to report any call to std::vector::reserve where the argument is not an identifier.
Next, the core of any clang-tidy check is the AST matcher expression. The tool clang-query can be used to directly run an AST matcher against a given input program, so I'll use that to show such a matcher. (Incorporating that matcher into a clang-tidy check is then done the like any other, as described in the documentation.)
So, here is a command that runs clang-query on the file reserve1.cc and reports all calls to std::vector::reserve whose argument is not an identifier:
clang-query -c='m
callExpr(
callee(
cxxMethodDecl(
matchesName("std::vector<.*>::reserve")
)),
unless(
hasArgument(0,
expr(declRefExpr())
))
)' \
reserve1.cc --
The matcher expression is fairly self-explanatory except for declRefExpr, which is the matcher that matches identifiers, which Clang terms "declaration references".
When the above command is run on the following input:
// reserve1.cc
// Example for a check that the 'reserve' argument is "simple".
// https://stackoverflow.com/questions/70859738/writing-a-specific-clang-tidy-check-to-avoid-passing-an-expression-into-stdvec
#include <vector>
double GetLength();
double GetStep();
void bad()
{
const double length = GetLength();
const double step = GetStep();
std::vector<int> v;
v.reserve(static_cast<std::size_t>(length / step)); // reported
}
void good(std::size_t len)
{
std::vector<int> v;
v.reserve(len); // not reported
}
struct Other {
void reserve(int);
};
void irrelevant(Other o, int x)
{
o.reserve(x + x); // not reported
}
// EOF
It prints:
Match #1:
/home/scott/wrk/learn/clang/reserve-argument/reserve1.cc:14:3: note: "root"
binds here
v.reserve(static_cast<std::size_t>(length / step)); // reported
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 match.
I recommend spending some time interactively testing and tweaking the AST matcher expression using clang-query on your program of interest before doing the additional work of embedding it into clang-tidy.
There is a bit more information about clang-query in this answer of mine that answers a vaguely similar question.
|
70,859,778 | 70,860,071 | If we return address of local variable of function using pointer, do we need to delete the pointer after using that function or not? | If I don't use delete ptr at comment here in below code, then it causes a memory leak?
int *create(){
int a;
int *a_ptr{&a};
return a_ptr;
}
int main(){
int *ptr = {nullptr};
ptr = create();
//here
return 0;
}
| Actually you return pointer to object that is destroyed after create function ends its execution.
int a; is created on stack so a_ptr points to some place on stack. During return all objects on stack are destroyed and there is only a_ptr left there as value.
No, you don't have memory leak but ptr in main() function is invalid as points to non-existing object.
|
70,859,955 | 70,861,779 | some blank space remains in QVBoxLayout after hiding widgets (Qt) | There are hundreds of widgets in QVBoxLayout. I am hiding/showing them based on option menus. If I hide some of widgets, some blank space remains in QVBoxLayout and I dont want this unnecessary space. Adding spacer at bottom is not solving the issue. Same for setting margin spacing. Its like hidden widgets consume some space. Is there any way to fix this?
Thanks.
| Layouts have some default spacing between each child widget, defined by setSpacing(), setHorizontalSpacing(), setVerticalSpacing(). Even if you hide the child widget, the spacing around it remains visible. (Note: I think this is a bad design decision made by Qt developers, but we need to live with it.) You have basically these options:
a) Remove the child widget from the layout instead of hiding it. Remember its original position and if it should be shown again, insert it at that position. This is complicated, the original position may be invalidated if you removed some other widgets meanhile, so this would require some clever algorithm for maintaining the correct visual positions of the hidden child widgets in the layout etc. I would not do this, feels too complicated for me.
b) Use zero-sized default spacing in the layout and add spacings manually by https://doc.qt.io/qt-5/qboxlayout.html#addSpacing and then when hiding the child widgets, set the size of the QSpacerItem next to it to zero. And set it back to non-zero when showing the child widget again.
c) Alternative to a) but do not keep original indexes but have a container of pointers to the child widgets and when a change in the visibility of the child widgets is required, then remove all the items from the layout and put all the child widgets which should be visible to the layout. This means to re-create the content of the layout in each change. Actually this is how I am doing it in my code. I have about 20 widgets and hiding/showing is fast enough. I believe it will be fast enough even for hundreds of widgets.
d) And alternative to c) ... if you have really large number of widgets, then you should consider deleting those which are not supposed to be visible and re-creating them when they are shown. I.e. in c) we keep the widget alive but hidden in a certain container but in d) we delete this widget and create it later again. It depends on your use case whether c) is better than d) or vice versa. My gut feeling is that c) should be fine performance-wise and is simpler.
Note: My reasonging is based on showing and hiding of widgets in grid layout, but I guess that VBox layout has the same principles regarding preserving default spacing even around hidden items.
|
70,860,100 | 70,860,344 | Why am I not able to print the last character in below code? | I am trying to take sentence as an input from the user in the below code.
eg.
Input -
9
do or die
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter the length of the sentence: ";
cin>>n;
cin.ignore();
char array[n+1];
cin.getline(array,n);
cin.ignore();
cout<<array[7]<<endl;
cout<<array[8]<<endl;
While printing the array[7], I am getting 'i' as my output, but while printing array[8] I am expecting 'e' as my output but I did not get anything as an output.
I have declared character array of size (n+1), which means array[n] should be null character but why array[8] is coming out to be null character?
Am I doing wrong somewhere?
| std::istream::getline(char* s, streamsize n):
Extracts characters from the stream as unformatted input and stores them into s as a c-string.
n is the maximum number of characters to write to s, including the terminating null character.
If you want to read your 9 characters of the sentence, not only your buffer needs to be 10 characters long, but also n in getline needs to be 10.
https://www.cplusplus.com/reference/istream/istream/getline/
|
70,860,830 | 70,860,903 | C++ SImple Looping To Find Largest Number From Array | Hi I create some mini looping with arrays to find the largest number from array, but the result is a random numbers, here's my code
int highest( int num1, int num2, int num3 ){
int bracket[] = {num1, num2, num3};
int result{0};
for ( int i = 0; i < sizeof(bracket); i++)
{
if ( bracket[i] > result )
{
result = bracket[i];
}
}
return result;
}
for example int highest( 5, 99, 1 )
the result is 1984875712 but i expected 99
What's the problem?, Thankyou
| Length of the array is sizeof(bracket) / sizeof(*bracket)
|
70,860,980 | 70,861,714 | Unable to overload operator using templates | I am trying to overload the + operator for a vector class. The vector class is able to specify the data type using templates. The + operator should be able to take two different vectors and create a new resulting one with the dominating data type. Currently my code looks like this:
template<typename T>
class Vector{
private:
int length;
T* data;
public:
/*
Set of constructors and other operators
*/
template<typename S>
Vector<typename std::common_type<S, T>::type> operator+(const Vector<S>& other) const
{
if(length != other.length) throw "Vectors do not have equal length!";
Vector<typename std::common_type<S, T>::type> result(length);
for(auto i = 0; i < length; i++)
{
result.data[i] = data[i] + other.data[i];
}
return result;
}
};
When this code is run for two vectors with different data types (example int and double) it will start complaining that other.length and result.data and other.data are all declared private within this scope. The error message looks like this:
./student_code.cpp: In instantiation of 'Vector<typename std::common_type<S, T>::type> Vector<T>::operator+(const Vector<S>&) const [with S = double; T = int; typename std::common_type<S, T>::type = double]':
./student_code.cpp:140:20: required from here
./student_code.cpp:91:28: error: 'int Vector<double>::length' is private within this context
91 | if(length != other.length) throw "Vectors do not have equal length!";
| ~~~~~~^~~~~~
./student_code.cpp:13:9: note: declared private here
13 | int length;
| ^~~~~~
./student_code.cpp:97:20: error: 'double* Vector<double>::data' is private within this context
97 | result.data[i] = data[i] + other.data[i];
| ~~~~~~~^~~~
./student_code.cpp:14:8: note: declared private here
14 | T* data;
| ^~~~
./student_code.cpp:97:46: error: 'double* Vector<double>::data' is private within this context
97 | result.data[i] = data[i] + other.data[i];
| ~~~~~~^~~~
./student_code.cpp:14:8: note: declared private here
14 | T* data;
| ^~~~
That is not a problem when I overload the operator assuming the other Vector has the same data type (so the code has no other template with typename S). I do not know why this happens and any help is very welcome.
| The problem is that when you instantiate say a Vector<int> and Vector<float>, then both of these are distinct types. Moreover, currently neither of them is allowed to access the internals of the other.
To solve the mentioned error, you should add a friend declaration as shown below:
template<typename T>
class Vector{
private:
//friend declaration
template<typename S> friend class Vector;
int length;
T* data;
public:
//other members here
};
|
70,860,988 | 70,861,256 | Cleanest way to avoid writing same condition twice | Lets say I have a loop that inputs a value from user, and if the value is equal to zero, it breaks.
Is there a way to do this without writing the same condition twice?
for example:
int x;
do
{
std::cin >> x;
if (x)
{
//code
}
} while(x);
What is the cleanest way to do this?
| It's probably cleanest to write a little function to read the value, and return a boolean to indicate whether you read a non-zero value, then use that function:
bool read(int &x) {
std::cin >> x;
return std::cin && (x != 0);
}
while (read(x)) {
// code to process x
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.