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
|
|---|---|---|---|---|
74,148,653
| 74,148,673
|
Implementation of stable_sort in python
|
In c++ there is a function stable_sort() function (It preserves the order ) .Is there any function in python like this ?
|
list.sort() is stable. From the documentation:
The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
|
74,148,958
| 74,149,018
|
How do i access private data members of a class in C++
|
#include<iostream>
using namespace std;
class item{
int a,b;
void getdata(int x,int y){
x=a;
y=b;
}
public:
void here(int a,int b)
{
void getdata();
}
void display();
};
void display()
{
printf("a is %d",a);
printf("\nb is %d ",b);
}
int main()
{
item A;
A.here(10,20);
A.display();
}
Errors
a and b are not declared in this scope for display function.
I cant also acces private function i.e void getdata(int,int) with a object without a public method, Right???
|
You've implemented a free function called display. The declared member function display does not have an implementation.
It should be:
void item::display() {
std::printf("a is %d\n", a);
std::printf("b is %d\n", b);
}
You should also #include <cstdio> to use std::printf.
Also note that the getdata function doesn't actually get any data since it assigns values to the local variables x and y. If you want the values available at the call-site, take x and y by reference:
void getdata(int& x, int& y) { // note the &
x=a;
y=b;
}
It also doesn't make sense to have getdata private. Instances of item can access the member variables directly so getdata is pointless unless made protected or public. You most probably want to have it public.
Since neither display nor getdata changes the object, you should also make them const qualified so that they can be used in const contexts.
The here function doesn't make sense since it calls getdata without arguments. I assume you want to assign values to the member variables a and b. If so:
void here(int a, int b) {
this->a = a;
this->b = b;
}
Demo
|
74,149,482
| 74,149,645
|
Find Extreme Value in Integers Given
|
I'm trying to find the highest value in a given list, but in an input list like this
7 385 -390 305 470 -145 255 30
my output is wrong, 385 instead of 470.
Could anyone please guide me towards my error!
Task description:
Read in an input value for variable numIn. Then, read numIn integers from input and output the largest of the integers read. End with a newline.
Ex: If the input is 2 345 -5, then the output is:
345
my code below
#include <iostream>
using namespace std;
int main() {
int numIn;
int high = 0;
cin >> numIn;
for (int i = 0; i < numIn; i++) {
cin >> numIn;
if (numIn > high) {
high = numIn;
}
}
cout << high << endl;
return 0;
}
|
First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this.
The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers.
cin >> numIn; // numIn is the number of input numbers
for (int i = 0; i < numIn; i++) {
cin >> numIn; // oops, numIn is now the first input number. it has been overwritten.
if (numIn > high) {
high = numIn;
}
}
A correct solution would look like this:
#include <iostream>
int main() {
int N; // assume that N >= 1. You could also replace this with numIn.
std::cin >> N;
int max;
std::cin >> max; // take in the first integer outside the loop
for (auto i = 1; i < N; i++) { // loop which runs N - 1 times
int E;
std::cin >> E;
max = std::max(max, E);
}
std::cout << max << '\n';
}
Without using std::max()
If you don't want to use std::max(), replace the line where you use it with a normal comparison (this is what std::max() does internally too)
if (E > max) { max = E; }
|
74,149,490
| 74,149,549
|
Pointer to a member function does not contain the information of the instance?
|
(This is a question after reading this answer)
I tried this code:
#include <iostream>
class A {
public:
int a;
A(int val) : a{val}{}
int f(int);
int (A::*p)(int);
};
int A::f(int in) {
return in + a;
}
int main() {
A a1(1000);
A a2(2000);
// Without these two lines, segmentation fault.
a1.p = &A::f; // no instance information.
a2.p = &A::f; // no instance information.
std::cout << a1.p << " " << a2.p << '\n';
std::cout << std::boolalpha << (a1.p == a2.p) << '\n';
std::cout << (a1.*(a1.p))(5) << '\n';
std::cout << (a1.*(a2.p))(5) << '\n';
std::cout << (a2.*(a1.p))(5) << '\n';
std::cout << (a2.*(a2.p))(5) << std::endl;
}
Results:
1 1
true
1005
1005 // the same result as above.
2005
2005 // the same result as above.
It seems that a1.p and a2.p are the same. Is the member function's address not assigned until it is dereferenced and called by attaching the instance's name?
If so, what's the point of assigning &A::f, if it has no information about the instance?
|
Non-static member functions have a "hidden" first argument that becomes the this pointer inside the function. So instance is not part of the function itself, but rather passed as an argument.
Note the quotes around "hidden", because it's only hidden in the function signature. When using other ways to call e member function, it's not really hidden but actually passed like any other argument. For example if using std::bind or std::thread, non-static member function are called with the instance as an actual argument.
Example:
struct thread_class
{
int value_;
explicit thread_class(int value)
: value_{ value }
{
}
void thread_func(int arg)
{
std::cout << "arg is " << arg << '\n';
std::cout << "value is " << value_ << '\n';
}
};
int main()
{
thread_class foo;
std::thread thread(&thread_class::thread_func, &foo, 123);
thread.join();
}
The three arguments to the std::thread constructor is the function to run, and the arguments to the function itself. The first is the object to call the function on, what becomes this inside thread_func.
|
74,149,523
| 74,149,649
|
Is it possible to use X-Macro with std::variant (or with template in general)?
|
I hope to do the following using X-macro with c++17, but since template parameter does not support trailing comma, it does not work for the std::variant part. Is there someway around it?
#define LIST_OF_TYPES(X) \
X(Type1) \
X(Type2) \
X(Type3)
#define MAKE_TYPE(name) class name {};
LIST_OF_TYPES(MAKE_TYPE)
#undef MAKE_TYPE
std::variant<
#define MAKE_VARIANT(name) name,
LIST_OF_TYPES(MAKE_VARIANT)
#undef MAKE_VARIANT
>
|
Yes, there's a workaround:
#define EMPTY(...)
#define IDENTITY(...) __VA_ARGS__
#define IDENTITY2(...) __VA_ARGS__
std::variant<
#define MAKE_VARIANT(name) (,) name IDENTITY
IDENTITY2(EMPTY LIST_OF_TYPES(MAKE_VARIANT) () )
#undef MAKE_VARIANT
>
Without IDENTITY2(...) this expands to EMPTY(,) Type1 IDENTITY(,) Type2 IDENTITY(,) Type3 IDENTITY(). IDENTITY2 forces it to expand again, this time to Type1, Type2, Type3.
Or, with my own macro looping library:
run on gcc.godbolt.org
#include <macro_sequence_for.h>
#define LIST_OF_TYPES (Type1)(Type2)(Type3)
#define DECLARE_CLASSES(seq) SF_FOR_EACH(DECLARE_CLASSES_BODY, SF_NULL, SF_NULL,, seq)
#define DECLARE_CLASSES_BODY(n, d, x) class x {};
#define MAKE_VARIANT(seq) std::variant<SF_FOR_EACH(MAKE_VARIANT_BODY, USE_COMMA, SF_NULL, EMPTY, seq)>
#define MAKE_VARIANT_BODY(n, d, x) d() x
#define EMPTY(...)
#define COMMA(...) ,
#define USE_COMMA(n, d, x) COMMA
DECLARE_CLASSES(LIST_OF_TYPES) // class Type1 {}; class Type2 {}; class Type3 {};
MAKE_VARIANT(LIST_OF_TYPES) // std::variant<Type1, Type2, Type3>
Slightly more verbose, but more readable in my taste.
Here, #define MAKE_VARIANT_BODY(n, d, x) d() x is called for each element, with x being the element, and d initially set to EMPTY (4th argument of SF_FOR_EACH()). After the first (and any subsequent) iteration, d is reassigned to USE_COMMA(...) (aka COMMA), so starting from the second iteration d() expands to , instead of .
|
74,149,760
| 74,149,839
|
c++ using range based to access the vector wrapped in a shared_ptr gives unexpected result
|
I have the following code, why is the range based output is not what is stored in the vector?
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
shared_ptr<vector<double>> get_ptr() {
vector<double> v{1, 2, 3, 4, 5};
return make_shared<vector<double>>(v);
}
int main() {
auto vec = get_ptr();
for (int i = 0; i<get_ptr()->size(); ++i) {
std::cout << (*get_ptr())[i] << std::endl;
}
for (auto v: (*get_ptr())) {
std::cout << v << std::endl;
}
}
The output on my ubuntu is something like below,
1
2
3
4
5
4.67913e-310
4.67913e-310
3
4
5
|
Every time you call get_ptr() you create a new and unique copy of the vector. And that object will be destructed as soon as the full expression involving the call is finished.
So in the case of
for (auto v: (*get_ptr()))
As soon as *get_ptr() is finished, the object will be destructed.
And due to how ranged for loops works, you will iterate using a non-existing vector, leading to undefined behavior.
|
74,149,928
| 74,150,085
|
defining constexpr variable by checking string condition
|
int run(std::string type, std::string interval)
{
if(type == "ST"){
if(interval == "SEC"){
constexpr unsigned int N = 10;
Runner<N> data();
data.parse();
} else{
constexpr unsigned int N = 20;
Runner<N> data();
data.parse();
}
}
else if(type == "JST"){
constexpr unsigned int N = 23;
Runner<N> data();
data.parse();
}
else{
constexpr unsigned int N = 5;
Runner<N> data();
data.parse();
}
}
I want to reduce the if statements and do the conditional checks on a separate function:
constexpr unsigned int arraysize(std::string type, std::string interval){
if(type == "ST"){
if(interval == "SEC"){
return 10;
} else{
return 20;
}
}
else if(type == "JST"){
return 23;
}
else{
return 5;
}
}
However this doesn't work because a constexpr function cannot have a parameter of nonliteral type std::string.
Is there a better way to take out conditional checks so that I end up with something like this:
int run(std::string type, std::string interval)
{
constexpr unsigned int N = arraysize(type, interval);
Runner<N> data();
data.parse();
}
|
run as you are showing can't work, even in principle, because you want N to be runtime-dependent. N can't be constexpr.
Alternative approach:
template<auto V>
inline constexpr auto constant = std::integral_constant<decltype(V), V>{};
template<typename F>
void apply_with_arraysize(F&& f, std::string type, std::string interval){
if(type == "ST"){
if(interval == "SEC"){
f(constant<10>);
} else{
f(constant<20>);
}
}
else if(type == "JST"){
f(constant<23>);
}
else{
f(constant<5>);
}
}
int run(std::string type, std::string interval)
{
apply_with_arraysize([](auto N){
Runner<N()> data; // N instead of N() also ok, if `Runner` doesn't use `auto` non-type template argument
data.parse();
}, type, interval);
}
|
74,150,310
| 74,150,707
|
Sending JavaScript Object QML signal parameter
|
I am trying to connect a QML signal to a Qt slot with following parameter types:
in QML side:
signal Sig(var info)
in Qt side:
QObject::connect(topLevel, SIGNAL(Sig(QVariantMap)), &mObj, SLOT(mSlot(QVariantMap)));
Which gives me the following:
QObject::connect: No such signal QQuickWindowQmlImpl_QML_24::Sig(QVariantMap) in ...
So, I assume that types var and QVariantMap does not match. According to this document, QVariantMap types are converted to JavaScript objects. But I am not sure if it also does the other way around.
I have implemented an opposite type of connection(Qt signal with QVariantMap, QML handler with "Connections" element) which worked just fine. I was able to get the signal's argument as a JS object.
By the way, I have also tried the same connection with string argument types in my code, so I don't think that there is another unrelated mistake in my code.
How do I pass JS objects to Qt(C++) side using signal/slot mechanism? I haven't been able to find a solution. Not even an example that matches my case(signal and slot argument types), actually. Which makes me think that I am doing some sort of design mistake.
|
The parameters are QVariants on C++ side, so you need to do
QObject::connect(topLevel, SIGNAL(Sig(QVariant)), &mObj, SLOT(mSlot(QVariant)));
Note that you also need to change mSlot parameter type, because QVariant can't be implicitly converted to QVariantMap. To get the map in the slot, use QVariant::toMap() method, if it indeed is a map (if it isn't, this method returns empty map, and you need to do some debugging).
It works the other way around, because QVariantMap can be implicitly converted to QVariant.
|
74,150,327
| 74,151,047
|
string size() returns 1 too large value in evaluation system
|
if I have very simple part of code like:
string myvariable;
getline(cin, myvariable);
cout << myvariable.size();
and if I run that program locally it returns appropriate value (so exactly number of characters including spaces in the given string).
But if I upload that program to the programs evaluation system (sth like programming olympics or spoj.com) I get value of size() 1 too much.
For example if myvariable value is "test", then:
locally:
size() == 4
in evaluation system:
size() == 5
I tried .length() but the result is exactly the same.
What is the reason for that? Thank you for your answers!
|
After the discussion in the comments, it is clear that the issue involves different line ending encodings from different operating systems. Windows uses \r\n and Linux/Unix use \n. The same content may be represented as
"Hello World!\n" // in a Linux file
or
"Hello World!\r\n" // in a Windows file
The method getline by default uses \n as delimiter on Linux/Unix, so it would yield a one greater size for the Windows file, including the unwanted character \r, represented as hex value 0D.
In order to fix this, you can either convert the line endings in your file, or trim the string after reading it in. For example:
string myvariable;
getline(cin, myvariable);
myvariable.erase(myvariable.find_last_not_of("\n\r") + 1);
See also How to trim an std::string? for more ways to trim a string for different types of whitespace.
|
74,150,480
| 74,150,685
|
How does structure padding work in ESP32's compiler
|
I was talking with a friend and trying out different structure configurations. And looking at the outputs has me confused as to how the structure is being padded. I'm using wokwi's online esp32 compiler for this. The structure configurations that have me confused are:
struct bruh{
short int aK;
short int a;
char cd;
};
//Printing the size of this structure gives the output as 6.
// I would have assumed either 8(padded) or 5(packed). Why?
The other example that has me puzzled is:
struct bruh{
int aK;
char cd;
};
//Output is 8. Understandable.
//Int is 4 bytes, and the extra character gets padded to the next 4 bytes.
but!
struct bruh{
char cd;
};
//Gives me the output as 1. If the example before this one is getting
// padded because of the additional character byte, why isn't this structure 4 bytes?
|
Padding is not to bring the size up to the next multiple of 4, it is to ensure every member is always on the correct alignment. Different types have different alignment requirements, and these are all implementation-defined.
You can use the alignof operator to look at the alignment of a type.
Here's one compiler reporting what it does with your types
|
74,150,499
| 74,150,879
|
my class has no suitable copy constructor - depending if the argument of the constructor is const or not
|
Question:
I am learning c++, and i created a class to represent complex numbers. I created a copy constructor with the format
complex(const complex &c);
and the program worked fine.
Then, i removed the const (so it became: complex( complex &c); ) and the program doesn't work. It gives me this error:
"message": "class \"complex\" has no suitable copy constructor"
and it refers to the add method. The add method is this:
complex complex::add(complex &c){
return complex( re + c.re, im + c.im);
};
If i do not add this method (and methods that generally return a complex number that is created in the return line, like this: return complex (integer_variable_Re, integer_variable_Im) ) the program works fine. When i add these kinds of methods, it throws me the error. I cannot understand why this doesn't work, as it should call the constructor that takes two integers and not the copy constructor.
Specs:
Ubuntu: 20.04Lts
IDE: VScode
Compliler: G++ 9.4
(it says somewhere this: GNU C17 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu) compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version isl-0.22.1-GMP, do not know if it it the compliler standard.)
Whole error message:
[{ "resource": "/home/papaveneti/Documents/Programming/LearnCpp/complex_classStack.cpp", "owner": "C/C++", "code": "334", "severity": 8, "message": "class \"complex\" has no suitable copy constructor", "source": "C/C++", "startLineNumber": 48, "startColumn": 12, "endLineNumber": 48, "endColumn": 19 }]
Whole program:
#include <iostream>
#include <math.h>
using namespace std;
class complex {
public:
complex (double r, double i); // constructor
// only method that does not specify type
//default constructor
complex ();
//copy cosntructor
complex( complex &c);
// methods:
complex add(complex &c);
void norm1();
private:
// fields:
double re, im;
double norm;
};
//constructor does not need to name a type
complex::complex(double r=0.0, double i=0.0){ // default values are 0
re = r; im = i;
norm1();
};
complex::complex(){
re=im=0;
}
complex::complex( complex &c){
re=c.re;
im=c.im;
}
void complex::norm1(){
norm = sqrt(re*re + im*im);
};
complex complex::add(complex &c){
return complex( re + c.re, im + c.im);
};
int main(){
complex c1(3,4), c2(1,2);
return 0;
}
|
Before C++17, the following line
return complex( re + c.re, im + c.im);
actually includes two object creations. First an unnamed temporary object is constructed using two double parameters. Then a copy of this object is made to where the return value is stored. This second copy is the reason for your compiler error. A copy constructor can only be used to copy a temporary object, if it is declared like this:
complex(const complex&);
If you omit the const qualifier, you cannot pass a temporary object.
With the introduction of mandatory copy elision in C++17, there is no copy (or move) involved in the line mentioned above. Thus your program compiles fine. Your compiler, which is rather old, does not use C++17 by default and so refuses to compile the program.
To solve your problem, you could either
use a copy constructor which takes a const reference
add a move constructor
use C++17 (either by using a newer compiler version or by passing the --std=c++17 command line option to your compiler
Edit:
You should also fix the problem that @Jason Liam mentions in this answer. As mentioned there, your program is ill-formed and should not compile even with the const constructor.
|
74,150,614
| 74,150,687
|
Error when trying to output element of a standard array that is a struct member
|
I'm trying to run the following code:
#include <iostream>
#include <array>
struct newperson {
std::array<char, 20> name{};
int age;
};
int main() {
newperson nicolas = {
"Nicolas",
21
};
newperson martin = {
"Martin",
45
};
std::cout << nicolas.age << std::endl;
std::cout << martin.name << std::endl;
return 0;
}
, which is a struct example
I get the following errors:
bast.cpp: In function 'int main()':
bast.cpp:21:19: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'std::array<char, 20>')
21 | std::cout << martin.name << std::endl;
| ~~~~~~~~~ ^~ ~~~~~~~~~~~
| | |
| | std::array<char, 20>
| std::ostream {aka std::basic_ostream<char>}
C:/msys64/mingw64/include/c++/12.2.0/ostream:754:5: error: no type named 'type' in 'struct std::enable_if<false, void>'
Is some different syntax required? I did take an existing example and change the C-style array to a standard one, after all.
And if I comment out the Martin lines, I get the following:
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccClI6JG.o:bast.cpp:(.text+0x42): undefined reference to `std::ostream::operator<<(int)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccClI6JG.o:bast.cpp:(.text+0x54): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccClI6JG.o:bast.cpp:(.text+0x76): undefined reference to `std::ios_base::Init::~Init()'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccClI6JG.o:bast.cpp:(.text+0xa9): undefined reference to `std::ios_base::Init::Init()'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccClI6JG.o:bast.cpp:(.rdata$.refptr._ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_[.refptr._ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_]+0x0): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\ccClI6JG.o:bast.cpp:(.rdata$.refptr._ZSt4cout[.refptr._ZSt4cout]+0x0): undefined reference to `std::cout'
collect2.exe: error: ld returned 1 exit status
That seems to be a problem with mingw/msys2, though, because it works with Godbolt and tio.run
|
There is no overloaded << (stream output) operator for the std::array container, whatever the element type. However, that array container does have a .data() member, which yields a pointer to the first element; in your case, that will be a char* and the relevant specialisation for outputting a char* (assuming that points to a properly null-terminated string/array) will do what you want:
std::cout << martin.name.data() << std::endl;
But, as pointed out in the comments, you would be far better off using a std::string, here, unless there is a specific reason why you need a fixed-length array in your structures.
(If you adapted this from code that used a "C-style" array for the .name member – i.e. char name[20]; – then the << would work because that array name will automatically 'decay' into a pointer to its first element; this doesn't happen for std::array.)
Alternatively, although there is no << ostream overload for the array<char, N> container provided by the Standard Library, you could provide your own. This can be implemented as a function template (so that different array sizes could be used), like this:
template <size_t N>
std::ostream& operator << (std::ostream& os, std::array<char, N> ArrChar)
{
return os << ArrChar.data();
}
|
74,150,709
| 74,152,675
|
Should two programs compiled with -O0 and -O2 each produce identical floating point results?
|
Short example:
#include <iostream>
#include <string_view>
#include <iomanip>
#define PRINTVAR(x) printVar(#x, (x) )
void printVar( const std::string_view name, const float value )
{
std::cout
<< std::setw( 16 )
<< name
<< " = " << std::setw( 12 )
<< value << std::endl;
}
int main()
{
std::cout << std::hexfloat;
const float x = []() -> float
{
std::string str;
std::cin >> str; //to avoid
//trivial optimization
return strtof(str.c_str(), nullptr);
}();
const float a = 0x1.bac178p-5;
const float b = 0x1.bb7276p-5;
const float x_1 = (1 - x);
PRINTVAR( x );
PRINTVAR( x_1 );
PRINTVAR( a );
PRINTVAR( b );
PRINTVAR( a * x_1 + b * x );
return 0;
}
this code on godbolt
This code produces different output on different platforms/compilers/optimizations:
X = 0x1.bafb7cp-5 //this is float in the std::hexfloat notation
Y = 0x1.bafb7ep-5
The input value is always the same: 0x1.4fab12p-2
compiler
optimization
x86_64
aarch64
GCC-12.2
-O0
X
X
GCC-12.2
-O2
X
Y
Clang-14
-O0
X
Y
Clang-14
-O2
X
Y
As we can see, Clang gives us identical results between -O0 and -O2 within same architecture, but GCC does not.
The question is - should we expect the identical result with -O0 and -O2 on the same platform?
|
The question is - should we expect the identical result with -O0 and -O2 on the same platform?
No, not in general.
C++ 2020 draft N4849 7.1 [expr.pre] 6 says:
The values of the floating-point operands and the results of floating-point expressions may be represented in greater precision and range than that required by the type; the types are not changed thereby.51
Footnote 51 says:
The cast and assignment operators must still perform their specific conversions as described in 7.6.1.3, 7.6.3, 7.6.1.8
and 7.6.19.
This means that while evaluating a * x_1 + b * x, the C++ implementation may use the nominal float type of the operands or it may use any “superset” format with greater precision and/or range. That could be double or long double or an unnamed format. Once the evaluation is complete, and the result is assigned to a variable (including, in your example, a function parameter), the result calculated with extended precision must be converted to a value representable in the float type. So you will always see a float result, but it may be a different result than if the arithmetic were performed entirely with the float type.
The C++ standard does not require the C++ implementation to make the same choice about what precision it uses in all instances. Even if it did, each combination of command-line switches to the compiler may be regarded a different C++ implementation (at least for the switches that may affect program behavior). Thus the C++ implementation obtained with -O0 may use float arithmetic throughout while the C++ implementation obtained with -O2 may use extended precision.
Note that the extended precision used to calculate may be obtained not just through the use of machine instructions for a wider type, such as instructions that operate on double values rather than float values, but may arise through instructions such as a fused multiply-add, which computes a*b+c as if a•b+c were computed with infinite precision and then rounded to the nominal type. This avoids the rounding error that would occur if a*b were computed first, producing a float result, and then added to c.
|
74,151,009
| 74,151,118
|
Erasing element in std::vector of std::pair of std::string
|
I have a std::vector of std::pair of std::string where the language and translation are the values. These are the values in my vector of pair
0. {English, Love},
1. {Spanish, Amor},
2. {Tagalog, Mahal},
3. {English, Love}
What I wanted to do is to only remove the index 3, but in my code if I try to remove the index 3, both index 0 and 3 are removed.
Here's my code:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <utility>
auto main() -> int {
using pair_of = std::vector<std::pair<std::string, std::string>>;
using str_pair = std::pair<std::string, std::string>;
pair_of language_translation{};
language_translation.emplace_back(std::make_pair("English", "Love"));
language_translation.emplace_back(std::make_pair("Spanish", "Amor"));
language_translation.emplace_back(std::make_pair("Tagalog", "Mahal"));
language_translation.emplace_back(std::make_pair("English", "Love"));
std::string language{"English"};
std::string translation{"Love"};
auto selected_pair = std::remove_if(
language_translation.begin(), language_translation.end(),
[&](const str_pair &data_pair) {
if(data_pair.first == language && data_pair.second == translation) {
return true;
}
else {
return false;
}
}
);
language_translation.erase(selected_pair, language_translation.end());
for(const auto &pair : language_translation) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
}
The output result is
Tagalog: Mahal
Spanish: Amor
What other algorithm can I use to solve a problem like this? Can you guys give an example? Thank you!
|
To delete by index you can do something like this:
language_translation.erase(std::next(language_translation.begin(), index));
|
74,151,198
| 74,151,367
|
C++ Concurrency in Action joining_thread implementation in listing 2.7
|
I am reading the second edition of C++ Concurrency in Action book and I have a question concerning chapter 2. In listing 2.7, a joining_thread class is provided. I was wondering why the second constructor copies pass the thread argument by value?
I understand that it is meant to call it like:
joining_thread jt{std::thread(fct)};
which I understand. But what prevents us from doing:
std::thread t(fct);
joining_thread jt(t);
which copies the thread to the constructor parameter and moves the copy. This seems to do differently as in listing one, where the thread guard is supposed to protect the thread passed to it, not a copy; so I guess the intention is the same here. Maybe this is not the case and I have my answer but I want to be sure to understand it correctly. Is it deliberate to create an internal copy in that case? Or what am I not understanding?
I thank you in advance for your help.
|
Since you write about copying of threads, I suppose you meant:
std::thread t(fct);
joining_thread jt(t);
instead of:
std::thread t(fct);
joining_thread jt(fct);
The first one simply does not compile because threads are non-copyable. In particular, std::thread has a deleted copy constructor: https://en.cppreference.com/w/cpp/thread/thread/thread.
Live demo: https://godbolt.org/z/EG41WK4bx
You need to employ the move constructor here by either:
std::thread t(fct);
joining_thread jt(std::move(t));
or your original:
joining_thread jt{std::thread(fct)};
Note that you cannot write directly:
joining_thread jt{fct};
since the corresponding converting constructor of std::thread is explicit.
|
74,151,559
| 74,152,498
|
Why does this std::enable_if only have the first parameter, and how does static_array match?
|
Here is a piece of code
// check if type of static array
template <class T>
struct ABIStaticArray : std::false_type //#1
{
};
// stringN type => bytesN
template <std::size_t N>
struct ABIStaticArray<std::array<char, N>> : std::false_type //#2
{
};
// a fixed-length array of N elements of type T.
template <class T, std::size_t N>
struct ABIStaticArray<std::array<T, N>> : std::true_type //#3
{
};
// fixed length of type, default 1 except static array type
template <class T, class Enable = void>
struct Length //#4
{
enum
{
value = 1
};
};
// length of static array type
template <class T>
struct Length<T, typename std::enable_if<ABIStaticArray<T>::value>::type> //#5
{
enum
{
value = std::tuple_size<T>::value * Length<typename std::tuple_element<0, T>::type>::value
};
};
Why does the std::enable_if in specialized template of Length only have the first parameter?
If I pass in a StaticArray, how does it match the specialized template of Length, if the value of first param of std::enable_if in specialized template of Length is true, the specialized template will become:
template <class T>
struct Length<T, void>
{
enum
{
value = std::tuple_size<T>::value * Length<typename std::tuple_element<0, T>::type>::value
};
};
why need this specialized template, what is the difference with the basic template of Length?
the call of Length likes:
Length<std::array<int, 5>>::value
the result is 5
Please help, thanks very much!
|
Let's see what is happening step by step. When you wrote:
Length<std::array<int, 5>>::value
Step 1) The template parameter T for Length is std::array<int, 5>
Step 2) Now there are two options that can be used. Either the primary template template <class T, class Enable = void> labeled as #4 or the specialization for static array #5. We want to find which one should be used. For this the condition typename std::enable_if<ABIStaticArray<std::array<int, 5>>::value>::type is tested.
Step 3) Now, ABIStaticArray<std::array<int, 5>> uses the 2nd specialization labeled as #3 because it is more specialized than the first specialization #2 and from the primary template #1.
Step 4) Since the second specialization is used, std::enable_if<ABIStaticArray<std::array<int, 5>>::value evaluates to true so that typename std::enable_if<ABIStaticArray<std::array<int, 5>>::value>::type evaluates to void.
Basically, the specialization of Length is preferred over the primary template.
Step 5) Since the specialization of Length is selected the value is calculated using value = std::tuple_size<std::array<int, 5>>::value * Length<typename std::tuple_element<0, std::array<int, 5>>::type>::value which comes out to be 5.
To confirm this I modified your program slightly:
// length of static array type
template <class T>
struct Length<T, typename std::enable_if<ABIStaticArray<T>::value>::type> //#5
{
enum
{
value = std::tuple_size<T>::value * Length<typename std::tuple_element<0, T>::type>::value
};
Length()
{
std::cout <<"specialization #5"<<std::endl;
}
};
int main()
{
Length<std::array<int, 5>> v; //will use the specialization of Length
}
Working demo.
The output of the program is:
specialization #5
|
74,152,355
| 74,153,013
|
CUDA and openCV (CPU) Matrix Addition Performance constant with increasing numels
|
I compare the performance of Matrix Addition using a simple CPU function, CUDA and openCV (on CPU) by increasing the number of elements consecutively and measuring the runtime. I have plotted the data below. Note that it is one plot per datatype, where CUCV_8U is a macro for unsigned char, CUCV_16U=unsigned short, CUCV32F=float and CUCV64F=double.
I have noticed that the runtime of openCV and CUDA does not increase until the matrices have roughly 2^12 elements. After they exceed that "limit", the runtimes start to diverge (note the logarithmic scaling). Now, I would like to explain that "limit".
If it was only for CUDA, I would suggest it is due to the number of available CUDA cores, which is 1024 for my GTX 960. When the number of total elements in the matrix exceeds the number of cores, the threads can not be executed parallel anymore, but are executed concurrently.
However, openCV seems to follow the same trend (constant runtime until roughly 2^12 elements) and so I am wondering what could be the reason for this. Anyone has an idea?
Thank you!
If you need information about the code I used have a look at my project repo https://github.com/Vinc37-git/cuCV or see below.
// CUDA Kernel
template <typename T>
__global__ void cuCV::kernel::add(DeviceCuMat<T> OUT, const DeviceCuMat<T> A, const DeviceCuMat<T> B) {
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y * blockDim.y + threadIdx.y;
int ch = blockIdx.z * blockDim.z + threadIdx.z;
int index = row * A.getWidth() + col + (A.getWidth()*A.getHeight()) * ch; // linearisation of index
if (col < A.getWidth() && row < A.getHeight() && ch < A.getNChannels())
OUT.getDataPtr()[index] = A.getDataPtr()[index] + B.getDataPtr()[index];
}
|
I have noticed that the runtime of openCV and CUDA does not increase until the matrices have roughly 2^12 elements.
Starting a kernel take some time since it requires an interaction with the OS (more specifically the graphic driver) and the target device with is generally a PCI device (requiring a PCI communication). I/O operations are generally pretty slow and they often has a pretty big latency (for HPC applications). There are many other overheads to consider including the time to allocate data on the device, to manage virtual memory pages, etc. Since system calls tends to takes at least 1 us on most mainstream systems and about dozens of us for the one involving discrete GPUs, the reported timing are expected. The time to start a data transfer to a PCI-based GPU is usually about hundreds of us (at least 10 us on nearly all platforms).
Note that GPUs are designed to execute massively parallel computing code, not low-latency ones. Having more core do not make small computation faster but more operation can be computed faster. This is the principle of the Amdahl's and Gustafson's laws.
If you want to compute small matrices, you should not use a discrete GPU. If you have a lot of them, then you can do that efficiently on a GPU but using one big kernel (not 1 kernel per matrix).
If it was only for CUDA, I would suggest it is due to the number of available CUDA cores, which is 1024 for my GTX 960
Such a computation should not be compute-bound but memory-bound (otherwise, you should clearly optimize the kernel as any GPU should saturate the memory for such basic operation). As a result, what matters is the memory bandwidth of the target GPU, not the number of CUDA core. Also note that the memory of the GPU tends to be faster than the one CPU can use but with a significantly bigger latency.
Also note that the GTX 960 is not design to compute double-precision computation efficiently. In fact, a good mainstream CPU should clearly outperform it for such computation. This GPU is made to speed up simple-precision computation (typically for 3D applications like games). If you want to speed up double-precision computations, then you need a (far more expensive) server-based GPU. Fortunately, this should not be much a problem for memory-bound code.
OpenCV seems to follow the same trend (constant runtime until roughly 2^12 elements)
There are still overhead for the OpenCV implementation. For example creating thread take some time, allocating data too (though it should be significantly faster than on GPU), not to mention caches are certainly cold (so possibly bound by cache misses). The time to create few threads on a mainstream Linux PC is about few us to few dozens of us (generally more on servers due to more core and a more complex architecture).
Overall, the CPU implementation appear to be memory bound since the speed of the computation is dependent of the item size (proportional at first glance). That being said, the throughput appears to be pretty slow if the code assuming the results are for 1 kernel execution (I got 2.5 GiB/s which is pretty bad for a recent mainstream PC). The GPU computation is also suspiciously inefficient since the timings are independent to the item size. This means the computation is certainly not memory-bound and the kernel can likely be optimized (check the layout of the image and the GPU does contiguous access first, and then apply some unrolling so to reduce the overhead of the kernel per thread).
I strongly advise you to profile both the CPU and GPU implementations. The first thing to do for the CPU implementation (for large matrices) is to check whether multiple cores are used and if SIMD instructions are executed. For both the CPU and GPU implementations, you should check the memory throughput.
|
74,152,542
| 74,152,849
|
Error in LLVM IR or runtime library produces SEGV
|
I'm writing a programming language called PPL.
In PPL integer literals are arbitrary width by default. This is archived with using pointer to GMP's mpz_class for integers.
However, when compiling -1, there is an error from address sanitiser:
==92833==ERROR: AddressSanitizer: SEGV on unknown address 0x000100000006 (pc 0x000105564bc4 bp 0x000105019f14 sp 0x00016ce45e50 T0)
==92833==The signal is caused by a UNKNOWN memory access.
#0 0x105564bc4 in __gmpz_neg+0x14 (libgmp.10.dylib:arm64+0x14bc4) (BuildId: efc29ca33b2a3664976db890d76d3d0832000000200000000100000000000c00)
Here are parts of runtime, related to the problem:
// Temporary solution for not leaking memory,
// as I haven't implemented memory management yet
std::unordered_set<mpz_class> values;
// PPL's big integer type
using Integer = const mpz_class *;
extern "C" {
// Used to create integer from literal
Integer _IntegerConstructorFromCString(const char *string)
{
assert(string);
// Inserts value and returns pointer to it
return &*values.emplace(mpz_class(string)).first;
}
/// - <:Integer> -> Integer
Integer _MinusInteger(Integer value)
{
// I checked in debugger, here value is 0x000100000006,
// which isn't a pointer I returned from _IntegerConstructorFromCString
assert(value);
// Inserts value and returns pointer to it
return &*values.emplace(-*value).first;
}
} // extern "C"
Here is LLVM IR generated by PPL's compiler:
@.str = private unnamed_addr constant [2 x i8] c"1\00", align 1
// Code for "-1" top level expression
define void @_top_level_code() {
// Create integer from "1"
%1 = call ptr @_IntegerConstructorFromCString(ptr getelementptr inbounds ([2 x i8], ptr @.str, i32 0, i32 0))
// Get -1
%2 = call ptr @"- <:Integer>"(ptr %1)
ret void
}
// Function from runtime
declare ptr @_MinusInteger(ptr %0)
// PPL's operator that hides runtime function invokation
define ptr @"- <:Integer>"(ptr %a) {
%1 = load ptr, ptr %a, align 8
%2 = call ptr @_MinusInteger(ptr %1)
ret ptr %2
}
What's wrong with my code?
P.S: may the problem be in the way I access function argument without alloca?
Or I don't dereference a pointer somewhere? (hard to say for me, as all of them are opaque)
|
I solved the problem with removing load of function arguments.
Instead of:
define ptr @"- <:Integer>"(ptr %a) {
%1 = load ptr, ptr %a, align 8 // This is wrong for some reason.
// Looks like arguments aren't pointers themself
%2 = call ptr @_MinusInteger(ptr %1)
ret ptr %2
}
Compiler now generates:
define ptr @"- <:Integer>"(ptr %a) {
%1 = call ptr @_MinusInteger(ptr %a)
ret ptr %1
}
|
74,153,853
| 74,153,929
|
Why isn't the source std::map for std::map::merge const?
|
Is there a reason why
template<class C2>
void std::map<Key,T,Compare,Allocator>::merge( std::map<Key, T, C2, Allocator>& source );
takes source as a reference, rather than a const reference?
Perhaps I'm having a senior moment here, but I don't see how source is changed in any way by the function, plus it's less than helpful the way it is.
|
merge() does, in fact, modify the source map. It's an optimized operation that executes the merge by relinking both maps' innards, transplanting the merged values from one map to another without actually copying either the key or the value, only by fiddling the internal pointers.
Hence, at the end, the source map will (usually) be just a shadow of its former glory. And it cannot be const, for that to happen.
|
74,153,872
| 74,154,664
|
Accessing embedded resource as "a file"
|
I'm trying to glue together two libraries where
lib1 is providing scripts to lib2.
The libraries are used in c++11 code I'm writing. I can't modify those libs.
Scripts in lib1 are embedded into the shared object with https://github.com/vector-of-bool/cmrc.
The content of each script can be accessed with an iterator, like so
cmrc::embedded_filesystem fs=cmrc::hpo::get_filesystem()
auto script1 = fs.open("script1")
# use iterator for script1...
However, lib2 function requires 'physical' file: void file(const char *);
I know I can dump content from lib1 iterator to a temp file, read it with lib2 and then remove the file. This solution sounds rather sub optimal and I'm looking for a better way.
|
While named pipes are usually used for inter-process communication, they also work intra-process. And on many Operating Systems, including Windows, they have a name that's part of the file system namespace. Hence you can usually pass a pipe name to libraries which expect file names.
|
74,154,181
| 74,154,344
|
Why isn't this abstract class working with circular dependency?
|
When I compile my code, I get:
"src/gameObject.cpp:8:13: error: expected unqualified-id before 'class' GameObject::class Component& getComponent(const std::string &name)"
alongside several other errors of a similar type. I'm not sure if the problem has to do with the abstract class or the forward declaration of the class. I have tried troubleshooting for the past day and I cannot for the life of me figure out how to fix this dependency. The intention is for "Components" to contain a pointer that points to the gameObject that they are owned by and for gameObjects to contain a list of different implementations of the Component abstract class. Any help would be appreciated.
Here is the code:
Component.h
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <string>
class GameObject;
class Component{
public:
GameObject* gameObject;
std::string name;
virtual void update(const float &dt) = 0;
virtual void draw() = 0;
virtual void start() = 0;
virtual ~Component();
};
GameObject.h
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <vector>
#include <string>
#include <typeinfo>
#include "Transform.h"
class GameObject{
public:
Transform transform;
GameObject(const std::string &name, const Transform &transform);
class Component& getComponent(const std::string &name);
void addComponent(const class Component &c);
std::vector<class Component> getAllComponents();
class Component& removeComponent(const std::string &name);
void update(const float &dt);
private:
std::vector<class Component> components;
std::string name;
};
gameObject.cpp
#include "Component.h"
GameObject::GameObject(const std::string &name, const Transform &transform)
:name(name), transform(transform)
{}
GameObject::class Component& getComponent(const std::string &name)
{
for(Component& c : components)
{
if(c.name == name)
return c;
else
return nullptr;
}
}
GameObject::void addComponent(const Component &c)
{
components.push_back(c);
c.gameObject = this;
}
GameObject::class Component& removeComponent(const std::string &name)
{
for (int i = 0; i < components.size(); i++) {
if(components[i].name == name)
components.erase(i);
}
GameObject::std::vector<class Component> getAllComponents()
{
return components;
}
GameObject::void update(const float &dt)
{
for(Component c : components)
{
c.update(dt);
}
}
|
First things first, you don't need to added the class key class everywhere a class name is expected. Often it is optional in C++ unlike C.
Problem 2
Next, you're actually defining a free function named getComponent instead of a member function. For defining the member function outside the class, we first have to be in the scope of the class which we can do by using the scope resolution operator :: as shown below.
class GameObject{
public:
Transform transform;
GameObject(const std::string &name, const Transform &transform);
//--v------------------------------------------------>removed class keyword from here
Component& getComponent(const std::string &name);
void addComponent(const class Component &c);
//--------------v------------------------------------>removed class keyword from here
std::vector< Component> getAllComponents();
//-v---------------------------------------------------->removed class keyword from here
Component& removeComponent(const std::string &name);
void update(const float &dt);
private:
//--------------v-------------------------->removed class keyword from here
std::vector< Component> components;
std::string name;
};
//-------------------vv---------------------------------->uses scope resolution operator here
Component& GameObject::getComponent(const std::string &name)
{
for(Component& c : components)
{
if(c.name == name)
return c;
else
return NULL;
}
}
Problem 3
The return type of the member function while implementing it outside the class should be placed before the name of the member function. This means GameObject::void addComponent(const Component &c) is invalid and should be changed to:
vvvv------------------------------------------------>return type void is placed before naming the member function
void GameObject::addComponent(const Component &c)
{
}
vvvvvvvvv---------------------------------------->return type Component& is placed before naming the member function
Component& GameObject::removeComponent(const std::string &name)
{
for (int i = 0; i < components.size(); i++) {
if(components[i].name == name)
components.erase(i);
}
|
74,154,268
| 74,212,004
|
Is it possible to create a service at runtime using gRPC C++ from a descriptor set?
|
I'm attempting to create some test drivers for some C++ applications that communicate over gRPC. Most of these test drivers simply use grpcurl to fire off some messages to the applications under tests and verify the responses.
Some of our apps, however, connect to streaming RPCs. It would be trivial to write a test driver app that serves all the streams we need; however I was hoping to make something a bit more generic. My idea was to write an app that could take in a descriptor set, the name of the streaming method to serve, and a JSON file defining the message to serve out when applications connect to the streaming RPC.
Parsing the descriptor set (generated via protoc's --descriptor_set_out argument), getting service and method descriptors for the streaming method, and loading the message to return from a JSON file were all pretty easy. Where I'm hung up is actually creating the service from the descriptor.
Here's the code I threw together as a quick proof-of-concept - note no error checking / hardcoded paths, I'm just trying to quickly see if this will work:
#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/util/json_util.h"
#include <fstream>
#include <sstream>
int main(int argc, char** argv)
{
google::protobuf::FileDescriptorSet desc;
std::stringstream sst;
{
std::ifstream i("/tmp/test.protoset");
sst << i.rdbuf();
}
desc.ParseFromString(sst.str());
google::protobuf::DescriptorPool desc_pool;
for (const auto& fdesc : desc.file())
{
desc_pool.BuildFile(fdesc);
}
auto sdesc = desc_pool.FindServiceByName("TestService");
auto mdesc = sdesc->FindMethodByName("connect");
auto resp_type = mdesc->output_type();
google::protobuf::DynamicMessageFactory dmf(&desc_pool);
sst.str("");
sst.clear();
auto out_message = std::shared_ptr<google::protobuf::Message>(dmf.GetPrototype(resp_type)->New());
{
std::ifstream i("/tmp/test_message.json");
sst << i.rdbuf();
}
auto stat = google::protobuf::util::JsonStringToMessage(sst.str(), out_message.get());
std::cout << "READ " << stat << " " << out_message->DebugString() << std::endl;
}
Is it now in any way possible to actually create the "TestService/connect" streaming rpc, wait for a connection, and return the message built in out_message?
|
There are a couple of ways to achieve this and one of which would be using gRPC C++ GenericService. By doing so, you can handle all methods without pre-declaring them.
|
74,154,484
| 74,154,550
|
`constexpr vector` still fails, while there's stated to be supported in cppreference
|
On https://en.cppreference.com/w/cpp/compiler_support, cosnstexpr vector is stated to be supported.
But when I wrote
#include <vector>
constexpr std::vector<int> vec{2, 3, 3, 3};
int main()
{
}
and compiles it using -std=gnu++2b flag,
it still triggers a error
In file included from /usr/include/c++/12/vector:61,
from test.cpp:1:
/usr/include/c++/12/bits/allocator.h:182:50: error: ‘std::vector<int>(std::initializer_list<int>{((const int*)(& const int [4]{2, 3, 3, 3})), 4}, std::allocator<int>())’ is not a constant expression because it refers to a result of ‘operator new’
182 | return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));
| ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~
I don't understand why, can someone help me?
My gcc version gcc version 12.1.0 (Ubuntu 12.1.0-2ubuntu1~22.04)
and __cpp_constexpr == 202110L
|
std::vector being constexpr-friendly means that it can be used inside a constant expression evaluation. It does not mean that a variable of that type can be declared with constexpr specifier. (Talking about constexpr std::vector in that context is maybe a bit misleading.)
Because std::vector uses dynamic allocation, it still must be destroyed during the evaluation of the constant expression, which is not the case in the initialization of a variable of that type.
What is allowed now is e.g.:
constexpr int some_calculation(int input) {
std::vector<int> vec;
// some complicated algorithm using `input`, using `vec` to store e.g. intermediate results
return /* the result */;
}
constexpr int constant_value = some_calculation(42);
|
74,154,552
| 74,154,846
|
Structuring a project with circular dependencies using C++ modules
|
I have an existing C++ project, and although I'm being pretty experienced with C++ itself, I haven't dony anything with modules yet and I thought it was time to finally bite that bullet.
I have a small library which is currently structured in several source and header files, where each header describes a major class and some of its smaller satellite types and functions. I like this set up, and my initial take on retrofitting modules into this was simply to have each source file being a module part. But I quickly ran into the problem of circular dependencies.
For the sake of argument, let's say this is a simple JSON library that uses some variant-like type called a JsonValue, with a source setup like this:
// JsonValue.h
#include "JsonArray.h"
class JsonValue
{
std::variant<double, JsonArray> data;
// ...
};
// JsonArray.h
class JsonValue;
class JsonArray
{
std::vector<JsonValue> array;
// ...
};
You'll notice the circular dependency here. JsonValue depends on the definition of JsonArray, and JsonArray depends on the declaration of JsonValue. In practice, this works fine. Although you can't construct a JsonArray in a translation unit that doesn't know the definition of JsonValue (the std::vector<JsonValue> requires this), in reality you'll never just include JsonArray.h without including JsonValue.h.
So, naive as I was, I simply converted the header files to module interface files that respectively exported the modules json:value and json:array. I imported the json:array into json:value, and for json:array itself I didn't need to do anything else. Or so I thought.
// JsonValue.ixx
export module json:value;
import json:array;
export class JsonValue
{
std::variant<double, JsonArray> data;
// ...
};
// JsonArray.ixx
export module json:array;
export class JsonArray
{
std::vector<JsonValue> array;
// ...
};
(And all member function implementations go in their respective module implementation files)
However, as it turns out, the circular dependency is a problem with modules, as they're essentially separate translation units with their own compilation step. The json:array module gets compiled separately without knowing the definition of JsonValue. I can't import json:value, because json:value itself is dependent on json:array.
I think that the only solution here is to have both classes in the same module interface file. That certainly seems the gist of this answer, although that one doesn't suffer from my problem as they just use pointers.
But I don't want that. In reality, the classes are a lot bigger than just these simple classes, and I don't want to dump them all into the same module interface file. I guess I can still hack around this using includes (which then are not supposed to be included on their own), but that feels kind of dirty. I'm really hoping there's some other solution that I'm missing.
And, perhaps naively as well, I was hoping to do away with separate class definitions and implementations by having every function implemented inline in the class itself. That certainly doesn't seem to be the case, especially not in this particular example.
|
What you need to do is make sure that the interface partition module json:array does not contain any code that requires JsonValue to be defined. Definitions of member functions or any other code which accesses it should not be part of that partition. They should be defined in an implementation unit, or a later interface unit, so long as they importsboth json:array and json:value.
Also, do not forget to export forward declarations of exported entities.
|
74,154,595
| 74,154,817
|
Modifying a data of type "static const int* const" from a member function
|
TLDR Question:
class MyClass
{
public:
void Modify()
{
//How can I modify MyData here
}
public:
static const int* const MyData;
};
Lore:
I have a class like this:
class Window
{
public:
const int* GetKeyboard()
{
return m_Keyboard;
}
private:
const int* const m_Keyboard = 0;
};
With this I would access keyboard as WindowObjectPtr->GetKeyboard() but I want to access it as Input::Keyboard. So I wrote something like this:
class Window
{
public:
const int* GetKeyboard()
{
return m_Keyboard;
}
private:
const int* const m_Keyboard = 0;
};
const int* Input::Keyboard = 0;
class Application;
class Input
{
friend class Application;
private:
static void SetKeyboard(const int* k) { Keyboard = k; }
public:
static const int* Keyboard;
};
class Application
{
public:
void Init()
{
Input::SetKeyboard(m_Window.GetKeyboard());
}
private:
Window m_Window;
};
int main()
{
Application application;
application.Init();
//Input::Keyboard
}
The only problem with the above code is that I can do Input::Keyboaord = nullptr;
So I want to change definition of keyboard to static const int* const Keyboard; but then Input::SetKeyboard cannot set it anymore.
Is there a valid version of something like mutable static const int* const Keyboard; ? or a different method of achieving what I am trying to do?
|
Either an object is const or it isn't. If it is const it must be given a value in its initialization and any attempt at changing it later will cause undefined behavior (if it isn't ill-formed to begin with).
There is no way to make an object const after a certain other point in the execution flow.
Of course you can just add a const reference to the object and use that whenever you don't intent to modify it for const-correctness:
static const int* Keyboard;
static const int* const& cKeyboard = Keyboard;
Now Keyboard can be used for modification and cKeyboard can't (without const_cast trickery).
But that all seems like completely avoidable and messy, since you could just have Keyboard be a non-static member, have Application have a non-static Input member and then have all initialization happen in the constructor's initializer lists. Then there wouldn't be a problem with having Keyboard be const-qualified at all.
|
74,155,446
| 74,155,466
|
void function parameter and overload resolution/template argument deduction
|
I am developing a system where users register their functions with a framework that calls the functions on the users' behalf. The framework accepts user functions that have at least one function parameter, which helps discourage functions with too many side effects. The number of input parameters to a function is thus checked at compile time. My code for getting the number of input parameters is simple:
template <typename R, typename... Args>
constexpr std::size_t number_input_parameters(R (*)(Args...)) { return sizeof...(Args); }
and then using it:
int no_parameters() {} // would be rejected by the framework
static_assert(number_input_parameters(no_parameters) == 0);
While developing the code, I was worried about functions that have void parameters:
int still_no_parameters(void) {} // framework should also reject this
but to my delight, the above implementation of number_of_parameters gives the right answer (using Clang 15 and GCC 12):
static_assert(number_input_parameters(still_no_parameters) == 0);
See https://godbolt.org/z/Taeox1rMq.
So clearly a function with a type R(void) is correctly interpreted by the compiler as having type R(). The link above also shows this to be true without using templates.
The question: In what way does the C++(20) standard somehow specify that a void function parameter should be ignored? I've looked in various places and been unsuccessful.
|
In what way does the C++(20) standard somehow specify that a void function parameter should be ignored?
From https://eel.is/c++draft/dcl.dcl#dcl.fct-4 :
A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
|
74,155,493
| 74,166,152
|
How can I resize frameless window in QML?
|
How can I return resize logic of borders in Frameless Window?
The frame windows has this logic:
Code in QML:
import QtQuick
import QtQuick.Controls 2.5
import Qt5Compat.GraphicalEffects
import NR 1.0
Window {
id: mainWindow
width: 640
height: 720
visible: true
title: qsTr("Hello World")
flags: Qt.Window | Qt.FramelessWindowHint
color: "transparent"
// (1)
MouseArea {
id: bottomArea
height: 5
anchors {
bottom: parent.bottom
left: parent.left
right: parent.right
}
cursorShape: Qt.SizeVerCursor
onPressed: {
previousY = mouseY
}
onMouseYChanged: {
var dy = mouseY - previousY
mainWindow.setHeight(mainWindow.height + dy)
}
}
// Some code of another Items here
}
I tried this code for left side:
MouseArea {
id: leftSideMouseArea
anchors.fill: parent
property point lastMousePos: Qt.point(0, 0)
onPressed: { lastMousePos = Qt.point(mouseX, mouseY); }
onMouseXChanged: mainWindow.width += (mouseX + lastMousePos.x)
}
I put this code in (1) place, but it doesn't work - on click (without move) windows resize to the rigth and app crashes with error:
QQuickPaintedItem::textureProvider: can only be queried on the
rendering thread of an exposed window
This looks like on picture:
Can you help me?
Thanks!
|
Since Qt5.15, we have startSystemResize, which performs a native resizing and is recommended against using methods like comparing the click position to the current position.
The function is very simple; once you pass an edge, the window begins to resize.
An example of a frameless window is shown below:
CustomWindow.QML
Change the offset from the window's edges where the mouse can be pressed by using this property.
property int edgeOffest: 5
Also for moving the window as well You can use a DragHandler, which, when activated, calls startSystemMove.
Window {
width: 200; height: 100
color: '#fab'
flags: Qt.Window | Qt.FramelessWindowHint
DragHandler {
onActiveChanged: if(active) startSystemMove();
}
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.LeftButton
property int edges: 0;
property int edgeOffest: 5;
function setEdges(x, y) {
edges = 0;
if(x < edgeOffest) edges |= Qt.LeftEdge;
if(x > (width - edgeOffest)) edges |= Qt.RightEdge;
if(y < edgeOffest) edges |= Qt.TopEdge;
if(y > (height - edgeOffest)) edges |= Qt.BottomEdge;
}
cursorShape: {
return !containsMouse ? Qt.ArrowCursor:
edges == 3 || edges == 12 ? Qt.SizeFDiagCursor :
edges == 5 || edges == 10 ? Qt.SizeBDiagCursor :
edges & 9 ? Qt.SizeVerCursor :
edges & 6 ? Qt.SizeHorCursor : Qt.ArrowCursor;
}
onPositionChanged: setEdges(mouseX, mouseY);
onPressed: {
setEdges(mouseX, mouseY);
if(edges && containsMouse) {
startSystemResize(edges);
}
}
}
}
Preview
Final Notes
Still, I do not recommend developing a custom window with custom functionality, which forces you to handle a lot of functions while still not feeling like a native one.
However, there are a few github projects that offered some helper libraries for this, so take a look at those.
https://github.com/antonypro/QGoodWindow
https://github.com/wangwenx190/framelesshelper
|
74,155,721
| 74,157,243
|
timer for measuring function execution time not working
|
I'm writing a cuda library and I need to check the differences in performance between the option CPU and GPU. So I created a simple class called Timer to measure the time required to execute first a GPU function and then the CPU version.
class Timer
{
public:
Timer()
{
_StartTimepoint = std::chrono::steady_clock::now();
}
~Timer() {}
void Stop()
{
_stopped = true;
using namespace std::chrono;
auto endTimepoint = steady_clock::now();
auto start = time_point_cast<milliseconds>(_StartTimepoint).time_since_epoch().count();
auto end = time_point_cast<milliseconds>(endTimepoint).time_since_epoch().count();
auto _ms = end - start;
_secs = _ms / 1000;
_ms -= _secs * 1000;
_mins = _secs / 60;
_secs -= _mins * 60;
_hour = _mins / 60;
_mins -= _hour * 60;
}
double GetTime(){
if(_stopped == true)
return _ms;
else{
Stop();
return _ms;
}
}
private:
std::chrono::time_point< std::chrono::steady_clock> _StartTimepoint;
double _secs,_ms,_mins,_hour;
bool _stopped = false;
};
Since I need to check the performances for different values of a parameter m I just run both the functions inside a for loop as you can see:
for (size_t m = MIN_M; m < MAX_M; m+=M_STEP){
m_array[m_cont] = m;
//simulate
double time_gpu,time_cpu;
Timer timer_gpu;
run_device(prcr_args,seeds,&m_array[m_cont]);
timer_gpu.Stop();
time_gpu = timer_gpu.GetTime();
Timer timer_cpu;
simulate_host(prcr_args,seeds,&m_array[m_cont]);
timer_cpu.Stop();
time_cpu = timer_cpu.GetTime();
double g = time_cpu/time_gpu;
ofs << m //stream to print the results
<< "," << time_cpu
<< "," << time_gpu
<< "," << g << "\n";
m_cont ++;
}
The problem is that the results i obtain are incredibly small and clearly wrong since they all are equal (the execution time should increase with m) and that my code requires a couple of minutes to run.
m,cpu_time,gpu_time,g
10,9.88131e-324,6.90979e-310,1.43004e-14
15,9.88131e-324,6.90979e-310,1.43004e-14
....
90,9.88131e-324,6.90979e-310,1.43004e-14
95,9.88131e-324,6.90979e-310,1.43004e-14
100,9.88131e-324,6.90979e-310,1.43004e-14
My guess is that the CPU doesn't execute the cycle sequentially and therefore starts and stops the clock immediately.
|
You declare a local variable _ms with the same name as your member variable. During the stop function the local variable takes precedence over the member variable, so you never actually store a value in the member. You can show this by initializing the member to some value in the class definition and you will see that same value pop out at the end. The 'auto' has nothing to do with it - defining it strictly as a double will have the same results of creating a local that takes precedence over the member.
Because you left the member un-initialized, it is filled in with whatever happened to be on the stack where it was created. This is why each instantiation of the timer has the same value within the loop.
one very small fix:
auto _msB = end - start;
_secs = _msB / 1000;
_ms = _msB - _secs * 1000;
You should also initialize your member variables so that debugging is easier, even if they are going to get overwritten during use.
I would also encourage letting the chrono library do more of the work for you. A very brief snippet would be:
auto duration = endTimepoint - _StartTimepoint;
auto ms = duration_cast<milliseconds>(duration);
_ms = ms.count();
You can do a duration cast for each unit type of name without having the possibility of a typo on the conversions or unnecessarily losing precision.
I'm not sure why you want differential time numbers as part of the timer, but if you must do that arithmetic you can do it by using the std::ratio on the count values that come out of duration casts.
|
74,155,956
| 74,174,392
|
Use OpenSSL in Unreal Engine 4.25
|
I’m trying to use the OpenSSL library included with the engine.
I am using 4.25
In my searches I see people saying to add OpenSSl as a dependency to my project’s build file.
I have seen couple different lines to add to the build file, every one of them causes errors - usually about the the function not being in the current context.
AddEngineThirdPartyPrivateStaticDependencies(Target, “OpenSSL”);
is one example - I believe I read some where to try
ExtraModuleNames.AddRange( new string[] { “OpenSSL”} ); - but that came back with OpenSSL not being a c++ module.
There is another function out there that I forget, but when I tried it, I got the error again about not being in context.
So far only by adding the folder “E:\UE_4.25\Engine\Source\ThirdParty\OpenSSL\1.1.1\Include\Win64\VS2015” to the visual studio c/c++ directory includes list can I just do a regular "#include “openssl/sha.h”. - but when I compiled it, it failed saying that the file didn't exist. Yet I can right click the include in code and view it, as well as intellisense recognizing the classes and functions.
In the solution explorer, I can see the openssl folder under UE4\Source\ThirdParty\openssl - but none of the different openssl version show up and none of the source code files.
In fact, all the ThirdParty libraries just contain one or more build files, or files with a .tps extension.
My ultimate goal is to get access to sha-256 to generate a hash for comparing local custom maps with a server copy - assumption is that if hash is different, server copy is a newer version and is then downloaded.
So my ultimate question is how do I use Unreal's included OpenSSL library.
|
My problem is that I kept trying to do things in the target file, not the build file - as mentioned in a comment above by Strom.
To enable OpenSSL in an unreal c++ project (I'm using Visual Studio):
Open up your project build file.
Add OpenSSL to the PublicDependencyModuleNames:
using UnrealBuildTool;
public class MyProject : ModuleRules
{
public MyProject(ReadOnlyTargetRules Target) : base(Target)
{
PublicDependencyModuleNames.AddRange(new string[] {
"PhysicsCore",
"OpenSSL"
});
}
}
Close your solution, right click your unreal project .uproject file and choose "Generate Project Files".
Where you want to use openSSL add at the top of your code file in the includes section or in your header file. (in my case I'm using evp as the docs say for sha256).
#define UI UI_ST
THIRD_PARTY_INCLUDES_START
#include "openssl/evp.h"
THIRD_PARTY_INCLUDES_END
#undef UI
|
74,156,096
| 74,158,117
|
Eigen tensor reshape then broadcast results in gibberish numbers when going from rank 0 to rank 1 tensor
|
I have the following code that seeks to find the maximum element of a rank 1 tensor, which shrinks to a rank 0 tensor, and then broadcast it back out to the full length of the rank 1 tensor so I can use it in further computations involving the original rank 1 tensor.
//reduces a rank 1 tensor to a rank 0 tensor.
Tensor<double,0> columnmaximum = input_tensor.maximum(this->imposed_dim).eval();
std::cout << "colmax is\n" << columnmaximum << std::endl;
this->columnbroadcast = Eigen::array<int,1> ({M});
this->rank1base = Eigen::array<int,1> ({1});
//expands it back out to a full column. columnshape is just
Tensor<double,1> columnmaximum_rk2 = columnmaximum.reshape(this->rank1base).broadcast(this->columnbroadcast);
std::cout << "colmaxrk2 is\n" << columnmaximum_rk2 << std::endl;
and noticed the following strange output:
colmax is
-2
colmaxrk2 is
-2
0.238402
3.91433e-310
-3.33086
-2
Something went wrong when broadcasting. My idea was to elevate the rank 0 tensor to a rank 1 tensor (of length one), and then broadcast in the single dimension to replicate the maximum as many times as I need to be able to subtract it from something else.
What is going wrong here with those three numbers in between when printing the enlarged tensor? I know in this special case, I could use the setConstant method but would like to use the reshape then broadcast trick also for higher-dimensional tensors where a summary statistic is less trivial, i.e. a rank 2 tensor etc..
Can anyone explain to me where these non-sensical numbers appear from? Am I committing a basic mistake? The amazingly small number looks a bit like unallocated memory to me.
Thank you so much!
|
It appears to be a bug in Eigen 3.4.0 related to tensors of dimension zero. Reproducible example (godbolt):
#include <iostream>
#include <Eigen/../unsupported/Eigen/CXX11/Tensor>
int main()
{
Eigen::Tensor<double, 3> MaxTest(4, 4, 4);
MaxTest.setRandom();
Eigen::Tensor<double, 0> columnmaximum = MaxTest.maximum();
std::cout << "colmax is\n" << columnmaximum << std::endl;
Eigen::array<Eigen::Index, 1> columnbroadcast({6});
Eigen::array<Eigen::Index, 1> rank1base({1});
Eigen::Tensor<double, 1> columnmaximum_rk2 = columnmaximum.reshape(rank1base).broadcast(columnbroadcast);
std::cout << "colmaxrk2 is\n" << columnmaximum_rk2 << std::endl;
}
If the debug checks in the standard library are enabled (-D_GLIBCXX_DEBUG for gcc's stdlibc++), the evaluation of the assignment (operator=()) to columnmaximum_rk2 fails. Without debug, it prints some random values as shown in the original post.
Putting an eval() between the reshape() and the broadcast() prevents the issue (godbolt):
Tensor<double, 1> columnmaximum_rk2 =
columnmaximum.reshape(rank1base).eval().broadcast(columnbroadcast);
Interestingly, Eigen trunk is not affected anymore by the issue (godbolt). Apparently, it got fixed since Eigen 3.4.0. Indeed, there is one commit that at least deals with the tensor broadcast (but I am not sure if this commit specifically fixes the issue).
Thus, another workaround could be to use the current trunk version.
|
74,156,130
| 74,156,254
|
How do I use concepts to constrain the argument types for variadic functions?
|
I have a variadic function that can take any combination of input arguments, as long as each one of those arguments is convertible to bool:
#include <concepts>
#include <cstddef>
// internal helper functions
namespace {
template <typename T>
constexpr std::size_t count_truths(T t) {
return (bool)t;
}
template <typename T, typename... Args>
constexpr std::size_t count_truths(T t, Args... args) { // recursive variadic function
return count_truths(t) + count_truths(args...);
}
}
template <typename T>
concept Booly = std::convertible_to<T, bool>;
// variadic function for which all arguments should be constrained to Booly<T>
// e.g. only_one(true, false, true, false, true) = false; only_one(true, false) = true
template <typename T, typename... Args> requires Booly<T>
constexpr bool only_one(T t, Args... args) {
return count_truths(t, args...) == 1;
}
I have attempted to constrain the templates using concepts to only allow bool-convertible types to be passed, but I have only managed to do so for the first parameter:
// following lines compile:
only_one(true, false, false);
only_one(BoolConvertible(), true, false);
// this line is correctly forced to failure due to the concept not being satisfied:
only_one(NonBoolConvertible(), false, true);
// BUT this line is not detected as a concept constraint failure (but still compilation failure):
only_one(true, NonBoolConvertible(), false, true);
How can I use C++20 concepts to constrain the remaining template parameters to ensure each one of them in Args... satisfies Booly<> ?
|
You can simply use C++17 fold expression to do this
#include <concepts>
template<std::convertible_to<bool>... Args>
constexpr bool only_one(Args... args) {
return (bool(args) + ... + false) == 1;
}
static_assert(only_one(true, false, true, false, true) == false);
static_assert(only_one(true, false) == true);
static_assert(only_one() == false); // allow empty pack
|
74,156,310
| 74,164,771
|
C++ - What are virtual methods?
|
Based on this, the following code should print "Running derived method", but when I run it, it prints "Running base method":
#include <iostream>
using namespace std;
class Base
{
public:
Base() {}
virtual void run() {cout << "Running base method" << endl;}
virtual ~Base() {}
};
class Derived : public Base
{
public:
Derived() {}
void run() {cout << "Running derived method" << endl;}
~Derived() {}
};
int main()
{
Base o = Derived();
o.run();
return 0;
}
|
There is an answer in the comments, but I have to post it as an answer to close it. Before reading it, I found it out myself by comparing the example code with my code, but the comment was helpful because I now know it's called object slicing. When I assign the value to a variable or field that has the base type, it forgets the original type, and to make it work properly, I have to use pointers
|
74,156,448
| 74,156,468
|
How to use pointer to member inside a class object (right syntax)?
|
In this example i'm trying to return x, y or z from get_by_ptr function, but can't unedrastand rigth(legal) syntax to do it. I understand that this pointer holds base address of object and pointer to member holds "address shift" and I can calculate address. But is there legal syntax way?
class foo {
public:
size_t x{ 33 };
size_t y{ 77 };
size_t z{ 99 };
size_t get_by_ptr(size_t foo::*ptr) {
//how to return x, y or z using ptr
}
};
int main() {
foo bar;
size_t foo::*ptr{ &foo::y };
size_t z{ bar.get_by_ptr(ptr) };
}
Thank You.
|
You likely want to write:
size_t get_by_ptr(size_t foo::*ptr) {
return this->*ptr;
}
|
74,156,479
| 74,156,590
|
Cannot execute int function in menu
|
I wrote program which use menu to execute function.
#include <iostream>
#include<conio.h>
#include <stdio.h>
#include <cstring>
using namespace std;
int menu();
void zad1();
void zad2();
int main(){
switch(menu()){
case 1: zad1();break;
case 2: zad1();break;
default: cout<<"blank";
};
getch();
return 0;
}
int menu(){
cout<<"Menu\n\n";
cout<<"Zad.1\nZad.2\n";
int wybor;
cin>>wybor;
return wybor;
}
int encryption(){
char string[256];
int i = 0;
int key = 3;
const int num_letters = 26;
printf("Enter the string you want encrypted\n");
fgets(string, sizeof(string), stdin);
for (i = 0; i < strlen(string); i++) {
if (string[i] >= 'a' && string[i] <= 'z') {
string[i] = 'a' + (string[i] - 'a' + key) % num_letters;
}
else if (string[i] >= 'A' && string[i] <= 'Z') {
string[i] = 'A' + (string[i] - 'A' + key) % num_letters;
}
}
printf("Encrypted: %s\n", string);
return 0;
}
void zad1(){
encryption();
}
The only thing is I my output is not working properly - it shows the menu, I can type number (1-2) to choose function to execute and all I get from function "encryption" is:
Enter the string you want encrypted
Encrypted:
and that's all - I can't type character. What am I missing? I used the menu before and everything worked properly.
|
After this input
cin>>wybor;
the input buffer contains the new line character '\n'.
So the next call of fgets
printf("Enter the string you want encrypted\n");
fgets(string, sizeof(string), stdin);
reads an empty string that contains only this new line character.
You need to clear the buffer before calling the function as for example
while ( getchar() != '\n' );
printf("Enter the string you want encrypted\n");
fgets(string, sizeof(string), stdin);
Or instead of the C function fgets you could use the C++ member function ignore for the object std::cin together with the function getline.
.
Also it seems here is a typo
case 2: zad1();break;
You should write
case 2: zad2();break;
Pay attention to that in fact your program is a C program. You are not using C++ features except the operator << for the output stream in the function menu. Using C stream functions and C++ stream functions together is a bad idea.
|
74,157,038
| 74,173,059
|
Create custom reporter for Catch2 in single header version
|
There is already a section in Catch2 documentation about how to create custom reporters. The problem is that this seems to work only for the non-single header version of Catch2.
Using single header version of Catch2, the two base classes for reporters (
Catch::StreamingReporterBase and Catch::CumulativeReporterBase) are not accessible.
They are not accessible because they are in a part of the header that is not included by the precompiler (by the way, I don't understand how default reporters work as they too are in not-included segments of the header).
Does someone know how to create custom reporters with single-header version of Catch2?
EDIT : I am using version 2 of Catch. The reporter base definitions are in a block disabled by a #ifdef OBJC block.
|
It depends on the version of the library you are using. Versions 2.x were based on the single header catch.hpp and had numerous additional macros to configure what is included from that header. In particular, you would need
#define CATCH_CONFIG_EXTERNAL_INTERFACES
#include "catch.hpp"
to access the reporter definitions.
With versions 3.x, this has changed and there are two options:
Adopt the new library architecture, meaning you link your targets against Catch2 and include the appropriate reporter header, e.g.
#include <catch2/reporters/catch_reporter_streaming_base.hpp>
Use the catch_amalgamated.hpp/cpp files to compile the library as a single translation unit. Additional configuration should no longer be needed to make the reporter classes available.
See also this document for more information on migrating to version 3.
|
74,157,060
| 74,196,934
|
Microsoft Graph - CompactToken parsing failed with error code: 8004920A
|
I am requesting access token from Microsoft Graph using this procedure:
I request access to the following scopes:
User.Read.All openid profile email offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All https://outlook.office.com/SMTP.Send
After the consent screen in web browser, the redirection occurs and the codes are sent to temporary localhost web server running on user's PC.
The code received is exchanged for access_token and refresh_token
When I try to query Microsoft Graph for user's profile I query:
GET https://graph.microsoft.com/v1.0/me
Header of the GET request contains:
Authorization: Bearer token-here-all-in-one-line
But I get the resulting JSON:
"InvalidAuthenticationToken"
"CompactToken parsing failed with error code: 8004920A"
I would normally assume the token is not correct, but I tested the same token from C++ app and a small PHP app, and I always test the same error. To be sure that it is not the wrong token, I deliberately modify it to a wrong token and then I get:
"CompactToken parsing failed with error code: 80049217"
After googling - 8004920A means "token rejected" (the error I have problem with) and 80049217 means "malformed token" so that is consistent with me deliberately inserting false data as token.
So I would assume that the token is correct but Microsoft Graph rejects it to query user profile information which is consented and approved.
I have tested the token on IMAP and SMTP access and there it works - mails are sent and received, so the access_token is definitely good.
Any ideas why Microsoft Graph rejects my attempt to query user profile?
Do I need to enable something when registering application in AzureAD portal?
I am doing this from C++ or from PHP so I don't think the code is of relevance here.
|
As @Nikolay has stated, the tokens for Graph and Outlook can't be mixed. And Microsoft has designed it poorly so that IMAP.AccessAsUser.All for example can't be used for IMAP access - the access_token simply won't work unless the https://outlook.office.com/ prefix is added.
But - I found another way, which works for just reading the user's profile and email address which is by decoding the id_token. As Microsoft documentation states - openid profile and email scopes will work with both Graph and Outlook. profile token can be used to extract the information about user's profile.
As explained on:
https://learn.microsoft.com/en-us/azure/active-directory/develop/id-tokens
id_token contains information such as email address, name etc.
A sample ID token from their page is:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjFMVE16YWtpaGlSbGFfOHoyQkVKVlhlV01xbyJ9.eyJ2ZXIiOiIyLjAiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vOTEyMjA0MGQtNmM2Ny00YzViLWIxMTItMzZhMzA0YjY2ZGFkL3YyLjAiLCJzdWIiOiJBQUFBQUFBQUFBQUFBQUFBQUFBQUFJa3pxRlZyU2FTYUZIeTc4MmJidGFRIiwiYXVkIjoiNmNiMDQwMTgtYTNmNS00NmE3LWI5OTUtOTQwYzc4ZjVhZWYzIiwiZXhwIjoxNTM2MzYxNDExLCJpYXQiOjE1MzYyNzQ3MTEsIm5iZiI6MTUzNjI3NDcxMSwibmFtZSI6IkFiZSBMaW5jb2xuIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiQWJlTGlAbWljcm9zb2Z0LmNvbSIsIm9pZCI6IjAwMDAwMDAwLTAwMDAtMDAwMC02NmYzLTMzMzJlY2E3ZWE4MSIsInRpZCI6IjkxMjIwNDBkLTZjNjctNGM1Yi1iMTEyLTM2YTMwNGI2NmRhZCIsIm5vbmNlIjoiMTIzNTIzIiwiYWlvIjoiRGYyVVZYTDFpeCFsTUNXTVNPSkJjRmF0emNHZnZGR2hqS3Y4cTVnMHg3MzJkUjVNQjVCaXN2R1FPN1lXQnlqZDhpUURMcSFlR2JJRGFreXA1bW5PcmNkcUhlWVNubHRlcFFtUnA2QUlaOGpZIn0.1AFWW-Ck5nROwSlltm7GzZvDwUkqvhSQpm55TQsmVo9Y59cLhRXpvB8n-55HCr9Z6G_31_UbeUkoz612I2j_Sm9FFShSDDjoaLQr54CreGIJvjtmS3EkK9a7SJBbcpL1MpUtlfygow39tFjY7EVNW9plWUvRrTgVk7lYLprvfzw-CIqw3gHC-T7IK_m_xkr08INERBtaecwhTeN4chPC4W3jdmw_lIxzC48YoQ0dB1L9-ImX98Egypfrlbm0IBL5spFzL6JDZIRRJOu8vecJvj1mq-IUhGt0MacxX8jdxYLP-KUu2d9MbNKpCKJuZ7p8gwTL5B7NlUdh_dmSviPWrw
The token consists of 3 parts - header, payload and the signature. They are separated by a dot. That's a standard JWT (JSON Web Token) See details at - https://en.wikipedia.org/wiki/JSON_Web_Token
After separating them and then base64 decoding each (the signature doesn't give anything useful after decoding) the result is:
1) The header
{
"typ": "JWT",
"alg": "RS256",
"kid": "1LTMzakihiRla_8z2BEJVXeWMqo"
}
2) The payload
Payload which contains the user info. Additional information can be extracted by adding Optional claims when registering app in Azure AD - (Token configuration in the menu on the left).
{
"ver": "2.0",
"iss": "https://login.microsoftonline.com/9122040d-6c67-4c5b-b112-36a304b66dad/v2.0",
"sub": "AAAAAAAAAAAAAAAAAAAAAIkzqFVrSaSaFHy782bbtaQ",
"aud": "6cb04018-a3f5-46a7-b995-940c78f5aef3",
"exp": 1536361411,
"iat": 1536274711,
"nbf": 1536274711,
"name": "Abe Lincoln",
"preferred_username": "AbeLi@microsoft.com",
"oid": "00000000-0000-0000-66f3-3332eca7ea81",
"tid": "9122040d-6c67-4c5b-b112-36a304b66dad",
"nonce": "123523",
"aio": "Df2UVXL1ix!lMCWMSOJBcFatzcGfvFGhjKv8q5g0x732dR5MB5BisvGQO7YWByjd8iQDLq!eGbIDakyp5mnOrcdqHeYSnltepQmRp6AIZ8jY"
}
3) The signature
For verification purposes only.
1AFWW-Ck5nROwSlltm7GzZvDwUkqvhSQpm55TQsmVo9Y59cLhRXpvB8n-55HCr9Z6G_31_UbeUkoz612I2j_Sm9FFShSDDjoaLQr54CreGIJvjtmS3EkK9a7SJBbcpL1MpUtlfygow39tFjY7EVNW9plWUvRrTgVk7lYLprvfzw-CIqw3gHC-T7IK_m_xkr08INERBtaecwhTeN4chPC4W3jdmw_lIxzC48YoQ0dB1L9-ImX98Egypfrlbm0IBL5spFzL6JDZIRRJOu8vecJvj1mq-IUhGt0MacxX8jdxYLP-KUu2d9MbNKpCKJuZ7p8gwTL5B7NlUdh_dmSviPWrw
|
74,157,171
| 74,157,266
|
C++ struct in a class with error: expected an identifier
|
Here is the simplest I think I can get this code:
class MyFrame : public wxFrame
{
public:
MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size);
private:
struct controlChoice
{
wxChoice *choice;
int prevChoice;
};
wxPanel *panel;
controlChoice *profileChoice;
}
MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
{
this->panel = new wxPanel(this, wxID_ANY);
controlChoice this->profileChoice;
this->profileChoice->choice = new wxChoice(this->panel, wxID_ANY);
}
On the line "controlChoice this->profileChoice;"
I receive "error: expected an identifier" and it's the "this" that's showing the error.
EDIT: removed the "does compile". Possibly it wasn't removing the previously successfully compiled executable and I just kept loading that.
|
The code does compile.
That is not valid C++ syntax and any conformant C++ compiler should reject it as controlChoice is a typename while this->profileChoice is a qualified name and C++ grammar rules doesn't allow such an usage.
You can instead use the member initializer list for initialization of those members:
class MyFrame : public wxFrame
{
public:
MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size);
private:
struct controlChoice
{
wxChoice *choice;
int prevChoice;
//add a constructor
controlChoice(wxChoice *pChoice, int pPrevChoice): choice(pChoice),
prevChoice(pPrevChoice)
{
}
};
wxPanel *panel;
controlChoice *profileChoice;
}
MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size)
: wxFrame(NULL, wxID_ANY, title, pos, size),
panel(new wxPanel(this, wxID_ANY)),
profileChoice(new controlChoice(new wxChoice(this->panel, wxID_ANY), 5))
{
//empty body as we did the initialization in the member initializer list
}
Note that initialization can be done in the member initializaer as opposed to assignment which is done in the constructor body. And since in the modified program we've used the member initializer list, we don't need to do anything else in the constructor body.
|
74,157,640
| 74,158,217
|
Is there an easy way to implement C++ queries like the ones from ODB?
|
I am working with filters in C++ and I would like to create a query like ODB does:
db->query (query::age > 30)
I don't know what kind of data is being passed there. I have been reading about filters in C++ (with functors, lambda expressions, ...) but it is not as simple and compact as ODB queries. In addition, these query conditions can be concatenated.
db->query_one (query::first == "Joe" &&
query::last == "Dirt")
I have been looking what I think that the query class code is, but I have not been able to identify how it is achieved.
I need to filter a list of instances of Systems:
class Model
{
int id;
QString name;
};
class System
{
int id;
int user_id;
Model model;
};
I would like to have something like this:
Filter<System> system_filter;
Query<System> system_query(System::id == 1 && System::Model::name == "MyModelName")
system_filter.filter(system_list, system_query);
Currently I have this code (similar to an example of the book Design Patterns in Modern C++):
template <typename T>
struct Specification
{
virtual ~Specification(){}
virtual bool is_specified(T* item) = 0;
};
template <typename T>
struct Filter
{
virtual QList<T*> filter(QList<T*> items, Specification<T>& spec)
{
QList<T*> result;
for (auto& item:items)
{
if (spec.is_specified(item))
{
result.push_back(item);
}
}
return result;
}
};
template <typename T>
struct IdSpecification: common::Specification<T>
{
int id;
IdSpecification(int id) : id(id){}
public:
bool is_specified(T* item) override
{
return item->getId() == id;
}
};
template <typename T>
struct NameSpecification: common::Specification<T>
{
QRegularExpression regex;
NameSpecification(const QRegularExpression& regex) : regex(regex){}
public:
bool is_specified(T* item) override
{
QRegularExpressionMatch match = regex.match(item->getName());
return regex.match(item->getName()).hasMatch();
}
};
template <typename T, typename B>
template <typename T>
struct AndSpecification: Specification<T>
{
Specification<T>& first;
Specification<T>& second;
AndSpecification(Specification<T>& first, Specification<T>& second): first(first), second(second){}
public:
bool is_specified(T* item) override
{
return first.is_specified(item) && second.is_specified(item);
}
};
So now I can do something like this:
IdSpecification<System> system_specification(3);
NameSpecification<System> name_specification("SytemName");
AndSpecification<System> and_specification(system_specification, type_specification);
auto system_filtered = system_filter.filter(system_list, and_specification);
Thanks!
|
You want expression trees.
You might start with:
template<auto Member>
struct member_query_t;
template<class T, class V>
struct member_query_t< V T::* M > {
V const& operator()(T const& t) const { return t.*M; }
};
template<auto Member>
constexpr member_query_t<Member> member_q = {};
now member_q<&Model::id> is a C++ object that knows both what class it is operating on, and how to access the member id.
We can now build something called exprssion trees. Here, we make some types and overload some operators to return a compile-time type with the information about the expression encoded in it.
We can augment this with an ordering, a hash, a comparison, and the like, so our store can see we are being queried for Member and store fast lookup information inside itself for Member.
template<class T, class V>
struct member_query_t< V T::* M > {
V const& operator()(T const& t) const { return t.*M; }
auto hasher() const {
return std::hash<T>{};
}
auto ordering() const {
return std::less<T>{};
}
auto comparison() const {
return std::equal_to<T>{};
}
};
you can get fancy to avoid requiring full specialization for those traits. This kind of syntax would be possible:
auto system_query(
member_query<&System::id> == 1 &&
member_query<&System::model>[member_query<&Model::name>] == "MyModelName"
);
where system_query has the entire process of how a lookup works stored its type.
We can then do a completely different advanced technique called type erasure in C++ to make this into a Query<System>.
Each of these is easily 100s of lines of relatively dense template code to get working right.
What more, even after you do that, writing Filter<System> to work requires delving into RTTI and writing an efficient generic database system that can handle nearly arbitrary lookup mechanisms and compose them together on request.
So you have like 3 hard challenges to do what you want to describe, any one of which would require me multiple iterated versions to get right.
|
74,157,781
| 74,183,319
|
Cause of difference in performances of default pmr allocator and default std allocator
|
I am trying to investigate the cause of the difference in performance between the two allocators, as shown in https://en.cppreference.com/w/cpp/memory/monotonic_buffer_resource.
What I have found so far:
In GCC, it seems that the default pmr allocator uses monotonic_buffer_resource but not the std allocator, according to compiler explorer.
I looked into the source code of the header files and libstdc++, but could not find how
monotonic_buffer_resource was selected to be used by the default pmr allocator.
From my reading of the source code, it seems that std::pmr::new_delete_resource() should be used, and that should make default std allocator and default pmr allocator the same, but obviously it is not.
void default_pmr_alloc() {
std::pmr::list<int> list; // uses monotonic_buffer_resource
for (int i{}; i != total_nodes; ++i) {
list.push_back(i);
}
}
void default_std_alloc() {
std::list<int> list; // uses operator new/delete
for (int i{}; i != total_nodes; ++i) {
list.push_back(i);
}
}
|
It does indeed use new_delete_resource. (which from std::pmr::get_default_resource())
you can check it by
list.get_allocator().resource()->is_equal(*std::pmr::new_delete_resource()); // true
https://godbolt.org/z/qGTG57MfY
Not sure about what the benchmark is, but type erasure comes with it's own penalty, pmr one would probably be slower.
|
74,158,371
| 74,170,421
|
VCPKG and CMAKE not using static libraries when compiling a .exe
|
I have a project that uses gRPC and I have gRPC installed on Windows with VCPKG. I have the -x64-windows-static triplet installed and I have the target triplet set in my CMakePresets.json file as shown below:
"name": "windows-base",
"hidden": true,
"generator": "Visual Studio 17 2022",
"binaryDir": "${sourceDir}/out/build/${presetName}",
"installDir": "${sourceDir}/out/install/${presetName}",
"cacheVariables": {
"CMAKE_C_COMPILER": "cl.exe",
"CMAKE_CXX_COMPILER": "cl.exe",
"VCPKG_TARGET_TRIPLET": "x64-windows-static",
"CMAKE_TOOLCHAIN_FILE": {
"value": "C:/src/vcpkg/scripts/buildsystems/vcpkg.cmake",
"type": "FILEPATH"
}
},
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
}
Prior to this, using dynamic libraries, the project built fine and the build folder was populated with the .exe and the .dll libraries. I wish to instead use static libraries with this project and get a single .exe. Compiling with the static triplet option I only get the .exe file but when I run I get several errors that .dlls are missing. Specifically zlib1.dll, cares.dll, re2.dll, and abseil_dll.dll. I have confirmed that the static packages exist at C:\src\vcpkg\packages, so I am not sure why they are not being used.
My cmake files are as follows:
Top Level:
cmake_minimum_required (VERSION 3.8)
project ("server")
set(DBUILD_SHARED_LIBS OFF)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib")
find_package( gRPC CONFIG REQUIRED )
find_package(Protobuf REQUIRED)
# Include sub-projects.
add_subdirectory("library")
add_subdirectory("proto")
add_subdirectory("example")
library:
add_library(client_library STATIC "client_library.cpp" "client_library.h")
target_link_libraries(client_library PUBLIC proto_library gRPC::grpc++ gRPC::grpc++_reflection gRPC::gpr gRPC::grpc gRPC::grpc++ protobuf::libprotoc protobuf::libprotobuf protobuf::libprotobuf-lite)
target_include_directories(client_library PUBLIC "${PROJECT_SOURCE_DIR}/proto")
proto:
add_library(proto_library STATIC "example.pb.cc" "example.pb.h" "example.grpc.pb.cc" "example.grpc.pb.h")
target_link_libraries(proto_library PRIVATE gRPC::grpc++ gRPC::grpc++_reflection gRPC::gpr gRPC::grpc gRPC::grpc++ protobuf::libprotoc protobuf::libprotobuf protobuf::libprotobuf-lite)
example:
add_executable(example "example.cpp" "example.h")
target_link_libraries(example PRIVATE client_library proto_library)
target_include_directories(example PUBLIC "${PROJECT_SOURCE_DIR}/library")
Any advice? Apologize if this has been asked before but I searched and could not find anything. I can't tell if this is a cmake issue or some sort of vcpkg or visual studio issue.
EDIT: Here is my vcpkg package directory:
|
Delete your CMakeCache and retry. You probably had VCPKG_TARGET_TRIPLET not set on first configure which defaults to x64-windows and makes find_library|file|path|program already find the x64-windows stuff. Since these are all cache variables they won't be found anew on subsequent runs! Also consider setting VCPKG_HOST_TRIPLET.
Other stuff:
set(DBUILD_SHARED_LIBS OFF) has a typo. No D at the beginning!
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib") is unnecessary
cmake_minimum_required (VERSION 3.8) consider setting this higher
|
74,158,506
| 74,158,921
|
Time complexity of lookup and then insertion in a std::map<std::string, std::set<std::string>>
|
So I have a graph (std::map) that stores strings as the keys and the values are sets of strings (adjacency lists for each node in a graph):
std::map<std::string, std::set<std::string>> graph
My insertion code is simply:
graph[from].insert(to)
where from and to are both strings. So I insert to in the set of strings associated at the key from.
For the average and worst-case time complexities for this insertion bit of code, I think they are O(x*log(V) * y*log(n)), where x is the length of the string from, y is the length of the string to, V is the number of nodes in the graph, and n is the number of edges in the graph (I included the string lengths because I think we also have to consider std::string comparisons which are O(length of either string))?
And the best-case time complexity is either the same as the average/worst-cases or it's O(x*y), which occurs if we get lucky and the root node of the red-black tree for the map and sets implementations are the strings from and to, respectively -- although, I'm the least confident about this one.
I'd appreciate some help. Thanks.
|
Time complexity is in terms of something, for example key comparisons. Finding a key in a std::map or std::set is in O(log n) key comparisons. If your key comparison function compares two strings character by character, then you can say that finding a key in this case is in O(s log n) with s the average size of the key strings (and not just the key you are trying to find).
In your scenario, you first find from in O(s log V) and then insert to in O(t log N). s is the average size of the key strings in the map, t is the average size of the key strings in the specific set (the set that corresponds to from), V is the size of the map (or number of vertices), and N is the size of the specific set.
These are two separate steps, which is why I say "specific set" and not "all the sets in the map", and so the total time complexity is simply O(s log V) + O(t log N) or O(s log V + t log N).
If you don't know the characteristics of the set you will insert to in advance, then you could do some more averaging and end up with O(s log V + u log(E/V)), where u is the average size of the key strings in all the sets in the map, and E is the number of these keys (number of edges). Reminder: this complexity is in terms of character comparisons. It may or may not be useful, especially because it has four variables.
|
74,158,577
| 74,158,638
|
C++ pass a child as a parent to a function
|
so here's a simplified version of my setup:
class GenericSensor{
public:
int read(){
return something;
}
};
class SpecialSensor : public GenericSensor{
public:
int read(){
return somethingElse;
}
};
and I have a function:
void someFunction(GenericSensor s){
printf("value is: %d\n", s.read());
}
how do I make someFunction work with GenericSensor, SpecialSensor or any other derived class's object?
|
You should declare read() as a virtual function which SpecialSensor, or any other derived class, can override.
Moreover, you should not pass GenericSensor around by value, otherwise you will slice the caller's object. Rather, pass it around by pointer or reference instead. So have someFunction() receive s by GenericSensor* pointer or GenericSensor& reference.
|
74,159,354
| 74,159,422
|
Why does this need auto?
|
auto data = new char[480][640][3]();
char data = new char[480][640][3]();
First works.
Second doesnt.
Why? Isn't auto supposed to just replace itself with the type of the initializer?
|
Because the type isn't char. The type is char(*)[640][3] and the declaration would be written as
char (*data)[640][3] = new char[480][640][3]();
|
74,159,372
| 74,161,745
|
nvprof - Warning: No profile data collected
|
On attempting to use nvprof to profile my program, I receive the following output with no other information:
<program output>
======== Warning: No profile data collected.
The code used follows this classic first cuda program. I have had nvprof work on my system before, however I recently had to re-install cuda.
I have attempted to follow the suggestions in this post which suggested to include cudaDeviceReset() and cudaProfilerStart/Stop() and to use some extra profiling flags nvprof --unified-memory-profiling off without luck.
This nvidia developer forum post seems to run into a similar error, however the suggestions here seemed to indicate needing to use a different compiler than nvcc due to some OpenACC library I do not use.
System Specifications
System: Windows 11 x64 using WSL2
CPU: i7 8750H
GPU: gtx 1050 ti
CUDA Version: 11.8
For completeness, I have included my program code, though I imagine it has more to due with my system:
Compiling:
nvcc add.cu -o add_cuda
Profiling:
nvprof ./add_cuda
add.cu:
#include <iostream>
#include <math.h>
#include <cuda_profiler_api.h>
// function to add the elements of two arrays
__global__
void add(int n, float *x, float *y)
{
for (int i = 0; i < n; i++)
y[i] = x[i] + y[i];
}
int main(void)
{
int N = 1<<20; // 1M elements
cudaProfilerStart();
// Allocate Unified Memory -- accessible from CPU or GPU
float *x, *y;
cudaMallocManaged(&x, N*sizeof(float));
cudaMallocManaged(&y, N*sizeof(float));
// initialize x and y arrays on the host
for (int i = 0; i < N; i++) {
x[i] = 1.0f;
y[i] = 2.0f;
}
// Run kernel on 1M elements on the GPU
add<<<1, 1>>>(N, x, y);
// Wait for GPU to finish before accessing on host
cudaDeviceSynchronize();
// Check for errors (all values should be 3.0f)
float maxError = 0.0f;
for (int i = 0; i < N; i++)
maxError = fmax(maxError, fabs(y[i]-3.0f));
std::cout << "Max error: " << maxError << std::endl;
// Free memory
cudaFree(x);
cudaFree(y);
cudaDeviceReset();
cudaProfilerStop();
return 0;
}
How can I resolve this to get actual profiling information using nvprof?
|
As per the documentation, there is currently no profiling support in CUDA for WSL. This is why there is no profiling data collected when you are using nvprof.
|
74,160,067
| 74,160,099
|
Lambda cannot be implicitly converted to std::function
|
I am attempting to create a wrapper around an std::function for reasons not explained here. I know that the following code works.
std::function<void()> function = [&]() -> void {};
The following is my wrapper around the std::function, however, it does not work when I try to construct it with a lambda.
template<typename Type, typename ...Args>
class custom_function {
public:
using function_type = std::function<Type(Args...)>;
custom_function(const function_type &other) {
function = other;
}
private:
function_type function;
};
// error: conversion from 'main()::<lambda()>' to non-scalar type 'custom_function<void>' requested
custom_function<void> function = [&]() -> void {
};
I thought that this would work since a lambda can be assigned to a std::function. If I add the following constructor, the code now compiles.
template<typename Type, typename ...Args>
class custom_function {
// ...
template<typename Lambda>
custom_function(const Lambda &other) {
function = other;
}
// ...
};
// this is now valid
custom_function<void> function = [&]() -> void {
};
Why does this constructor work but the previous constructor did not? Why is...
custom_function(const function_type &other) {
function = other;
}
different from...
template<typename Lambda>
custom_function(const Lambda &other) {
function = other;
}
I'm compiling with C++17 using G++ on Windows. Thanks
|
It's one too many implicit conversion steps. Generally speaking, C will let you get away with one level of indirection. So we could call a function that expects a double and pass it an int, and things will work fine, because there's an implicit conversion from double to int. Now let's look at your code.
custom_function(const function_type &other) {
function = other;
}
This is a converting constructor, which is just a fancy way of saying it's a constructor that takes one argument of some other type. When we write
custom_function<void> f = [&]() -> void {
};
This is a copy initialization. In principle, it's constructing something on the right hand side and then assigning it to the left. Since we don't explicitly call a constructor on the right hand side, we have to convert our lambda into custom_function<void>. We could do that if either
There was an conversion operator to custom_function<void> defined on the right hand type (which will never be the case here, since the right hand type is a lambda type), or
There was a converting constructor on custom_function<void> that takes a lambda as argument. This won't work here, since the only constructor takes a std::function. And we're already talking about a conversion, so we're not going to consider doing another conversion to get to std::function.
When you replace your constructor with a template function that can take any type, then that template function suffices as a valid conversion from the lambda type directly to your custom function type.
Note that you can also use brace initialization to directly call your constructor. This will work with either constructor.
custom_function<void> f { [&]() -> void {} };
That's because this is an actual explicit constructor call and therefore will consider implicit conversions to get from the argument type to the declared constructor parameter type.
See also this discussion on the different initialization techniques.
|
74,160,279
| 74,160,317
|
Comparing "Hello 4" to input in C++
|
I'm trying to use something like strcmp to compare a command like "Hello 4" and keep the 4 as a variable
Something like this:
if(strcmp(c, "Hello %d") == 0){
int num = %d;
}
|
You're looking for sscanf, which uses the scanf-style percent encoders you're using and takes a string to parse as its argument (as well as pointers to store the successful parses into).
It returns the number of arguments successfully stored, or a negative number in the case of an EOF error. In your case, we'll consider it a successful parse if we successfully store the one argument. If we get a zero, that's a failed parse, and if we get a negative number, that's a premature EOF, so we want the result of sscanf to be greater than zero.
#include <cstdio>
#include <iostream>
int main() {
const char* c = "Hello 100";
int num;
if (std::sscanf(c, "Hello %d", &num) > 0) {
std::cout << "Success! " << num << std::endl;
} else {
std::cout << "Failure..." << std::endl;
}
}
Note that in the else branch, the num variable won't be assigned, so it will have whatever value your code previously assigned to it (which, in the code sample I've shown here, is nothing at all, hence UB). So be careful not to reference that variable in the failure branch.
|
74,160,621
| 74,160,638
|
Multithreading in a for loop misses the first iteration
|
I am writing an application requiring a variable number of threads, which I would like to create within a vector over which I could iterate. The application consistently skips the first iteration of the for-loop but instead performs an unintended operation at the end of the loop. I would like not only to solve the issue but also to understand its origin.
Here is a toy example to recreate the behavior:
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
std::mutex my_mutex;
void print_func(int idx){
std::lock_guard<std::mutex> f(my_mutex);
std::cout << "Thread id: " << idx << std::endl;
}
int main() {
const auto processor_count = 4;
std::vector<std::thread> ThreadVector;
for(int i = 0; i < processor_count; i++){
ThreadVector.emplace_back([&](){print_func(i);});
}
for(auto& t: ThreadVector){
t.join();
}
return 0;
}
Here's the output:
Thread id: 1
Thread id: 2
Thread id: 3
Thread id: -214744752
Here's the intended behavior:
Thread id: 0
Thread id: 1
Thread id: 2
Thread id: 3
|
Your lambda:
[&](){print_func(i);}
captures the int i by reference, so when the thread started, i is no longer the same value, and for the last iteration, i goes out of scope, therefore it has garbage value from the stack.
Capturing by value instead of reference will solve your problem:
[i](){print_func(i);}
|
74,160,971
| 74,163,026
|
Declaring a variable and assigning with move assignment operator in one statement on Clang causes seg fault
|
I've got this trivial example of what I thought was calling the move assignment operator of this Test struct. Running it, it calls the move constructor and then seg faults on destruction on Clang. On MSVC, it works fine.
I'm a bit confused by that behavior cause i would expect it to construct with the parameterless constructor and then call the move assignment operator.
#include <iostream>
struct Test
{
Test() : data(nullptr), dataCount(0) {}
Test(Test&& other)
{
std::cout << "mv cstr" << std::endl << std::flush;
delete[] data;
data = other.data;
other.data = nullptr;
dataCount = other.dataCount;
}
Test& operator=(Test&& other)
{
std::cout << "mv op" << std::endl << std::flush;
delete[] data;
data = other.data;
other.data = nullptr;
dataCount = other.dataCount;
return *this;
}
~Test()
{
std::cout << "dstr " << (void*)this << std::endl << std::flush;
delete[] data;
data = nullptr;
}
char* data;
size_t dataCount;
};
int main() {
Test test;
test.data = new char[3];
test.dataCount = 3;
Test newTest = std::move(test);
return 0;
}
If I instead declare and then assign, it of course works as expected
int main() {
Test test;
test.data = new char[3];
test.dataCount = 3;
Test newTest;
newTest = std::move(test);
return 0;
}
I've read through the std::move, move assignment operator, and move constructor documentation a few times but I'm just not getting what's specifically different here or left up to the compilers that would give different behavior between MSVC and Clang.
What am I missing?
|
The move constructor is going to be called, because that is exactly what the code you wrote is designed to do:
Test newTest = std::move(test);
There is no move assignment happening here, since a new object, newTest, is being constructed from the value on the right side of the =.
Since your move constructor has a call to delete[] data; and data is not initialized, undefined behavior occurs.
i would expect it to construct with the parameterless constructor and
then call the move assignment operator.
If you think about this, this should not be expected. The compiler isn't going to take a circuitous route like this to construct the object, causing an unnecessary slow down.
What if the default constructor was "heavy", i.e. went through expensive operations to construct the object? The whole point of the move constructor is to not have to go through this step, and to simply "steal" the data from the object being moved from.
|
74,161,049
| 74,161,200
|
How to save excess user inputs? C++
|
As you know in C++ one is able to have variables assigned based on a user input via std::cin.
When using std::cin ,if I recall correctly, when there are too many inputs that what is required, then the extra inputs are ignored.
int main(){
int a, b;
std::cin >> a >> b;
std::cout << a << " " << b << endl;
return 0;
}
Input : 2 4 9 16 32
Output : 2 4
I am looking to still use the excess information from the user.How does one store the remaining inputs if one doesn't know the amount of excess inputs that the user will type?
|
answer:
The data stream is not lost, cin still holds the unused data stream.
explain
You can understand cin like this way, it has a stream of date, and each time cin was called, it would check the target variable type and pour (or consume) the date to fill the variable until success or read delimiters or use out the data.
For you above example, cin has "1 2 3 4", and tried to fill the integers a, and b. When it done, cin still holds the data "3 4". The information is not lost.
demo of full code
#include<iostream>
int main(){
int a, b, c, d;
std::cin >> a >> b;
std::cout << a << " " << b << endl;
std::cin >> c >> d;
std::cout << c << " " << d << endl;
return 0;
}
Compile and run:
g++ demo.cpp -Wall -o demo.out
./demo.out
Input and Ouput
1 2 3 4
1 2
3 4
P.S.
There are different ways of reading input for various purpos. i.e. while loop to into variables into a container, pour the input into a stream data structure, etc. For example, uses stringstreams family data structures.
details could be find in refences like: c++ basic io
|
74,161,145
| 74,161,316
|
storage of mipmaps in OpenGL
|
OpenGL version 450 introduces a new function which can be used to allocate memory for a texture2D:
glTextureStorage2D(textureObj,levels,internal_format,width,height);
//here, parameter 'levels' refers to the levels of mipmaps
//we need to set it 1 if we only want to use the original texture we loaded because then there is only one mipmap level
And, there is a function can help us generate mipmaps for a texture conveniently:
glGenerateTextureMipmap(textureObj);
So, I have a question: as I need to speciy the size of the storage when I use glTextureStorage2D, do I need to reserve extra space for later using of glGenerateTextureMipmap as mipmap requires extra memory?
I know that I can use glTexImage2D to avoid this problem, that I can first bind the texture to target GL_TEXTURE_2D, then copy the image's data to the texture's memory by using glTexImage2D which only asks me to give the target mipmap level instead of number of mipmap levels, and finally use glGenerateMipmap(GL_TEXTURE_2D).
I am a little confused about glGenerateMipmap. Will it allocate extra space for generated mipmap levels?
|
What do you mean by "reserve extra memory"? You told OpenGL how many mipmaps you wanted when you used glTextureStorage2D. When it comes to immutable storage, you don't get to renege. If you say a texture has width W, height H, and mipmap count L, then that's what that texture has. Forever.
As such, glGenerateTextureMipmaps will only generate data for the number of mipmaps you put into the texture (minus the base level).
|
74,161,794
| 74,161,879
|
Can a friend class object access the methods of the host class?
|
Suppose we have a class A:
class A{
int a_;
public:
friend class B;
A(int a):a_(a){}
int getA(){ return a_;}
void setA(int a){a_ = a;}
void print(int x){cout << x << endl;}
};
and another class B:
class B{
int b_;
public:
B(int b):b_(b){}
void setB(int b){b_ = b;}
int getB(){return b_;}
//friend void A::print(int x);
};
How to use a method of class A like print() using an object of class B?
//main.cpp
B b1(10);
b1.print(b1.getB());
|
How to use a method of class A like print() using an object of class B?
B isn't related to A in any way so you can't. The only thing you've done by adding a friend declaration is that you've allowed class B(or B's member functions) to access private parts of class A through an A object. Note the last part of the previous sentence. We still need an A object to be able to call A::print().
That is, friendship doesn't mean that you can directly(without any A object) access A's private members.
|
74,162,104
| 74,162,293
|
C Preprocessor Stringify enter\newline characters
|
So like many that have dealt with OpenGL Shaders in the past being able to write them without an extra program to convert them into a string has always been a want. So what I am looking for is a way to replace enter presses\newline characters in the source code with "\n" for example:
const char *sShaderSrc =
ConvertTextToString(
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
uniform mat4 mModel;
uniform mat3 mNormal;
uniform mat4 mViewProj;
varying vec3 vNormal;
void main()
{
gl_Position = (mViewProj *mModel) * vec4(aPos,1.0) ;
vNormal = mNormal*aNormal;
}
)
;
and then the preprocessor would convert it into
const char *sShaderSrc =
"#version 330 core\n\nlayout (location = 0) in vec3 aPos;\nlayout (location = 1) in vec3 aNormal;\n\nuniform mat4 mModel;\nuniform mat3 mNormal;\nuniform mat4 mViewProj;\n\nvarying vec3 vNormal;\n\nvoid main()\n{\n gl_Position = (mViewProj *mModel) * vec4(aPos,1.0);\n vNormal = mNormal*aNormal;\n}\n"
;
that way if OpenGL gives errors when compiling then I get shader line numbers in the error message.
Help would be much appreciated. The only edge case I could think of is also dealing with the case if the text editior inserts "\r\n" or "\n".
I have tried
#define RAWSTRINGIFY(x) R#x
//then you do
RAWSTRINGIFY((
//glsl code here...
))
but doesn't work the straight insertion
|
A Macro Solution (and why it doesn't work for your purpose)
This can be implemented as a variadic macro so that it actually compiles.
#define ConvertTextToString(...) #__VA_ARGS__
Unfortunately, there are two problems preventing this from being useful in the scenario.
It still doesn't preserve the newlines, as the newlines are not passed to the macro. Macro expansion is done after tokenization, which means that by the time a macro is expanded, all the newlines are already gone. See C++ preprocessor stringification that preserves newlines?
The #version 330 core is seen by the compiler as a preprocessor directive, which causes errors like this. There's no solution around this.
main.cpp:6:2: error: invalid preprocessing directive
#version 330 core
Using Raw String Literals
A solution to your intended use case (i.e. multiline string literals) is to use raw string literals in C++. For example,
const char* shaderSrc = R""""(
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
// ...
)"""";
|
74,162,633
| 74,168,316
|
Problem compiling from source OpenCV with MVSC2019 in 64 bit version
|
I was compiling openCV for windows with Qt using MSVC in the 2019 64 bit version.
At the time of launching the first configuration I get a bit list of errors like this:
Check size of size_t
CMake Error at C:/Program Files/CMake/share/cmake-3.25/Modules/CheckTypeSize.cmake:147 (try_compile):
Cannot copy output executable
''
to destination specified by COPY_FILE:
'C:/Users/alejandro/Downloads/opencv/build/CMakeFiles/CheckTypeSize/SIZEOF_SIZE_T.bin'
Recorded try_compile output location doesn't exist:
C:/Users/alejandro/Downloads/opencv/build/CMakeFiles/CMakeScratch/TryCompile-jglvcw/Debug/cmTC_e9d0b.exe
Call Stack (most recent call first):
C:/Program Files/CMake/share/cmake-3.25/Modules/CheckTypeSize.cmake:277 (__check_type_size_impl)
3rdparty/libjpeg-turbo/CMakeLists.txt:25 (check_type_size)
Does anyone know how can I solve this problem?
EDIT 1
I have seen that another importar error is this one related with OpenMP:
CMake Error at C:/Program Files/CMake/share/cmake-3.25/Modules/FindOpenMP.cmake:420 (try_compile):
Cannot copy output executable
''
to destination specified by COPY_FILE:
'C:/Users/alejandro/Downloads/opencv/build/CMakeFiles/FindOpenMP/ompver_C.bin'
Recorded try_compile output location doesn't exist:
C:/Users/alejandro/Downloads/opencv/build/CMakeFiles/CMakeScratch/TryCompile-q8quzk/Debug/cmTC_e2ecd.exe
Call Stack (most recent call first):
C:/Program Files/CMake/share/cmake-3.25/Modules/FindOpenMP.cmake:560 (_OPENMP_GET_SPEC_DATE)
C:/Program Files/CMake/share/cmake-3.25/Modules/FindBLAS.cmake:768 (find_package)
C:/Program Files/CMake/share/cmake-3.25/Modules/FindLAPACK.cmake:247 (find_package)
C:/Program Files/CMake/share/cmake-3.25/Modules/FindLAPACK.cmake:283 (_lapack_find_dependency)
cmake/OpenCVFindLAPACK.cmake:176 (find_package)
CMakeLists.txt:733 (include)
|
I had the same problem, it is the CMake-3.25.0-rc2 fault, change it to 3.24.2 and it will work.
|
74,162,863
| 74,162,900
|
Does std::string class handle clean up if the assignment operator fails due to length_error or bad_alloc?
|
Does std::string class handle clean up if the assignment operator fails due to length_error or bad_alloc? Does it give me back my intact string I provided?
UPDATE:
SOLVED: YES OPERATOR= IS SAFE PER MY REQUIREMENTS. THE CODE BELOW ADDS NO VALUE TO EXCEPTION SAFETY
given this reference from https://cplusplus.com/reference/string/string/operator=/ about exceptions
if the resulting string length would exceed the max_size, a length_error exception is thrown.
A bad_alloc exception is thrown if the function needs to allocate storage and fails.
The explanation below is assuming std::string class doesn't fix any assignment that was done.
I figured if I assigned *this ("num" below) to a temp I could save any damage done to *this if the line num = other.num; below failed. The reason I am not sure if this is futile is because this snippet num = temp;, The fact I do not check this for success could be a failure. Is my code futile? Is there a standard way to handle this that I am missing?
const BigInt
&BigInt::operator=(const BigInt &other)
{
string temp = num; // using string operator=
if (temp.compare(num) == 0)
{
try
{
num = other.num;
}
catch(...)
{
num = temp;
throw;
}
return *this;
}
return *this;
}
RESOURCES PER ANSWERS GIVEN:
string operator=
https://en.cppreference.com/w/cpp/string/basic_string/operator%3D
> If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11)
RAII Model https://en.cppreference.com/w/cpp/language/raii
|
Since C++11 it leaves the string intact.
If an exception is thrown for any reason, this function has no effect (strong exception guarantee).
(since C++11)
cppreference
|
74,163,013
| 74,166,829
|
ShellExecuteA cannot find file
|
I'm trying to open a file with a c++ program using ShellExecuteA in Windows10. (I'm also using VisualStudio2019 in case that's relevant.)
ShellExecute itself is working (I can use "explore" and "find" as it is intended), however it seems to be unable to find the file even though it exists in the directory. I have tried both an absolute as well as a relative path and neither work.
My code is this:
#include <iostream>
#include <windows.h>
#include <shellapi.h>
#include <string>
#include <limits.h>
using namespace std;
string getCurrentDir() {
char buff[MAX_PATH];
GetModuleFileName(NULL, buff, MAX_PATH);
string::size_type position = string(buff).find_last_of("\\/");
return string(buff).substr(0, position);
}
int main()
{
cout << "path: " << getCurrentDir() << endl;
int ret1 = (int)ShellExecuteA(NULL, "open", "C:\\Users\\Sasha\\source\\repos\\shellopen\\Debug\\MyTextFile.txt", NULL, NULL, SW_SHOWNORMAL);
cout << ret1 << endl;
int ret2 = (int)ShellExecuteA(NULL, "open", "MyTextFile.txt", NULL, NULL, SW_SHOWNORMAL);
cout << ret2 << endl;
return 0;
}
The result is
path: C:\Users\Sasha\source\repos\shellopen\Debug
2
2
"2" apparently means that the file couldn't be found, however "MyTextFile.txt" definitely exists in the directory and there is no spelling mistake.
I've tried googling the problem but it seems to be uncommon enough that I haven't found anything that works for me. I'd be very grateful for any help.
|
Ok, it turned out it was a spelling mistake, causing my file to be named "MyTextFile.txt.txt"
Thank you to everyone who tried to help me find the answer.
|
74,163,649
| 74,163,812
|
Does std::optional contain a value during construction?
|
Check out the following code for an example:
#include <iostream>
#include <optional>
class A {
public:
A();
~A();
};
std::optional<A> a;
A::A() { std::cout << a.has_value(); }
A::~A() { std::cout << a.has_value(); }
int main() {
a.emplace();
std::cout << a.has_value();
}
I ended up with something similar, and was caught by surprise that a had no value in the constructor. Which is probably a good thing since the object isn't fully constructed and my design could be improved. But I didn't find any evidence in cppreference about the way it's supposed to behave according to the standard.
So my question is (mainly due to curiosity): What should be the output in the example code above, and is it specified or implementation-defined (or UB)?
Interestingly, the above code prints (spoiler):
010 for GCC and Cland, and 011 for MSVC.
|
As far as I can tell, the current draft of the standard (as provided by https://timsong-cpp.github.io/cppwp/) is not explicit, but the MSVC behaviour is for me the specified one (whever it is the desirable one during destruction is dubious):
First emplace contains the following text
Effects: Calls *this = nullopt. Then direct-non-list-initializes the contained value with std::forward(args)....
...
Remarks: If an exception is thrown during the call to T's constructor, *this does not contain a value, and the previous *val (if any) has been destroyed.
It would be a perverse reading to set has_value to false as per the nullopt assignation, then true during the construction (when that action is not specified) and finally reset it if the construction fails with an exception.
The behaviour during the destruction is this one:
Effects: If is_trivially_destructible_v != true and *this contains a value, calls val->T::~T()
There is no mention of changes of has_value, if one was desired specifying it would be in order.
|
74,163,821
| 74,163,973
|
Qt: QDesktopWidget file not found
|
So I'm trying to use this class just to resize a window and its the main class I found to get the geometry of a users screen. I couldn't find many others with this problem besides adding :
QT += widgets in my .pro file and running qmake.
Unfortunately this did not work, if anyone has any advice Thankyou!
|
From the Qt documentation:
QDesktopWidget was already deprecated in Qt 5, and has been removed in Qt 6, together with QApplication::desktop().
QScreen provides equivalent functionality to query for information about available screens, screen that form a virtual desktop, and screen geometries.
|
74,164,180
| 74,164,830
|
c++ constexpr typed as nested class
|
This works: (A)
class Foo {
public:
const bool b;
constexpr ~Foo() = default;
constexpr Foo(const bool b) : b(b) {};
};
class Bar {
public:
static constexpr Foo tru { true };//Foo is complete type
};
This fails to compile: (B)
class Bar {
public:
class Foo {
public:
const bool b;
constexpr ~Foo() = default;
constexpr Foo(const bool b) : b(b) {};
};
static constexpr Foo tru { true };//undefined constructor 'Foo' cannot be used
};
error:
$ clang++ --std=c++20 -D_POSIX_C_SOURCE=200112L -fPIC -g -Werror -Wall LiteralStruct.cpp -o LiteralStruct
LiteralStruct.cpp:9:24: error: constexpr variable 'tru' must be initialized by a constant expression
static constexpr Foo tru { true };
^~~~~~~~~~~~
LiteralStruct.cpp:9:24: note: undefined constructor 'Foo' cannot be used in a constant expression
LiteralStruct.cpp:7:15: note: declared here
constexpr Foo(const bool b) : b(b) {};
^
1 error generated.
This also fails to compile, but gives a good reason: (C)
class Foo {
public:
const bool b;
constexpr ~Foo() = default;
constexpr Foo(const bool b) : b(b) {};
static constexpr Foo tru { true };//Foo is NOT a complete type
};
error:
$ clang++ --std=c++20 -D_POSIX_C_SOURCE=200112L -fPIC -g -Werror -Wall LiteralStruct.cpp -o LiteralStruct
LiteralStruct.cpp:6:24: error: constexpr variable cannot have non-literal type 'const Foo'
static constexpr Foo tru { true };
^
LiteralStruct.cpp:6:24: note: incomplete type 'const Foo' is not a literal type
LiteralStruct.cpp:1:7: note: definition of 'Foo' is not complete until the closing '}'
class Foo {
version:
clang version 10.0.0-4ubuntu1
Target: x86_64-pc-linux-gnu
C failing makes sense and has a good error message. B feels like it should work, Foo and all it's contents should be complete and defined at that point in the file. Basically my question is: do I report a clang bug that B should work, or a feature request for a better error message? If Foo is truly not complete by virtue of being a member of an incomplete type, then I should think the error message should be similar to that of C.
Edit:
I just upgraded clang to the bleeding edge (16.0.0-++20221021052626+7dd2f4bc009d-1~exp1~20221021172738.418) and got the same result.
|
The problem with (B) is distinct from the one with (C). In (B) the completeness of Foo is not in question. Foo is complete as soon as the closing } of its definition is reached and since the member declaration of tru is placed after that, Foo is complete for its purpose.
There is also no problem in (B) with Bar being incomplete at the declaration of tru. While that's true, incompleteness does not prevent looking up members which were declared prior, like the nested class Foo.
The problem is, as the error message is pointing out, whether or not the constructor Foo::Foo(bool) is defined at the point of the declaration of tru. This is an important question, because tru is initialized in that declaration using the constructor in question and it is marked constexpr, requiring that the initialization be a constant expression. Calling a (constexpr) function in a constant expression is only allowed if the function is defined (not only declared) prior to the expression.
Consider for example
class Bar {
public:
class Foo {
public:
const bool b;
constexpr ~Foo() = default;
constexpr Foo(const bool b);
};
static constexpr Foo tru { true };
};
constexpr Bar::Foo::Foo(const bool b) : b(b) {};
You will get the same or a similar error message here. In this case it is more obvious what the issue is. When static constexpr Foo tru { true }; is reached and the compiler tries to evaluate the (compile-time constant) value of Foo, it hasn't seen the definition of the constructor yet, so it can't know how to determine the value of tru.
Now in your example (B) it seems that Bar::Foo::Foo(bool) is defined before it is used in the constant expression for tru and I think if one follows the current standard by exact wording, then this is true. However, there is a complication which changes this in practice and in the probable intent of the standard:
The body of a function defined inside a class is special in that it is a so-called complete-class context. In such a context it is possible for name lookup to find not only preceding declarations as is normally the case in C++, but also declarations for all members of the class (and enclosing classes), irregardless of whether they are declared only later.
So for example the following is allowed:
class Bar {
public:
class Foo {
public:
const bool b;
~Foo() = default;
Foo(const bool b) : b(X) {};
};
constexpr static bool X = false;
};
Although X is not declared yet when Foo::Foo(bool) is defined and uses X, the compiler has to accept it and figure out that X is the static member declared at the end.
In order to achieve this lookup behavior, the compiler practically must rewrite the code to
class Bar {
public:
class Foo {
public:
const bool b;
~Foo() = default;
Foo(const bool b);
};
constexpr static bool X = false;
};
inline Bar::Foo(const bool b) : b(X) {};
Now "normal" lookup rules can find X as expected.
But if we apply this rewriting to your example (B) we get my first example in this answer and as we determined it cannot work with the constant expression evaluation. So in practice you can't use a member function of the same class (including nested or enclosing classes) in a constant expression evaluation for a static data member inside the class definition itself.
That the current standard wording doesn't describe this behavior properly is an issue with the standard, not the compiler. My impression is that Clang is implementing it as intended. While it may sometimes be possible to consider the constructor defined where it is lexically placed for the purpose of constant expression evaluation if e.g. all names used in its definition can already be found at that point, in general it is impossible, because you could create infinite recursive type dependencies this way.
|
74,165,235
| 74,165,268
|
Is it possible to use a macro defined value in C/C++?
|
In the LLVM codebase, I see this lines:
class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject,
public ilist_node<Function> {
My LSP (clangd) tells me that LLVM_EXTERNAL_VISIBILITY refers to
/// LLVM_LIBRARY_VISIBILITY - If a class marked with this attribute is linked
/// into a shared library, then the class should be private to the library and
/// not accessible from outside it. Can also be used to mark variables and
/// functions, making them private to any shared library they are linked into.
/// On PE/COFF targets, library visibility is the default, so this isn't needed.
///
/// LLVM_EXTERNAL_VISIBILITY - classes, functions, and variables marked with
/// this attribute will be made public and visible outside of any shared library
/// they are linked in to.
#if __has_attribute(visibility) && \
(!(defined(_WIN32) || defined(__CYGWIN__)) || \
(defined(__MINGW32__) && defined(__clang__)))
#define LLVM_LIBRARY_VISIBILITY __attribute__ ((visibility("hidden")))
#if defined(LLVM_BUILD_LLVM_DYLIB) || defined(LLVM_BUILD_SHARED_LIBS)
#define LLVM_EXTERNAL_VISIBILITY __attribute__((visibility("default")))
#else
#define LLVM_EXTERNAL_VISIBILITY // <-------------- THIS
#endif
#else
#define LLVM_LIBRARY_VISIBILITY
#define LLVM_EXTERNAL_VISIBILITY
#endif
I can't figure out the usefulness: why should I #define an identifier without a value, but using that as if it had one?
One idea is that it acts as a conditional: if something happens, then the preprocessor substitutes some text; if not, it simply doesn't substitute anything, but prevents the compiler from complaining about some undefined LLVM_LIBRARY_VISIBILITY token. Is this correct?
Moreover, what kind of attributes can be specified there? Something about the linkage of the class?
Thanks!
|
One idea is that it acts as a conditional: if something happens, then the preprocessor substitutes some text; if not, it simply doesn't substitute anything, but prevents the compiler from complaining about some undefined LLVM_LIBRARY_VISIBILITY token. Is this correct?
Pretty much. Some build environments, it'll have a value. Others not. Seems mainly a matter of portability.
__attribute__((visibility("default"))) refers to the visibility of the symbol it is attached to. The default visibility can be changed at compile time.
|
74,165,292
| 74,529,850
|
How to compute the mel spectrogram on STM32?
|
I'm working with a STM32F4Discovery board, and I'm trying to run a neural network on it for sound classification.
I want to create the mel spectrogram directly on board from the sound recorded from the built-in microphone, which I already converted to PCM, and than give it as input to my neural network (trained with tensorflow, and generated with STM Cube AI).
The network's input is an image of 30x30x1.
Is there a C/C++ library that can I use to implement it?
I've tried LibrosaCpp but it crash when calling Eigen functions.
|
It is possible to compute the mel spectrogram on STM32 boards by using CMSIS DSP Library provided by ARM alongside with the STM32_AI_AudioPreprocessing_Library included in the FP-AI-Sensing package.
In the FP-AI-Sensing library there is also an example for the mel spectrogram computation.
|
74,166,718
| 74,171,436
|
thread::detach during concurrent thread::join in C++
|
In the following program, during one thread (main) is performing thread::join, another thread (x) calls thread::detach:
#include <thread>
#include <iostream>
int main(void) {
auto t = std::thread([] {
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
} );
auto x = std::thread([&t] {
std::this_thread::sleep_for( std::chrono::milliseconds(500) );
if ( t.joinable() )
{
std::cout << "detaching t..." << std::endl;
t.detach();
}
} );
std::cout << "joining t..." << std::endl;
t.join();
x.join();
std::cout << "Ok" << std::endl;
return 0;
}
It work fine in GCC's libstdc++ and Clang's libc++ printing
joining t...
detaching t...
Ok
but in Visual Studio the program terminates with not-zero exit code before printing Ok. Online demo: https://gcc.godbolt.org/z/v1nEfaP7a
Is it a bug in Visual Studio or the program contains some undefined behavior?
|
Neither join nor detach are const-qualified and therefore the implementation is allowed to modify internal memory of the thread object without having to provide any guarantees of write/write or write/read data race avoidance on unsynchronized calls to these member functions per the default data race avoidance requirements of [res.on.data.races].
There is also no exception to this rule mentioned in [thread.threads] or anywhere else for these functions.
Therefore calling join and detach without establishing a happens-before relation between the two calls is a data race and causes undefined behavior.
Even without the detach call, there is still a write/read data race on the join/joinable pair of calls.
|
74,166,778
| 74,172,649
|
Can relaxed stores be reordered before a compare_exchange across the loop iterations?
|
Consider the following code.
#include <atomic>
#include <cassert>
#include <thread>
struct foo {
std::atomic<foo*> _next = nullptr;
};
foo dummy = {};
foo a = {};
std::atomic<foo*> b = nullptr;
void thread_0() {
auto* old = b.load(std::memory_order_acquire); // (1)
do {
a._next.store(old, std::memory_order_relaxed); // First iteration: (2), Second iteration: (4)
} while (!b.compare_exchange_weak(old, &a, std::memory_order_release, std::memory_order_relaxed)); // First iteration: (3), Second iteration: (5)
}
void thread_1() {
// plain store is enough for the demonstration here,
// but then the code may hang indefinitely when it is actually executed.
// Just think this is a plain store in this example.
const auto* avoid_hang = b.exchange(&dummy, std::memory_order_relaxed); // (6)
if (avoid_hang) { return; }
while (b.load(std::memory_order_acquire) != &a) {}; // (7)
assert(a._next.load(std::memory_order_relaxed)); // Can this assert fire?
}
/*
void thread_1_ignore_hang() {
b.store(&dummy, std::memory_order_relaxed); // (6)
while (b.load(std::memory_order_acquire) != &a) {}; // (7)
assert(a._next.load(std::memory_order_relaxed)); // Can this assert fire?
}
*/
int main() {
std::jthread t0(thread_0);
std::jthread t1(thread_1);
return 0;
}
And the following order of execution.
Thread 0 Thread 1
(1) old = nullptr(load b, mo_acquire)
(2) a->_next = nullptr (6) b = &dummy
(3) cmpxchg fails, old = &dummy (load b, mo_relaxed)
(4) a->_next = &dummy
(5) cmpxchg succeeds, b = &a (load b, mo_relaxed, store to b, mo_release)
(7) (load b, mo_acquire)
AFAIK, std::memory_order_release store (introduced by compare_exchange_weak) only prevent reads/writes before it from being reordered after it.
Then, in Thread 1's view, could (4) be reordered before (2) and read a._next as nullptr and make the assert fire?
I can't really test this with my hardware because on x86 all atomic loads/stores will have std::memory_order_acquire/std::memory_order_release memory ordering, respectively.
|
I think two separate questions are being conflated here.
First, to answer the title question, loops are irrelevant to memory ordering. All that matters is program order - "sequencing" in the language of the C++ standard. You will not find any mention of looping in the memory model sections of the standard. And at the level of the machine, for purposes of memory ordering, CPUs don't care what non-memory instructions are executed between two memory accesses; in particular they don't care if one of them is a branch.
That means that, in your example, (4) can be reordered before (3).
But it does not mean that (4) can be reordered before (2); this is not allowed. It is nothing to do with acquire/release ordering; it is simply the fact that every atomic variable has a modification order [intro.races p4], which must be consistent with the happens-before ordering. This is the write-write coherence rule [intro.races p15].
In particular, it must be consistent with sequencing. Since (2) is unquestionably sequenced before (4), the value nullptr must precede &dummy in the modification order of a._next.
Now the load in the assert (call it (8)) is sequenced after the acquire load (7), which takes its value &a from the release store (5), which is sequenced after the store (4). So store (4) happens before load (8). By write-read coherence [intro.races p18], load (8) must not return any value that precedes, in the modification order, the value stored by (4), namely &dummy. So load (8) cannot return nullptr, and the assert cannot fire.
In short, weak memory ordering only affects how loads and stores of different objects can be reordered. But two stores to the same object can never be reordered with each other.
For some intuition about this rule, think back to the reason we have memory reordering in the first place: a memory access can take a long time, and we'd like to go on and do more useful work while we're waiting for it to finish. So if you have
a.store(5, std::memory_order_relaxed);
b.store(10, std::memory_order_relaxed);
and the store to a is stalled, we might as well just put it in a store buffer and move on. If we're able to access b more quickly, then a weakly-ordered architecture will go ahead and do the store to b while a is still waiting.
But if instead we have
a.store(5, std::memory_order_relaxed);
// more code
a.store(10, std::memory_order_relaxed);
and if the first store is still waiting by the time we get to the second store, the correct thing to do is to replace it in the store buffer by the second store. There's no guarantee that any other core would have happened to load a while it had the value 5 anyway, so we might as well not do the first store at all. But the store of 10 can't possibly be ready to commit before the store of 5, because they are both waiting for the same cache line to become available. And so even if the memory ordering rules allowed the two stores to be reordered, it would provide no benefit in efficiency, while being very confusing and making it hard to write correct code without sprinkling barriers everywhere.
|
74,167,516
| 74,168,032
|
How to create a template that can use different arguments from the same base class
|
I'm trying to create a Threshold template class that allows me to compare numeric values against a threshold value. I want to easily change the comparison function to use greater_equal or less_equal so I create the following template:
template<typename T, typename comp_func = std::greater_equal<T>, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
class Threshold
{
public:
Threshold(T threasholdValue) : _thresholdValue(threasholdValue) {}
~Threshold() = default;
bool isExceeded(T value) const
{
return comp_func{}(value, _thresholdValue);
}
private:
T _thresholdValue;
};
I want to be able to pass instances of this class to a function that accepts the Threshold:
template<typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
void foo(Threshold<T>& threshold)
{
. . .
}
This works fine as long as I use the default comparison function (std::greater_equal) but when I try to create a Threashold with "std::less_equal", this becomes a different type and I cannot pass it into foo:
Threshold<int32_t> greaterEqThreshold(5);
Threshold<int32_t, std::less_equal<int32_t>> lessEqThreshold(10);
foo(greaterEqThreshold);
foo(lessEqThreshold); <--- Compile Error!
I understand why this is happening but I can't figure out how to solve the problem, other by creating a pure virtual class and having Threshold inherit from it and then using reference to that class. However, this solutions seems a little long winded for what I want do do.
Is there a way to make this work? Is there a better way to do this?
Edit
std::less_equal and std::greater_equal both inherit from std::binary_function (hence the title of my question), so I tried this:
template<typename T, typename _Compare_func = std::less_equal<T>, typename std::enable_if<std::is_arithmetic<T>::value || std::is_same<std::binary_function<T, T, bool>, _Compare_func>::value>::type* = nullptr>
class Threshold
{
public:
...
};
but that didn't seem to make a difference.
|
You specifically declared foo as a function that only takes a Threshold<T>, i.e. an instance of a template where the comparator is the default. Just include both template arguments in your definition:
template<typename T, typename comp_func,
typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
void foo(Threshold<T, comp_func>& threshold)
{
// . . .
}
|
74,168,266
| 74,168,267
|
std::format pointer error C3615: consteval function 'std::_Compile_time_parse_format_specs' cannot result in a constant expression
|
How to fix (stdC++20 mode VS2022)
#include <format>
#include <string>
auto dump(int *p)
{
std::string resultstring = std::format(" p points to address {:p}", p);
resulting in:
error C3615: consteval function 'std::_Compile_time_parse_format_specs' cannot result in a constant expression
|
Cast the pointer to void like this:
std::string resultstring = std::format("{:p}", (void *)p);
The problem is not with the format string itself, but rather that the templated type checking on the variable arguments FAILS for any non-void pointer types, generally with a confusing error in the header .
|
74,168,405
| 74,168,493
|
understanding std::is_base_of possible implementation from cppreference
|
Here we have is_base_of template implementation taken from cppreference.com:
namespace details {
template <typename B>
std::true_type test_pre_ptr_convertible(const B*); //1
template <typename>
std::false_type test_pre_ptr_convertible(const void*); //2
template <typename, typename>
auto test_pre_is_base_of(...)->std::true_type; //3
template <typename B, typename D>
auto test_pre_is_base_of(int) ->
decltype(test_pre_ptr_convertible<B>(static_cast<D*>(nullptr)));
}
template <typename Base, typename Derived>
struct is_base_of :
std::integral_constant<
bool,
std::is_class<Base>::value&& std::is_class<Derived>::value&&
decltype(details::test_pre_is_base_of<Base, Derived>(0))::value
> { };
And some private inheritance:
class A {};
class B : A {};
is_base_of<A,B>::value gives true and declaration no. 3 is the best match. Declaration no. 1 fails as a candidate(was passed a pointer to object of private subclass) and declaration no. 2 is ignored. But Why? Isn't void* a good match for every pointer type? If declaration no. 3 was not provided the code wouldn't compile. My question is why declaration no. 3 needs to be provided for this code to compile successfully? Why declarations no. 1 and no. 2 aren't sufficient?
|
Overload resolution ignores accessibility for the purpose of deciding which candidates are viable and for choosing the best candidate.
If D is a derived class of B (irregardless of accessibility), then //1 is always viable and a better candidate for overload resolution than //2 (which is also viable) and overload resolution will choose the former.
If //1 is chosen as best candidate and B is not a public base of D, then the required implicit conversion on the argument will however fail because B is not an accessible base. But that is already after overload resolution was done. There will be no attempt to then fall back to the "second best" overload //2.
Since the call to test_pre_ptr_convertible is therefore invalid, the whole program would normally be ill-formed. However, the call here is in the return type of a function template and so SFINAE applies, meaning that the overload
template <typename B, typename D>
auto test_pre_is_base_of(int) ->
decltype(test_pre_ptr_convertible<B>(static_cast<D*>(nullptr)));
is simply not viable for the call from is_base_of and the only other remaining overload for test_pre_is_base_of is //3, which is then chosen.
|
74,168,488
| 74,168,543
|
Difference between const method and method with const attributes
|
What is the difference between const at the beginning:
const int MyClass::showName(string id){
...
}
And :
int MyClass::showName(const string id) {
...
}
And :
int MyClass::showName(string id) const{
...
}
|
const modifies the thing it's next to, like a word like "little". "A little yard with a shed" is different from "a yard with a little shed". Let's look at your code examples:
const int MyClass::showName(string id) {
The returned integer is const. This has no effect because the caller receives a copy and had no ability to modify the original anyways.
int MyClass::showName(const string id) {
The variable id is const. This means that code in showName() like id += "foo"; will be a syntax error because you aren't allowed to modify id.
int MyClass::showName(string id) const {
The method showName() is const. Suppose you have member variables of your class, for instance
class MyClass {
int something;
int showName(string id) const;
}
We call showName() a const member function, meaning modifying other parts of the object isn't allowed inside showName(). Writing code in showName() like something = 1; is a syntax error because it tries to modify a member of MyClass.
|
74,168,490
| 74,168,563
|
How to correctly implement producer consumer problem
|
I tried to implement producer consumer problem in C++, but I found that my implementation has a problem that it will produce until the size reaches the capacity and then start the consume process. I wonder what's the problem with my implementation.
#include <iostream>
#include <mutex>
#include <thread>
#include <queue>
#include <chrono>
using namespace std;
std::mutex mtx;
condition_variable cv;
queue<int> q;
int n=2;
int produceData() {
int res=rand()%1000;
cout<<"produce data:"<<res<<endl;
return res;
}
void consumeData() {
cout<<"consume data:"<<q.front()<<endl;
}
void producer(){
while(true) {
unique_lock<mutex> lk(mtx);
cv.wait(lk,[&](){return q.size()<n;});
q.push(produceData());
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void consumer() {
while(true) {
unique_lock<mutex> lk(mtx);
cv.wait(lk,[&](){return q.size()>0;});
consumeData();
q.pop();
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
|
You need to unlock the mutex while you sleep. Just introducing a new block (curly braces) is all you need to do. Such that the unique_lock destructor will run before the sleep call. You could also manually invoke lk.unlock before the sleep call.
Instead of this:
void producer(){
while(true) {
unique_lock<mutex> lk(mtx);
cv.wait(lk,[&](){return q.size()<n;});
q.push(produceData());
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
this:
void producer(){
while(true) {
{
unique_lock<mutex> lk(mtx);
cv.wait(lk,[&](){return q.size()<n;});
q.push(produceData());
cv.notify_one();
} // mutex will implicitly unlock on this line as a result of the destructor for lk
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
Make a similar change in the consumer function as well.
|
74,168,788
| 74,169,014
|
how to check repetition of a certain number of zeroes following by an equal number of ones in a string?
|
If user enters a string, i want to make a function to check if a repetition of a certain number of zeroes follows an equal number of ones. Example: 001101 (correct), 01(correct),001010 (incorrect).
I've tried to store the string in 2 separate strings and compare the size but my 2nd while loop isn't stopping.
void check(string num) {
string st0 = "", st1 = "";
int n = num.length();
int k = 0;
while (k < n) {
int i = 0;
while (num[i] == num[i+1]) {
st0.push_back(num.back());
num.pop_back();
k++;
i++;
}
st0.push_back(num.back());
num.pop_back();
k++;
int j = 0;
while (num[j] == num[j+1]) {
st1.push_back(num.back());
num.pop_back();
k++;
j++;
}
st1.push_back(num.back());
num.pop_back();
k++;
if (st0.size() != st1.size()) {
cout << "incorrect \n";
}
st0.clear();
st1.clear();
}
}
|
Here you are testing the elements from left to right and you're adding to st0 the last elements from num string. For example:
"111010": after the first while num = "111" and st0 = "010"
while (num[i] == num[i+1]) {
st0.push_back(num.back());
num.pop_back();
k++;
i++;
}
And to fix you should add the first element tested not the last.
while( num[i] == num[i+1] && i+1 < n ){
st0.push_back(num[i]);
i++;
}
st0.push_back(num[i]);
i++;
You did the same mistake here
while (num[j] == num[j+1]) {
st1.push_back(num.back());
num.pop_back();
k++;
j++;
}
Fix:
while( num[i] == num[i+1] && i+1 < n){
st1.push_back(num[i]); // same here
i++;
}
st1.push_back(num[i]);
i++;
I used the same i here so that we continue looping the string from where we left off in the first while.
But there is a more optimized solution if you're interested:
void check(string num)
{
int cnt0 = 0 , cnt1 = 0;
int n = num.length();
int i=0;
bool test = true ;
while (i<n){
/* we can use two variables and increment them instead of strings and compare them cauz we are not using the elements we just need the size of them */
while( num[i] == num[i+1] && i+1 < n ){
cnt0++ ;
i++;
}
cnt0++;
i++;
while( num[i] == num[i+1] && i+1 < n) {
cnt1++;
i++;
}
cnt1++;
i++ ;
if ( cnt1 != cnt0 ){
test = false ;
break;
}
cnt1 = 0;
cnt0 = 0;
}
if( test ) {
cout << "correct \n" ;
}
else {
cout << "incorrect \n" ;
}
}
In the above algorithm, as you can see, you only need the length of the string st0 and st1 so you could just use 2 int variables and test the difference between the two, this way is more memory efficient as well as slightly faster run times.
|
74,168,804
| 74,168,823
|
Password requirements
|
I'm trying to declare this string as Invalid but in an input like this:
59G71341 or 8pjf7h14sx13 or 60s1v344
My output is getting approved through my string if statement and is getting listed as Valid.
Could anyone guide me to why its passing through my if statement and labeling Valid!!
I haven't learned how to use a debugger yet so bare with me.
Task description:
Declare a Boolean variable named goodPasswd. Use goodPasswd to output "Valid" if secretStr contains no more than 5 digits and secretStr's length is greater than or equal to 5, and "Invalid" otherwise.
Ex: If the input is 80796, then the output is:
Valid
Ex: If the input is XBdg, then the output is:
Invalid
#include <iostream>
using namespace std;
int main()
{
string secretStr;
bool goodPasswd = false;
cin >> secretStr;
int counter = 0;
for (int i = 0; i < secretStr.length(); ++i)
{
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
{
++counter;
}
} //approves string if both true
if ((counter <= 5) && (secretStr.length() >= 5))
{
goodPasswd = true;
}
else
{
goodPasswd = false;
}
if (goodPasswd)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
return 0;
}
|
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
should be
if ((secretStr[i] >= '0') && (secretStr[i] <= '9'))
0 and 9 are integers, but you are comparing characters, so you need to use the characters '0' and '9', or you could just use the isdigit function.
if (isdigit(secretStr[i]))
isdigit is declared in #include <cctype>
Not related to your question but you don't need to goodPasswd variable. Simply
if (counter <= 5 && secretStr.length() >= 5)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
seems a bit cleaner to me.
|
74,169,044
| 74,170,790
|
Cant Overflow The Buffer For Shell Coding
|
I have this shell code which is suppose to open a MessageBox. It works when testing it with https://github.com/NytroRST/ShellcodeCompiler, however when I create a new console application using c and try to compile this
#include <stdio.h>
#include <Windows.h>
unsigned char rc[] = "\x31\xC3\x89\x64\xE2\x80\xB9\x41\x30\xE2\x80\xB9\x40\x0C\xE2\x80\xB9\x70\x14\xC2\xAD\xE2\x80\x93\xC2\xAD\xE2\x80\xB9\x58\x10\xE2\x80\xB9\x53\x3C\x01\xC3\x9A\xE2\x80\xB9\x52\x78\x01\xC3\x9A\xE2\x80\xB9\x72\x20\x01\xC3\x9E\x31\xC3\x89\x41\xC2\xAD\x01\xC3\x98\xC2\x81\x38\x47\x65\x74\x50\x75\xC3\xB4\xC2\x81\x78\x04\x72\x6F\x63\x41\x75\xC3\xAB\xC2\x81\x78\x08\x64\x64\x72\x65\x75\xC3\xA2\xE2\x80\xB9\x72\x24\x01\xC3\x9E\x66\xE2\x80\xB9\x0C\x4E\x49\xE2\x80\xB9\x72\x1C\x01\xC3\x9E\xE2\x80\xB9\x14\xC5\xBD\x01\xC3\x9A\x31\xC3\x89\x53\x52\x51\x68\x61\x72\x79\x41\x68\x4C\x69\x62\x72\x68\x4C\x6F\x61\x64\x54\x53\xC3\xBF\xC3\x92\x92\xC3\x84\x0C\x59\x50\x31\xC3\x80\x66\xC2\xB8\x6C\x6C\x50\x68\x33\x32\x2E\x64\x68\x75\x73\x65\x72\x54\xC3\xBF\x54\x24\x10\xC6\x92\xC3\x84\x0C\x50\x31\xC3\x80\xC2\xB8\x6F\x78\x41\x23\x50\xC6\x92\x6C\x24\x03\x23\x68\x61\x67\x65\x42\x68\x4D\x65\x73\x73\x54\xC3\xBF\x74\x24\x10\xC3\xBF\x54\x24\x1C\xC6\x92\xC3\x84\x0C\x50\x31\xC3\x80\xC2\xB8\x65\x73\x73\x23\x50\xC6\x92\x6C\x24\x03\x23\x68\x50\x72\x6F\x63\x68\x45\x78\x69\x74\x54\xC3\xBF\x74\x24\x20\xC3\xBF\x54\x24\x20\xC6\x92\xC3\x84\x0C\x50\x31\xC3\x80\xC2\xB8\x59\x6F\x75\x23\x50\xC6\x92\x6C\x24\x03\x23\x68\x41\x72\x65\x20\x68\x48\x6F\x77\x20\x68\x48\x65\x79\x20\x54\x31\xC3\x80\x50\x68\x54\x65\x73\x74\x54\x31\xC3\x80\x50\xC3\xBF\x74\x24\x04\xC3\xBF\x74\x24\x14\x31\xC3\x80\x50\xC3\xBF\x54\x24\x34\x92\xC3\x84\x20\x31\xC3\x80\x50\xC3\xBF\x54\x24\x04\x6e";
int main() {
(*(void(*)()) rc)();
}
It always throws an Access Violation Exception after running it, I can get rid of this exception if I change the memory protections at the location of the shell codes injection. But yet it still does not display the MessageBox. I am certain the shell code works because the link above has a program that tests the shellcode and it works flawlessly. Only difference between their exploitation approach is that they are using c++ to do it and im using c.
|
Use VirtualProtect,
DWORD oldProt = 0;
VirtualProtect(rc, sizeof(rc), PAGE_EXECUTE_READWRITE, &oldProt);
|
74,169,189
| 74,169,259
|
Difference in finding a number inside an unordered_map in C++ STL
|
In the case of unordered_map in C++, what is the main difference between:
if(map.find(n) != map.end())
if(map.count(n) > 0)
if(map[n] > 0)
Consider map is an unordered_map of type <int,int>.
|
These lines:
if(map.find(n) != map.end())
if(map.count(n) > 0)
Are mostly equivalent. map::count will never return more than 1.
This line:
if(map[n] > 0)
Loads the value associated with the key, n and compares if it's value is greater than zero. Not the same thing as the first two. map[n] also has a side effect. If n is not already a key in the map, the map will create a new value ("default initialized" or "zero-init" value) for that key. Hence, it can increase the size of the map implicitly.
|
74,169,243
| 74,169,553
|
unwanted implicit cast makes overload ambiguous
|
Consider the following code sample:
void my_print(bool is_red, const char* format, ...){
va_list args;
va_start(args, format);
if(is_red)
print_red(format, args);
else
print_normal(format, args);
va_end(args);
}
void my_print(const char* format, ...){
va_list args;
va_start(args, format);
print_normal(format, args);
va_end(args);
}
int main() {
my_print((const char*)"Hello %s\n", "World");
return 42;
}
This code is ambiguous to the compiler and it yields the error:
more than one instance of overloaded function "my_print" matches the argument list:
function "my_print(bool is_red, const char *format, ...)" (declared at line 12)
function "my_print(const char *format, ...)" (declared at line 22)
argument types are: (const char *, const char [6])
From what I understand the parameters I passed can interpreted as either (const char*, ...) where the '...' is just 'const char*' or (bool, const char*, ...) where the '...' is empty.
I would expect the compiler to assume I want to call the one which does not require an implicit cast from 'bool' to 'const char*' (which I do), and hence call the second instance.
How can I clarify this ambiguity to the compiler without changing the syntax of the function call?
|
You could rename both overloads of my_print to functions named differently and introduce a template names my_print instead, which allows you to add a check, if the type of the first parameter is char const* in an if constexpr to resolve the ambiguity.
void print_red(char const* format, va_list lst)
{
printf("red :");
vprintf(format, lst);
}
void print_normal(char const* format, va_list lst)
{
printf("normal :");
vprintf(format, lst);
}
void my_print_with_color_impl(bool is_red, const char* format, ...) {
va_list args;
va_start(args, format);
if (is_red)
print_red(format, args);
else
print_normal(format, args);
va_end(args);
}
void my_print_impl(const char* format, ...) {
va_list args;
va_start(args, format);
print_normal(format, args);
va_end(args);
}
template<class T, class ... Args>
void my_print(T first, Args ... args)
{
if constexpr (std::is_same_v<std::decay_t<T>, char const*>)
{
my_print_impl(first, args...);
}
else
{
my_print_with_color_impl(first, args...);
}
}
int main() {
my_print("Hello %s\n", "World");
return 42;
}
Alternatively pre C++17 you could create a template class for printing and partially specialize it based on the first parameter:
template<class T, class...Args>
struct Printer
{
void operator()(bool is_red, char const* format, ...) const
{
va_list args;
va_start(args, format);
if (is_red)
print_red(format, args);
else
print_normal(format, args);
va_end(args);
}
};
template<class...Args>
struct Printer<char const*, Args...>
{
void operator()(char const* format, ...) const
{
va_list args;
va_start(args, format);
print_normal(format, args);
va_end(args);
}
};
template<class T, class ... Args>
void my_print(T first, Args ... args)
{
(Printer<typename std::decay<T>::type, Args...> {})(first, args...);
}
int main() {
my_print("Hello %s\n", "World");
my_print(1, "Hello colorful %s\n", "World");
return 42;
}
|
74,169,313
| 74,169,421
|
Template deduction depends on another template deduction
|
Since std::format isn't supported everywhere, and I didn't want another large dependency like fmt, I wanted to quickly roll my own to_string solution for a number of types. The following is the code.
#include <ranges>
#include <string>
#include <concepts>
template<typename Type>
constexpr std::string stringify(const Type &data) noexcept;
template<typename Type> requires std::integral<Type>
constexpr std::string stringify(const Type &data) noexcept {
return std::to_string(data);
}
template<typename Type>
constexpr std::string stringify_inner(const Type &data) noexcept {
return stringify(data);
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify_inner(const Type &data) noexcept {
return "[" + stringify(data) + "]";
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify(const Type &data) noexcept {
std::string string;
for (auto &i : data) {
string += stringify_inner(i);
string += ", ";
}
string.pop_back();
string.pop_back();
return string;
}
Now, if I write the following code, I get some nice output.
int main() {
std::vector<int> a = { 1, 2, 3, 4 };
std::vector<std::vector<int>> b = {{ 1, 2 }, { 3, 4 }};
std::cout << stringify(a) << std::endl;
std::cout << stringify(b) << std::endl;
}
// >>> 1, 2, 3, 4
// >>> [1, 2], [3, 4]
Now, for some reason, if I remove the stringify<std::vector<int>> call, the compiler fails to deduce the correct function.
int main() {
// std::vector<int> a = { 1, 2, 3, 4 };
std::vector<std::vector<int>> b = {{ 1, 2 }, { 3, 4 }};
// std::cout << stringify(a) << std::endl;
std::cout << stringify(b) << std::endl;
}
// >>> undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>,
// >>> std::allocator<char> > stringify<std::vector<int, std::allocator<int> > >(std::vector<int,
// >>> std::allocator<int> > const&)'
I think I understand what is happening here, but I don't know why exactly or how to fix it. It seems like the compiler needs the manual instantiation of stringify<std::vector<int>>, so that it can resolve stringify<std::vector<std::vector<int>>>.
I've never encountered this behavior before and have no idea how to continue. I'm compiling with C++20, using GCC on Windows. Thanks.
|
The order of declarations of your template overloads results in
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify(const Type& data) noexcept;
being for the overload, when specializing
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify_inner(const Type &data) noexcept {
return "[" + stringify(data) + "]";
}
with Type = std::vector<int>, but this function isn't defined anywhere. You need to make sure to declare the function signature for ranges early enough for the compiler to use it:
template<typename Type>
constexpr std::string stringify(const Type& data) noexcept;
template<typename Type> requires std::integral<Type>
constexpr std::string stringify(const Type& data) noexcept {
return std::to_string(data);
}
/////////////////////// Add this ////////////////////////////////////
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify(const Type& data) noexcept;
/////////////////////////////////////////////////////////////////////
template<typename Type>
constexpr std::string stringify_inner(const Type& data) noexcept {
return stringify(data);
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify_inner(const Type& data) noexcept {
return "[" + stringify(data) + "]";
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify(const Type& data) noexcept {
std::string string;
for (auto& i : data) {
string += stringify_inner(i);
string += ", ";
}
string.pop_back();
string.pop_back();
return string;
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify(const Type& data) noexcept;
template<typename Type>
constexpr std::string stringify_inner(const Type& data) noexcept {
return stringify(data);
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify_inner(const Type& data) noexcept {
return "[" + stringify(data) + "]";
}
template<typename Type> requires std::ranges::range<Type>
constexpr std::string stringify(const Type& data) noexcept {
std::string string;
for (auto& i : data) {
string += stringify_inner(i);
string += ", ";
}
string.pop_back();
string.pop_back();
return string;
}
|
74,169,479
| 74,169,496
|
What's wrong with the space for an array declaration in c++?
|
I have long been declaring a lot more space for arrays during competitive programming.
int pr[100010]; //for example
However, when I was trying to declare an array for a smaller space this morning, things went wrong.
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int pr[100]; //seems enough
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
You see, this program was for calculating the prefix sum of an array. The value for this array comes from input.
The space for this array seems enough.
But when I input these to my program and found that it occurs to a wrong output:
//the input:
5
1 2 3 4 5
//the output:
1875947561
1875947563
1875947566
1875947570
1875947575
The array might just out of bounds. I thought.
However, when I modified the space 100 to 10, the answer was correct this time!
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int pr[10]; //smaller, but correct!
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
cout << "*" << pr[i] << endl;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
5
1 2 3 4 5
1
3
6
10
15
It seems that the problem happend at here:
pr[i] = pr[i-1] + x;
I know that the initial value of the array was 0, but why a smaller space works well and the higher space didn't ?
The most interesting thing is that when I declare the array as a global variable, though small, the answer was correct?
#include <iostream>
using namespace std;
int pr[1]; //such a tiny space but correct!
int main()
{
int n; cin >> n;
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
The results:
//the input
5
1 2 3 4 5
//the output
1
3
6
10
15
This problem confuses me a whole day, can someone help me? I can't fell asleep as the problem was still there :(
|
The problem is here:
int pr[100]; //seems enough
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x; // uninitialized read of pr[0]
}
Reading an uninitialized variable is undefined behavior. In this case you read some garbage value, but your program could also crash or produce other unexpected results.
As a side note, your program does not need an array at all. You could output each value as soon as you calculate it, and store the current sum in a scalar.
|
74,169,543
| 74,169,560
|
Why i am getting a zero total amount of money?
|
This code should accept three inputs represent the money: "cent", "paper" and "coins", then calculate the total amount of the money:
int coins = 0;
int paper = 0;
int cents = 0;
int transaction = 0;
int total_money = coins + paper + cents;
cout << "Do you want to fill your piggy bank?";
cin >> transaction;
while (transaction != 2)
{
cout << "How many paper money? :";
cin >> paper;
cout << "How many coins ? :";
cin >> coins;
cout << "How many cents? :";
cin >> cents;
cout << "Do you want another transaction?";
cin >> transaction;
if (transaction == 2)
{
cout << "total in piggy bank" << total_money << endl;
}
else
{
cout << "End of the program";
}
return 0;
}
What seems to be the problem here?
|
You need to do the addition after you get the values from the user, not before.
Like this (for example)
if (transaction == 2)
{
int total_money = coins + paper + cents;
cout<<"total in piggy bank" <<total_money<< endl;
}
A program is a set of statements that are executed in a particular order. Variables in that program are updated at certain points in the execution of the program. If you get your code in the wrong order then the variables are not going to have the values you expect them to.
|
74,169,933
| 74,175,025
|
How to embed a youtube video?
|
I'm trying to embed a youtube video in a QWebEngineView widget, however, the video is not playing and I'm getting this msg:
"Video indisponible Watch on YouTube"
I tried with different videos and in all I got the same error, I also tried setting some settings up like:
QWebEngineView* view = new QWebEngineView();
view->setHtml(R"(<iframe width="800" height="600" src="https://www.youtube.com/embed/TodEc77i4t4" title="Qt 6 - The Ultimate UX Development Platform" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>)");
view->settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);
view->settings()->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
view->show();
What I'm missing?
|
I didn't use HTML and I test this way and it shows me the Video:
I add this code in MainWindow:
QWidget *wgt = new QWidget(this);
QGridLayout *gridLayout = new QGridLayout(wgt);
wgt->setStyleSheet(QString::fromUtf8("border: 1px solid black;\n"
"border-radius: 25px;background-color:black;"));
ui->centralwidget->layout()->addWidget(wgt);
QWebEngineView* view = new QWebEngineView(wgt);
view->setWindowTitle("Qt 6 - The Ultimate UX Development Platform");
view->setUrl(QUrl("https://www.youtube.com/embed/TodEc77i4t4"));
view->settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);
view->settings()->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
wgt->layout()->addWidget(view);
This is the Result:
For Style your widget please look at Qt Style Sheets Reference, it's similar to CSS and you can use this.
for example, you can add this:
view->setStyleSheet(QString::fromUtf8("border: 1px solid black;\n"
"border-radius: 25px;"));
QWebEngineView object didn't get style so I add it inside the helper widget and add style to that.
you can clone it from here :
https://gitlab.com/ParisaHR/stackoverflow_qwebengineview
|
74,170,473
| 74,173,819
|
Is it possible to load an extra helper .so during current gdb session?
|
Is it possible to load an extra helper .so during current gdb session?
// point.h
class Point
{
public:
int x;
int y;
Point(int x1, int y1) {x = x1; y = y1;}
};
// main.cpp
#include "point.h"
#include <stdio.h>
int main()
{
Point p(3, 4);
printf("%d\n", p.x);
return 0;
}
g++ -g -c main.cpp -o main.o
g++ -g main.o -o main
When debugging, I need to add a helper function to dump the Point object. But I don't want to recompile and rerun. (It might take a long time.) So I am trying to build another helper.so.
// helper.cpp
#include "point.h"
#include <stdio.h>
void dump_point(Point *p)
{
printf("Point(%d, %d)\n", p->x, p->y);
}
g++ -g -fPIC -shared helper.cpp -o helper.so
Is it possible to load this helper.so in gdb so I can call dump_point() without rerunning?
|
When debugging, I need to add a helper function to dump the Point object.
The "normal" way to do this to write a custom pretty printer in Python.
One advantage of doing that is that the pretty printer will also work for a core dump, whereas dump_point() solution will not (regardless of whether it's linked in or loaded from a separate .so).
So I am trying to build another helper.so.
If your main was linked against libdl, you could do this:
(gdb) call dlopen("./helper.so", 0)
(gdb) call dlsym($_, "dump_point")
Note: you will want to make dump_point extern "C" to avoid name mangling.
|
74,170,676
| 74,170,767
|
In c++ Why and how classname::member syntax can be used for an instance member?
|
class Human {
public:
Human(string name);
string getName() {
return Human::name;
}
void setName(string name) {
Human::name = name ;
}
private:
string name;
};
Human::name in getName and setName funcs. work perfectly although name is not a static variable.
Why is this happening ?
As far as I know "::" is used to acces functions or static members of a class.
I thought correct usage in getName would be return this -> name or return name.
And even, when generated auto setter function in Clion, setter function uses Human::name not this -> name
I'm coming from java background and in java classname.X (which resembles classname::X in c++) was only used for static members or functions of a class. That is why I am confused
|
First things first, you're missing a return statement inside setName, so the program will have undefined behavior.
Now, Human::name is a qualified name that refers to(or names) the non-static data member name. For qualified names like Human::name, qualified lookup happens which will find the data member name.
On the other hand, just name(without any qualification) is an unqualified name and so for it, unqualified lookup will happen which will also find the data member named name. And so you could have just used name(instead of Human::name) as it will also refer to the same non-static data member.
Basically the main difference between name and Human::name are that:
name is a unqualified name while Human::name is a qualified name.
For name unqualified lookup will happen while for Human::name qualified lookup will happen.
The similarity between the two is that:
Both at the end of the day refer to the same non-static data member.
|
74,170,753
| 74,170,903
|
Is there a difference in undefined behaviour in C and C++ when accessing different members of different type in a union for write and read operations?
|
Let's start immediately with the example code:
#include <stdio.h>
#include <stdbool.h>
typedef union {
bool b;
int i;
} boolIntUnion;
int main(void) {
boolIntUnion val;
val.i = 0;
printf("i = %d; %s\n", val.i, ((val.b) ? "true" : "false"));
val.i = 1;
printf("i = %d; %s\n", val.i, ((val.b) ? "true" : "false"));
val.i = 2;
printf("i = %d; %s\n", val.i, ((val.b) ? "true" : "false"));
}
My question now if using the union as you can see here is some sort of undefined behaviour. What's of interest for me is the third case, where I'm setting val.i to 2, but then use the boolean from the union via val.b as a condition for my printed string. In MSVC 19 and gcc, I get the expected behaviour of the 2 in the union resulting in a value of true from val.b, but with Clang (and Clang-cl), I get false. I'm suspecting a compiler error, because if I look at the assembly output of Clang, I see test cl, 1, whereas MSVC and gcc give me test eax, eax and test al, al respectively. I tested this on Godbolt with all three compilers including execution output. Clang in the middle is where you can see the differing behaviour. [1]
Now, I'm not sure if using a union in this way is undefined behaviour under any C or C++ standard. That's basically my question now. If this is valid code, which I assume, I'd file a bug with Clang / LLVM. Just wanted to be sure beforehand. I tested this with both Clang and Clang++, same behaviour.
[1] https://godbolt.org/z/c95eWa9fq
|
In C++, using a union member other than the last-stored member is undefined behavior, with an exception for structures with common initial layouts.
C++ 2020 draft N4849 [class.union] (11.5) 2 says “… At most one of the non-static data members of an object of union type can be active at any time…” with a note there is an exception for inspecting the members in structures in the union that have a common initial sequence. [basic.life] (6.7.3) 1.5 says the lifetime of an object o ends when (among other possibilities) “the storage which the object occupies … is reused by an object that is not nested within o (6.7.2)”. Thus, after val.i = …;, the lifetime of val.b has ended (if it began), and the behavior of accessing val.b is not defined by the C++ standard. Any output or other behavior from the program or compiler is allowed by the C++ standard.
In C, accessing a union member other than the last-stored member results in reinterpreting the applicable bytes of the union in the new type, per C 2018 note 99 (speaking about 6.5.2.3 3, which says that accessing a union with . or -> provides the value of the named member, without exception for whether it was the last-stored member or not).
|
74,171,051
| 74,171,119
|
Warning in visual studio in simple sfinae code
|
I am writing a simple code for learning sfinae. However, it generates a warning only in Visual Studio (not when using g++).
The code is:
#include <iostream>
#include <type_traits>
template <class T, typename std::enable_if<std::is_integral<T>::value, nullptr_t>::type = nullptr>
void f(T t)
{
std::cout << "Integer" << std::endl;
return;
}
template <class T, typename std::enable_if<!std::is_integral<T>::value, nullptr_t>::type = nullptr>
void f(T t)
{
std::cout << "not integer" << std::endl;
return;
}
int main()
{
f(10);
f(5.5);
f("Hello");
return 0;
}
And the warning is:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\ostream(746): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
sfinae2.cpp(9): note: see reference to function template instantiation 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,const char *)' being compiled
sfinae2.cpp(23): note: see reference to function template instantiation 'void f<int,nullptr>(T)' being compiled
with
[
T=int
]
The warning disappears when compiling with the flag /EHsc, or when deleting the cout from both functions.
I want to know why this flag is needed.
Best regards.
|
I want to know why this flag is needed.
From msvc's exception handling model:
Arguments
c
When used with /EHs, the compiler assumes that functions declared as extern "C" never throw a C++ exception. It has no effect when used with /EHa (that is, /EHca is equivalent to /EHa). /EHc is ignored if /EHs or /EHa aren't specified.
(emphasis mine)
|
74,171,185
| 74,171,318
|
Two different outputs from functions
|
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
char* InitializingMatrix(char start, char end) {
char matrix[9];
//Initializing random symbols to char massive
srand((unsigned)time(0));
for (int i = 0; i < 9; i++)
matrix[i] = (int)start + rand() % (int)end;
//Output matrix
for (int i = 0; i < 9; i++)
(i == 3 || i == 6) ? cout << endl << (char)matrix[i] << " " : cout << (char)matrix[i] << " ";
cout << endl;
return matrix;
}
void Output(char matrix[]) {
//Output matrix
for (int i = 0; i < 9; i++)
(i == 3 || i == 6) ? cout << endl << (char)matrix[i] << " " : cout << (char)matrix[i] << " ";
}
int main() {
Output(InitializingMatrix('1', '6'));
return 0;
}
Problem
The output of the matrix from the function for initializing the matrix and from the function for outputting the matrix are different.
Questions
Why output from InitializingMatrix and Output have differences?
How to fix it?
|
The issue that you return a Pointer but you allocate a Value.
Allocation:
char matrix[9];
Return value:
char* InitializingMatrix(...)
Type char matrix[] is a compiled time array.
If you wish to use arrays you'll need to use new char() instead to dynamically allocate a new array.
The C++ OOP way is to use a class:
Use the built in type std::array<...>
Create a class and save the array in there:
struct MyData
{
char Data[10];
}
The compiler would help you pass this around by value or use a ref to pass it by reference instead:
MyData Initialize() { ... };
void Output(MyData& data);
//or
void Output(const MyData& data);
int main()
{
MyData data = Initialize();
Output(data );
return 0;
}
The more professional way is to use built-in types or frameworks that exist,
If you need a matrix you can use libraries like GMTL or EIGEN
|
74,171,340
| 74,173,736
|
Can't able to static compile QT 6.4.0 using Mingw
|
When I was trying to compile QT 6.4.0 static with Mingw I had and error with fxc, after spending time found it was an error because it couldn't able to find fxc.exe so I added fxc to path from windows kits (10), after adding it fixed that error but now I'm getting different errors.
Configure: configure.bat -release -static -static-runtime -no-pch -optimize-size -opengl desktop -platform win32-g++ -prefix "C:\qt\6.4.0static\qt-static" -skip webengine -nomake tools -nomake tests -nomake examples
My OS: Windows 11 Pro (21H2).
For more log details: Pastebin
qsgd3d12engine.cpp: In member function 'D3D12_CPU_DESCRIPTOR_HANDLE QSGD3D12CPUDescriptorHeapManager::allocate(D3D12_DESCRIPTOR_HEAP_TYPE)':
qsgd3d12engine.cpp:121:41: warning: comparison of integer expressions of different signedness: 'int' and 'long long unsigned int' [-Wsign-compare]
121 | for (int bucket = 0; bucket < _countof(heap.freeMap); ++bucket)
| ^
qsgd3d12engine.cpp:157:23: warning: comparison of integer expressions of different signedness: 'int' and 'long long unsigned int' [-Wsign-compare]
157 | for (int i = 1; i < _countof(heap.freeMap); ++i)
| ^
qsgd3d12engine.cpp: In function 'void getHardwareAdapter(IDXGIFactory1*, IDXGIAdapter1**)':
qsgd3d12engine.cpp:224:83: error: expected primary-expression before ')' token
224 | HRESULT hr = D3D12CreateDevice(adapter.Get(), fl, _uuidof(ID3D12Device), nullptr);
| ^
qsgd3d12engine.cpp:224:63: error: '_uuidof' was not declared in this scope
224 | HRESULT hr = D3D12CreateDevice(adapter.Get(), fl, _uuidof(ID3D12Device), nullptr);
| ^~~~~~~
In file included from C:/msys64/mingw64/include/winbase.h:2811,
from C:/msys64/mingw64/include/windows.h:70,
from C:/Qt/dev/Qt/src/qtbase/src/corelib/global/qt_windows.h:64,
from C:\Qt\dev\Qt\src\qtbase\include/QtCore/qt_windows.h:1,
from C:/Qt/dev/Qt/src/qtbase/src/gui/opengl/qopengl.h:49,
from C:\Qt\dev\Qt\src\qtbase\include/QtGui/qopengl.h:1,
from C:/Qt/dev/Qt/src/qtdeclarative/src/quick/scenegraph/coreapi/qsggeometry.h:44,
from ..\..\..\..\include\QtQuick/qsggeometry.h:1,
from qsgd3d12engine_p.h:57,
from qsgd3d12engine.cpp:40:
qsgd3d12engine.cpp:241:80: error: expected primary-expression before ')' token
241 | if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), fl, _uuidof(ID3D12Device), nullptr))) {
| ^
qsgd3d12engine.cpp:241:60: error: '_uuidof' was not declared in this scope
241 | if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), fl, _uuidof(ID3D12Device), nullptr))) {
| ^~~~~~~
EDIT: Fixed the issues, check the marked answer for more details.
|
To fix __uuidof error with mingw follow the steps from this link:
https://forum.qt.io/topic/128587/build-failure-_uuidof-was-not-declared-in-this-scope/7
To fix QT DirectX issue follow this steps:
Download Windows SDK from https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/. (I downloaded SDK for windows 11 (my OS)).
open this file pathToQTSource\qtdeclarative\plugins\scenegraph\d3d12\qsgd3d12engine.cpp in your preferred editor and add this line #include <d3d12sdklayers.h> at include section and save it.
That's it.
To fix another error I've faced while compiling mfvideorenderercontrol.cpp:
Goto pathToQtSource\qtmultimedia\src\plugins\wmf\player\mfvideorendercontrol.cpp and change the access modifier from protected to public of void customEvent(QEvent *event) function (declared at class PresentEvent).
Thanks to @thedemons for helping me to fix the issue.
|
74,171,347
| 74,171,579
|
How to print a whole pair by just a key value in map c++?
|
Let's say I'm having a map of integer key value!
map<int,string>a={{1,"one"},{2,"two"}};
How can I print a whole pair by just supplying a key value?
Let's say user entered 1; I want my code to print 1,one then,How can i do so?
|
I've a map and user has to supply a key value,If that key value is present in that map,Then I've add that whole "pair" in different map, Is it possible to do so?
Yes this is possible. You can use std::map::find to check if your input map contains a given key and then std::map::insert to add the key value pair into the output map as shown below:
int main()
{
std::map<int,string> searchMap={{1,"one"},{2,"two"}}; //map in which key is to be searched
std::map<int, string> outputMap;
int input =0;
if(std::cin >> input); //take input from user
{
//search the map for the input key
auto findInput = searchMap.find(input);
if(findInput!=searchMap.end())//check if the input was found inside the map
{
std::cout << "The map contains the key: " << input << " entered by user" << std::endl;
//add the key value pair to the outputmap
outputMap.insert({input,findInput->second}); //or just outputmap[input] = findInput->second
}
else
{
std::cout <<"The map does not contain the key: " << input << " entered by user" << std::endl;
}
}
//lets confirm that outputmap was filled with input
for(const auto&[key, value]:outputMap)
{
std::cout << key << "->" << value << std::endl;
}
}
Working demo
|
74,171,648
| 74,172,133
|
Is it possible to "overload" the type deduced by auto for custom types in C++?
|
Not sure whether "overloading" is the proper term, however I am curious whether it is possible to make expressions of a given type to automatically convert to other type?
Possible motivation:
template <typename T> Property {
// implement the desired behavior
};
class SomeClass {
// ...
Property<SomeType> someProperty;
// ...
};
SomeClass someInstance{ ... };
auto someVariable = someInstance.someProperty; // Type of some variable will be Property<T>
If I take some effort, I can disallow constructor and assignment of Property and use
SomeType someVariable = someInstance.someProperty;
However, I am curious whether it is possible to make
auto someVariable = someInstance.someProperty;
such the the type of someVariable is SomeType and not Property<SomeType>.
Thanks.
|
No, that is not possible. auto will deduce to the (decayed) type of the right-hand side and there is no way to affect this deduction.
You can however of course write a function template X such that
auto someVariable = X(someInstance.someProperty);
will result in the type you want, basically without any restrictions on the possible type transformations made by X.
|
74,171,933
| 74,172,170
|
hierarchical_mutex: are spurious exceptions possible?
|
In his book, C++ Concurrency in Action, A. Williams introduces the concept of a lock hierarchy as a deadlock-avoidance mechanism. Below, I report a stripped down version of a HierarchicalMutex implementation (taken from the book):
class HierarchicalMutex {
private:
std::mutex Mutex_;
unsigned const Level_;
unsigned PrevLevel_{0};
static thread_local unsigned current_level;
public:
explicit HierarchicalMutex(unsigned level) : Level_{level} {}
void lock() {
if (current_level <= this->Level_) { // (1)
// I can only lock a mutex with a lower level than the currently
// locked one.
throw std::logic_error("lock: Out of order");
}
this->Mutex_.lock();
this->PrevLevel_ = std::exchange(current_level, this->Level_);
}
// try_lock implemented accordingly [...]
void unlock() {
if (current_level != this->Level_)
throw std::logic_error("unlock: Out of order");
current_level = this->PrevLevel_;
this->Mutex_.unlock();
}
};
// current_level initialized to UINT_MAX so that, in the beginning, any
// HierarchicalMutex may be locked.
thread_local unsigned HierarchicalMutex::current_level{
std::numeric_limits<unsigned>::max()};
Les's imagine threads A and B competing to lock an instance of HierarchicalMutex, as shown in the following code:
int main() {
HierarchicalMutex mutex{1};
std::thread threadA{[&mutex] { std::scoped_lock sl{mutex}; }};
std::thread threadB{[&mutex] { std::scoped_lock sl{mutex}; }};
threadB.join();
threadA.join();
}
Say that thread A:
Calls mutex.lock();
Successfully evaluates check (1) to false;
Locks HierarchicalMutex::Mutex_;
Updates HierarchicalMutex::current_level and sets it to 1.
At this point, thread B:
Calls mutex.lock();
Evaluates check (1) to true.
This means that thread B will throw; but I'd expect it to wait until thread A unlocks mutex.
My questions are:
Is the execution flow I pictured even possible?
If so, is it correct for thread B to throw or should it wait for thread A to unlock mutex (as I'd expect)?
If my expectation is correct, how should HierarchicalMutex be implemented in order for thread B to wait instead of throwing? Is it enough to replace <= in check (1) with <?
|
At this point, thread B:
Calls mutex.lock();
Evaluates check (1) to true.
No it won't. current_level is declared as a thread_local object. If you are unfamiliar with what that means, see your C++ textbook for a more complete discussion, but it boils down that current_level is a separate, discrete object in each execution thread. In both execution threads it's 0, and check (1) evaluates to false.
|
74,172,117
| 74,172,339
|
OpenMP: are variables automatically shared?
|
We already know that local variables are automatically private.
int i,j;
#pragma omp parallel for private(i,j)
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
//do something
}
}
it is equal to
#pragma omp parallel for
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
//do something
}
}
How about the other variables ? are they shared by default or do we need to specify shared() like in the example below ?
bool sorted(int *a, int size)
{
bool sorted = true;
#pragma omp parallel default(none) shared(a, size, sorted)
{
#pragma omp for reduction (&:sorted)
for (int i = 0; i < size - 1; i++) sorted &= (a[i] <= a[i + 1]);
}
return sorted;
}
Can we not specify the shared and work directly with our (a, size, sorted) variables ?
|
They are shared by default in a parallel section unless there is a default clause specified. Note that this is not the case for all OpenMP directives. For example, this is generally not the case for tasks. You can read that from the OpenMP specification:
In a parallel, teams, or task generating construct, the data-sharing attributes of these variables are determined by the default clause, if present (see Section 5.4.1).
In a parallel construct, if no default clause is present, these variables are shared.
For constructs other than task generating constructs, if no default clause is present, these variables reference the variables with the same names that exist in the enclosing context.
In a target construct, variables that are not mapped after applying data-mapping attribute rules (see Section 5.8) are firstprivate.
You can safely rewrite your code as the following:
bool sorted(int *a, int size)
{
bool sorted = true;
#pragma omp parallel for reduction(&:sorted)
for (int i = 0; i < size - 1; i++)
sorted &= a[i] <= a[i + 1];
return sorted;
}
|
74,172,199
| 74,172,432
|
When resizing a std::vector of std::queue. Compile error; static assertion failed: result type must be constructible from value type of input range
|
I got the following class:
class Buf {
const uint8_t *data;
size_t size;
public:
Buf() : data(nullptr), size(0) {};
Buf(const uint8_t *data_, size_t size_) : data(data_), size(size_) { };
Buf(Buf&& other) noexcept
: data{std::exchange(other.data, nullptr)}, size{other.size} {};
Buf& operator=(Buf&& other) noexcept {
data = std::exchange(other.data, nullptr);
size = other.size;
return *this;
}
Buf(const Buf& other) = delete;
Buf& operator=(Buf other) = delete;
~Buf()
{
free((void *)data);
}
};
I use this class inside a queue
int main()
{
std::vector<std::queue<Buf>> data;
data.resize(10); // compile error
return 0;
}
I get a long compile error boiling down to:
error: static assertion failed: result type must be constructible from
value type of input range
If I in turn use a std::deque instead it seems to compile.
So why does not work with std::queue and how could it be fixed. And why does it seem to work with std::deque
The code: https://godbolt.org/z/Ev86YG1nG
|
std::queue is a container adapter; that is, it forwards all of its actual operations to an internal container of a type specified by a template argument. By defualt, this container is std::deque.
However, std::deque<T> is not noexcept moveable. Therefore, when vector<T> attempts to resize itself, it cannot use the move operation; it must copy it. And since Buf is not copyable, neither is std::deque<Buf>. So vector tries to copy a non-copyable type; hence the compile error.
There's not really a good solution to this. vector is not a good type for a queue, since insertion/removal at the front is slow. And deque is not noexcept moveable, nor is list. Maybe if the queues are small, using std::queue<Buf, std::vector<Buf> might work out performance-wise.
Using std::deque for the outer container works because many of its operations do not require the type to be moveable or copyable. Insertion/removal from the head/tail don't provoke copying.
|
74,172,825
| 74,173,057
|
match c++ constructors with regex
|
I'm trying to create a regular expression to match constructor functions in C++ code. For instance, given a file that has the following content:
Foo::foo // 1
Foo::Foo // 2
Foo::~Foo // 3
Foo::Foo(std::string) // 4
Logger::removeAppender(PLogAppender*) // 5
Logger::error(std::string&) // 6
I'd like the expression to find lines 2 and 4.
The thing I came up with is this:
\(\w\+\)::\1
which matches the required lines, but also stuff I don't want:
Logger::removeAppender(PLogAppender*)
Logger::error(std::string&)
where I've highlighted the matching characters from the expression. I understand the issue is that the regex finds the same subset of characters before and after ::, but I don't know how to deal with it. How can I change my expression to match only constructors?
EDIT
The reason for needing this... I'm working on a large C++ project which, unfortunately, uses a lot of static initialisation. We recently upgraded our compiler to g++ version 9.3.1 and started experiencing the static initialisation order fiasco. At this point, I'm trying to find out the order of initialisation in the old working code. I was therefore thinking to use gdb with rbreak to match constructors so I can see what is initialised first. Is there a better way to do this?
|
Just use \s to make sure there are spaces ahead of the definition, also match for the arguments as well:
(?<=\s|^)(\w+)::\1\s*(\((?:.|\n)*?\))*
Try it on regexr
|
74,172,859
| 74,172,892
|
How to do a logical 'or' of requirements in a single concept?
|
I have the following case
template<typename Class>
concept has_member = requires (Class t)
{
// How can I write only either of the following conditions be satisfied?
{t.isInterface() }->std::same_as<bool>;
// or
{t.canInterface() }->std::same_as<bool>;
// or
// ... more conditions!
};
struct A {
bool isInterface() const { return true; }
};
struct B {
bool canInterface() const { return true; }
};
void foo(const has_member auto& A_or_B)
{
// do something
}
int main() {
foo(A{}); // should work
foo(B{}); // should work
}
Like I mentioned in the comments, I would like to logically or the requirements (in a single concepts), so that the class A and B can be passed to the doSomething().
As per my knowledge, the the current concept is checking all the requirements, that means a logical and.
If I take it apart to different concepts everything works, but I would need more concepts to be written tosatify the intention.
Is it possoble to combne into one? something like pseudocode
template<typename Class>
concept has_member = requires (Class t)
{
{t.isInterface() }->std::same_as<bool> || {t.canInterface() }->std::same_as<bool>;
// ...
};
|
Is it possoble to combine into one?
Yes, it is possible. You can write the conjunction of two requires as follows:
template<typename Class>
concept has_member =
requires (Class t) { {t.isInterface() }->std::same_as<bool>; }
|| //---> like this
requires (Class t) { {t.canInterface() }->std::same_as<bool>;};
// ... more conditions!
Demo
|
74,173,217
| 74,173,592
|
How does c++ decide which namespace to pick if it is omited
|
Why was the last A picked from ns1 namespace instead of ns2?
(Bar is of type
ns1::A<ns1::A<ns2::A, ns2::B>, ns2::B>)
namespace ns1 {
template <typename T, typename U>
struct A {};
}
namespace ns2 {
struct /*ns2*/ A : ns1::A<int, /*ns2*/ A> {
typedef ns1::A<int, /*ns2*/ A> Foo;
};
struct B : ns1::A< /*ns2*/ A, B> {
typedef ns1::A< /*ns1*/ A, B> Bar;
};
}
I'm using vscode with g++ 11.2.0
|
C++ classes have an injected class name available in class scope, which refers to the class itself. For example, for ns1::A<T, U>, the name A refers to ns1::A<T, U> in class scope .
This injected class name can also be accessed in derived classes, so in ns2::B, the name A refers to the base class which is ns1::A<ns2::A, ns2::B>.
The injected class name behaves like a member typedef, so it takes precedence over namespace-scope names when in class scope. To refer to a namespace-scope type you'd need to qualify it.
Within ns2::A, you get different behavior: here the base class has an injected class name A referring to ns1::A<int, ns2::A> (similarly to before), but ns2::A also has an injected class name A referring to itself. The derived class's names take precedence so A refers to ns2::A here.
|
74,173,414
| 74,173,931
|
Does std::cout guarantee to print a string if it doesn't end with a newline?
|
I've heard that the following program isn't guaranteed to print the string on every platform and to actually do it you need to add \n to the end or flush the buffer by other means. Is that true or does the standard guarantee the expected output anyway?
#include <iostream>
int main() {
std::cout << "Hello, world!";
}
|
[ios.init]/1 The class Init describes an object whose construction ensures the construction of the eight objects declared in <iostream> (29.4) that associate file stream buffers with the standard C streams provided for by the functions declared in <cstdio> (29.12.1).
[ios.init]/3
Init();
Effects: Constructs and initializes the objects cin, cout, cerr, clog, wcin, wcout, wcerr, and wclog if they have not already been constructed and initialized.
[ios.init]/4
~Init();
Effects: If there are no other instances of the class still in existence, calls cout.flush(), cerr.flush(), clog.flush(), wcout.flush(), wcerr.flush(), wclog.flush().
So therefore, std::cout.flush() would be called as part of the program's normal termination sequence, by the destructor of the same object (sometimes known as nifty counter) that ensured std::cout was initialized in the first place.
|
74,173,642
| 74,174,596
|
Linker command failed. CMAKE_INSTALL_RPATH not working
|
Trying to build a simple application with EASTL lib and having an error while building cmake --build .
I don't know where is my mistake.
Getting error:
/usr/bin/ld: warning: libc++.so.1, needed by /home/user_name/.conan/data/eastl/package/lib/libEASTL.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: warning: libc++abi.so.1, needed by /home/user_name/.conan/data/eastl/package/lib/libEASTL.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: /home/user_name/.conan/data/eastl/package/lib/libEASTL.so: undefined reference to `std::__1::mutex::lock()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
gmake[2]: *** [CMakeFiles/md5.dir/build.make:97: bin/md5] Error 1
gmake[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/md5.dir/all] Error 2
gmake: *** [Makefile:91: all] Error 2
My CMakeLists.txt:
cmake_minimum_required(VERSION 3.21)
project(MD5Encrypter)
add_definitions("-std=c++17")
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
set(CMAKE_BUILD_RPATH_USE_ORIGIN ON)
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
set(CMAKE_SKIP_BUILD_RPATH OFF)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH ON)
set(CMAKE_INSTALL_RPATH "$ORIGIN/../.lib")
conan_basic_setup()
add_executable(md5 main.cpp)
target_link_libraries(md5 ${CONAN_LIBS})
Have libEASTL.so in {project_dir}/.lib
|
Find the solution.
The problem was is missing package libc++-dev
So, the solution is to install it:
sudo apt install libc++-dev
|
74,174,248
| 74,174,533
|
c++ can't pass an argument with CreateProcess
|
i have to pass a string into my process, but for some reason i can't
i've tried to pass a path and an argument in function, i've tried to put a \0 after the argument, i've tried to pass an argument or space + an argument but it doesn't passes.
could you please help me?
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
using namespace std;
void _tmain(int argc, TCHAR* argv[])
{
cout << "we are here!\n";
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
string first = "C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe"; //Initializing a name of our file
wstring temp = wstring(first.begin(), first.end()); // Initializing an object of wstring
LPCWSTR file_name = temp.c_str(); // Applying c_str() method on temp
string s1 = " 1.exe 1\0";
LPWSTR cl1 = (LPWSTR)s1.c_str();
// Start the child process.
if (!CreateProcess(file_name, // No module name (use command line)
cl1, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Creating console for our application
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
cout << "we are done!\n";
}
thanks for your help in advance
|
Are you compiling in Unicode or Multibyte (MBCS)?
Assuming you are compiling in Unicode you can avoid the use of string objects and use wstring objects instead.
To initialize a wstring you have to prefix the double quoted string with an L, i.e.
wstring first(L"C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe");
So, you can avoid the use of temp variable.
Note: Is more efficient to initialize a (w)string using the constructor instead of the assignment operator.
Also, the cast in
string s1 = " 1.exe 1\0";
LPWSTR cl1 = (LPWSTR)s1.c_str();
is nos valid, as s1.c_str() return type is const char* (or LPCSTR).
Instead, you can declare
wstring s1(L" 1.exe 1\0");
LPCWSTR cl1 = s1.c_str();
In fact, you don't need to assign the result of c_str() to another variable. You can call to c_str() when you are calling to CreateProcess. The code could be something as:
//Initializing a name of our file
wstring first(L"C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe");
wstring s1(L" 1.exe 1\0");
// Start the child process.
if (!CreateProcess(first.c_str(), // No module name (use command line)
const_cast<LPWSTR>(s1.c_str()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Creating console for our application
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return;
}
If you are compiling with MBCS you should change wstring by string and remove the L prefix when initializing strings. The rest of the code could remain the same.
|
74,174,382
| 74,174,406
|
why don't we deallocate memory after allocating memory for object in heap in C++?
|
#include<iostream>
using namespace std;
class car
{
string name;
int num;
public:
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
void enter()
{
cin >> name;
cin >> num;
}
void display()
{
cout << "Name: " << name << endl;
cout << "Num: " << num << endl;
}
};
int main()
{
// Using new keyword
car *p = new car("Honda", 2017);
p->display();
}
why don't we deallocate space for 'car *p'? If we don't deallocate memory space on the heap, won't there be a memory leak?
I am a newbie trying to learn c++. I had read that I always had to deallocate space after allocating on heap... I found this code online
|
Most operating systems will free all memory associated with a program when it ends, so in this case, delete p; can be extraneous.
This gets a bit more uncertain the lower level you go, especially in embedded systems. Best to get in the practice of using delete everytime you use new.
Or don't use new/delete at all when possible.
In your case it is certainly not necessary to use dynamic memory allocation. You could simply write:
int main() {
car p("Honda", 2017);
p.display();
}
If you insisted on using dynamic memory allocation, you might use a smart pointer which will take care of the deallocation for you.
#include <memory>
// car class stuff
int main() {
std::unique_ptr<car> p = std::make_unique<car>("Honda", 2017);
p->display();
}
An aside on your car class: accustom yourself to using member initializer lists in your constructors.
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
Becomes:
car(string a, int n) : name(a), num(n)
{
cout << "Constructor called" << endl;
}
|
74,174,625
| 74,174,684
|
Why reference to array's object returns the object's address, not the value itself?
|
I've been studying arrays for a while and I struggle to grasp the idea behind these lines of code:
int array[] {1, 2, 3, 4};
std::cout << "The address of the first element is " << &array[0];
Why reference in this case prints the address and not the value?
As far as I know reference access the value of the object being referenced, not its address.
|
int a = 24;
int& r = a; // <- when is part of a type (e.g `int&` here) `&` denotes a reference type
int* p = &a; // <- as an operator `&` is the address of operator
|
74,174,626
| 74,174,739
|
std::generate_n cannot generate my objects
|
I have a very simple class, which has an x, y and z values. Like so:
class Individual
{
public:
static std::unique_ptr<Individual> Spawn(std::mt19937& rng);
Individual(double x, double y)
:
x(x),
y(y)
{
SetZ();
}
double GetZ() const
{
return z;
}
private:
void SetZ()
{
z = x * 0.123f + y * 0.912f;
}
private:
double x = 0.0f;
double y = 0.0f;
double z = 0.0f;
};
The Spawn method just generates random values for x and y and spawns an individual:
std::unique_ptr<Individual> Individual::Spawn(std::mt19937& rng)
{
std::uniform_real_distribution<double> dist(-10.0f, 10.0f);
return std::make_unique<Individual>(dist(rng), dist(rng));
}
The problem is that in main.cpp I've got a vector of these individuals, and I'm trying to populate it with 10 random individuals via std::generate_n :
std::mt19937 rng = std::mt19937(std::random_device{}());
std::vector<std::unique_ptr<Individual>> individuals;
std::generate_n(individuals.begin(), 10,
Individual::Spawn(rng));
However I'm getting an error: error C2064: term does not evaluate to a function taking 0 arguments.
What gives? What am i doing wrong? Any help/criticism is appreciated
|
generate_n()'s last argument is meant to be a function, not a value. That function will be called n times, once for each element to generate. You are giving it a std::unique_ptr. Wrap your Spawn(rng) call in a lambda expression instead.
Additionally, std::generate_n() requires an iterator to the start of a range that is at least n elements in size. It does not (it can't) use that iterator to insert new elements, non-member algorithms can never do that with an iterator. One solution is to wrap the container with std::back_inserter to create an output iterator that will extend the container as needed. Alternatively, you can resize() the vector to a size of at least n before calling std::generate_n().
A correct implementation for your function is :
std::mt19937 rng = std::mt19937(std::random_device{}());
std::vector<std::unique_ptr<Individual>> individuals;
std::generate_n(
std::back_inserter(individuals),
10,
[&rng](){ return Individual::Spawn(rng); });
Live demo : https://godbolt.org/z/756Ejscvd
|
74,174,928
| 74,174,969
|
What is a difference between *iterator.fun() and (*iterator).fun()
|
I have simple code
#include <iostream>
#include <set>
using namespace std;
class Example
{
string name;
public:
Example(string name)
{
this -> name = name;
}
string getName() const {return name;}
};
bool operator<(Example a, Example b)
{
return a.getName() < b.getName();
}
int main()
{
set<Example> exp;
Example first("first");
Example second("second");
exp.insert(first);
exp.insert(second);
for(set<Example>::iterator itr = exp.begin(); itr != exp.end(); ++itr)
{
//cout<<*itr.getName(); - Not working
cout<<(*itr).getName()<<endl;
}
}
I wonder why *itr.getName() doesn't work but (*itr).getName() works fine. What is the difference between *itr and (*itr) in this case?
|
C++ has rules for operator precedence. According to these rules, the member access operator . has higher precedence than the dereference operator unary *.
Therefore, the expression
*itr.getName()
Is interpreted as though it had the parentheses:
*(itr.getName())
That is, it tries to evaluate itr.getName() and then dereference that. itr doesn't have any such member getName, so this doesn't compile. However, you can use the parentheses yourself to write:
(*itr).getName()
This dereferences itr first, and then accesses the getName member of the resulting Example. You can also use the dereference-and-member-access operator -> as follows:
itr->getName() // Same meaning as (*itr).getName()
|
74,175,159
| 74,175,217
|
How to write a macro to convert member function to a string of its name?
|
I want to write
ProgressFunction.BindUFunction(this, NAMEOF(&MyActor::HandleProgress));
instead of
ProgressFunction.BindUFunction(this, "HandleProgress");
where BindUFunction's second parameter can only accept TCHAR*.
Question
How to define NAMEOF macro to convert &Whatever::FunctionName to "FunctionName"?
|
You could stringify the argument and find the last : in it.
#include <cstring>
#include <iostream>
#define NAMEOF(x) (strrchr(#x, ':') ? strrchr(#x, ':') + 1 : #x)
int main() {
std::cout << NAMEOF(&MyActor::HandleProgress);
}
This is very similar to https://stackoverflow.com/a/38237385/9072753 .
|
74,175,542
| 74,175,569
|
error: call to implicitly-deleted copy constructor of <T> unique_ptr
|
I'm trying to create a unique pointer to a <Node> type variable:
#include <memory>
struct Node
{
int val;
std::unique_ptr<Node> next;
Node(int value, std::unique_ptr<Node> nextNode) : val(value), next(std::move(nextNode)){};
}
int main()
{
Node headNode = Node(1, nullptr);
std::unique_ptr<Node> head = std::make_unique<Node>(headNode);
return 0;
}
And when I'm compiling this code I'm getting the following error:
error: call to implicitly-deleted copy constructor of 'Node'
return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in instantiation of function template specialization 'std::make_unique<Node, Node &>' requested here
std::unique_ptr<Node> head = std::make_unique<Node>(headNode);
^
note: copy constructor of 'Node' is implicitly deleted because field 'next' has a deleted copy constructor
std::unique_ptr<Node> next;
^
note: copy constructor is implicitly deleted because 'unique_ptr<Node>' has a user-declared move constructor
unique_ptr(unique_ptr&& __u) _NOEXCEPT
|
std::make_unique<Node>(headNode);
This constructs a unique Node by attempting to copy-construct it from another Node.
std::unique_ptr is not copyable, by definition (that would be due to the "unique" part of "unique_ptr"). This means that any class that contains a std::unique_ptr is not copyable by default, and its default copy-constructor is deleted.
This is the reason for your compilation error. You would get the same compilation error without involving std::unique_ptr:
Node node2{headNode};
This results in the same compilation error. You have two options:
Implement a copy constructor for Node that does whatever would be a meaningful result for copy-constructing your Node.
Re-engineer your code, in some way, that avoids copy-constructing Nodes.
If your described goal is "a unique pointer to a type variable", then this does not require copy-constructing it, merely:
std::unique_ptr<Node> head = std::make_unique<Node>(1, nullptr);
|
74,175,661
| 74,175,697
|
My recursive display function is not going to the next value of the array
|
I have a recursive display function, meant to go through the values of array b and print the details. My function is successful in looping the correct amount of times, but only prints out the value at index 0. For example, if I have 3 books, it prints out the first book 3 times and is not going to the other values. I am a beginner programmer and I believe I am missing something very simple or obvious, but any help is appreciated.
void displayBooks(int n)
{
// Write the code below
if (n >= currentCount) {
return;
}
else {
cout << "Name: " << b->getName() << "\n";
cout << "Name of Book Author: " << b->getAuthor() << "\n";
cout << "Publication Year: " << b->getYearOfPublication() << "\n";
cout << "ID: " << b->getID() << "\n";
displayBooks(n + 1);
}
}
This is the function itself, however I can't show the complete program since it is a lot of code with multiple files. When the function is first called as displayBooks(0) in a switch case.
|
I believe that you are not printing out each index of the "b" variable you need to access the index of each one. You need to have b as an array of pointers then access the index of that variable like b[n]->someProperty();
You can create the array like this:
Obj* b[HOWMANY];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.