question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,350,288 | 70,351,312 | Returned Eigen Matrix from templated function changes value | I came around some weird behavior concerning the eigen library and templated functions.
Maybe someone can explain to me, why the first version is not working, while the other 3 do. My guess would be the first case freeing up some local variable, but hopefully someone can enlighten me. Thanks in advance.
Here is the code:
Compiler-Explorer: https://compiler-explorer.com/z/r45xzE417
#include <concepts>
#include <iostream>
#include <Eigen/Core>
auto RungeKutta1_auto(const auto& f, const std::floating_point auto& h, const auto& y_n)
{
auto ret = y_n + h * f(y_n);
std::cout << ret.transpose() << std::endl;
return ret;
}
template<typename _Scalar, int _Rows, int _Cols>
auto RungeKutta1_template(const auto& f, const std::floating_point auto& h, const Eigen::Matrix<_Scalar, _Rows, _Cols>& y_n)
{
Eigen::Matrix<_Scalar, _Rows, _Cols> ret = y_n + h * f(y_n);
std::cout << ret.transpose() << std::endl;
return ret;
}
int main()
{
auto f = [](const Eigen::Matrix<double, 10, 1>& y) {
Eigen::Matrix<double, 10, 1> y_dot = 2 * y;
return y_dot;
};
auto g = [](const Eigen::Matrix<double, 10, 1>& y) {
return 2 * y;
};
std::cout << "RungeKutta1_auto(f, 0.05, y):" << std::endl;
Eigen::Matrix<double, 10, 1> y;
y << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;
y = RungeKutta1_auto(f, 0.05, y);
std::cout << y.transpose() << std::endl;
// Output
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
// 3.47627e-311 1 2 3 4 5 6.6 7 8 9
std::cout << "RungeKutta1_template(f, 0.05, y):" << std::endl;
y << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;
y = RungeKutta1_template(f, 0.05, y);
std::cout << y.transpose() << std::endl;
// Output
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
std::cout << "RungeKutta1_auto(g, 0.05, y):" << std::endl;
y << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;
y = RungeKutta1_auto(g, 0.05, y);
std::cout << y.transpose() << std::endl;
// Output
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
std::cout << "RungeKutta1_template(g, 0.05, y):" << std::endl;
y << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;
y = RungeKutta1_template(g, 0.05, y);
std::cout << y.transpose() << std::endl;
// Output
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
// 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
}
| In the first version,
auto ret = y_n + h * f(y_n);
due to Eigen's expression templates this gives you an intermediate expression type, as opposed to a Matrix type. You would need to explicitly invoke eval() on it to force the lazy eval to occur (and in such converting the expression to a resulting Matrix type object); e.g.:
auto ret = (y_n + h * f(y_n)).eval();
In the other versions you are explicitly typing out the type of ret to be a Matrix type, meaning you will not end up storing intermediate expression template types.
|
70,350,554 | 70,360,432 | How can I fix this callback include problem? | I am kind of new to C++ (and StackOverflow). I am trying to get something to work, but I have some #include problems.
I want to call a callback I made (from here), but I am struggling to do this.
This is my code so far. When I include child.hpp in the someclass.hpp file (because it needs information about Child for Callback<Child>), it has a looped include and the compiler crashes.
I have read about forward declarations (would be class Child; in the someclass.hpp file), and after trying I figured out this works, but I also read different opinions about this.
I have all .hpp files guarded with #ifndef CLASSNAME #define CLASSNAME ... #endif
Do I need to change my entire design, or what is the best option in my case?
base.hpp
#include "someclass.hpp"
class Base
{
protected:
unique_ptr<SomeClass> someClass;
};
base.cpp
#include "base.hpp"
Base::Base()
{
this->someClass = make_unique<SomeClass>();
}
child.hpp
#include "base.hpp"
class Child : public Base
{
public:
void callbackFunction(std::string data);
unique_ptr<Callback<Child>> callback;
};
child.cpp
#include "child.hpp"
void Child::callbackFunction(std::string data)
{
/*does something*/
}
Child::Child()
{
this->callback = make_unique<Callback<Child>>(this, &Child::callbackFunction);
//I can call this->callback->call(data); here without problems
this->someClass->setCallback(this->callback);
//^^^^^^^^^^^^^^^ == base.someClass
}
someclass.hpp
#include "child.hpp" // < does crash compiler due to loop
//> someclass.hpp uses child.hpp
//> child.hpp uses base.hpp
//> base.hpp uses someclass.hpp
// and thus loop
class SomeClass
{
public:
void someFunction(std::string data);
void setCallback(unique_ptr<Callback<Child>> callback);
unique_ptr<Callback<Child>> callbackInstance;
};
someclass.cpp
//not 100% sure about the type of this parameter
void setCallback(unique_ptr<Callback<Child>> callback)
{
this->callbackInstance = callback;
}
void SomeClass::someFunction(std::string data)
{
//here I want to call this "Child::callbackFunction" which should go like "this->callbackInstance->call(data)" ?
}
also in someclass.hpp
template<class T>
class Callback
{
public:
Callback(T* instance, void (T::*function)(std::string))
{
this->callbackInstance = instance;
this->callback = function;
}
void call(std::string data)
{
(callbackInstance->*callback)(data);
}
private:
T *callbackInstance;
void (T::*callback)(std::string);
};
| To solve the mentioned error("expected class-name before '{' token on child.hpp") you should remove the #include "someclass.hpp" from base.hpp and replace it with a forward declaration for class SomeClass as shown below.
base.hpp
#ifndef BASE_H
#define BASE_H
//NO NEED TO INCLUDE someclass.hpp
#include <memory>
class SomeClass;//FORWARD DECLARE SomeClass
class Base
{
std::unique_ptr<SomeClass> someClass;
public:
//add declaration for default constructor
Base();
};
#endif
base.cpp
#include "base.hpp"
#include "someclass.hpp"
//other things here
Base::Base()
{
this->someClass = std::make_unique<SomeClass>();
}
child.hpp
#ifndef CHILD_H
#define CHILD_H
#include "base.hpp"
#include <memory>
#include "someclass.hpp"
class Child : public Base
{
public:
void callbackFunction(std::string data);
std::unique_ptr<Callback<Child>> callback;
//add declaration for default constrcutor
Child();
};
#endif
child.cpp
#include "child.hpp"
void Child::callbackFunction(std::string data){
/*does something*/
}
Child::Child()
{
this->callback = std::make_unique<Callback<Child>>(this, &Child::callbackFunction);
//I can call this->callback->call(data); here without problems
}
someclass.hpp
#ifndef SOMECLASS_H
#define SOMECLASS_H
#include <string>
//REMOVED include child.hpp from here
class SomeClass
{
public:
void someFunction(std::string data);
//I think I need an instance of Callback<Child> here?
};
template<class T>
class Callback
{
public:
Callback(T* instance, void (T::*function)(std::string))
{
this->callbackInstance = instance;
this->callback = function;
}
void call(std::string data)
{
(callbackInstance->*callback)(data);
}
private:
T *callbackInstance;
void (T::*callback)(std::string);
};
#endif
someclass.cpp
#include "someclass.hpp"
void SomeClass::someFunction(std::string data)
{
//here I want to call this "Child::callbackFunction" which should go like "this->callbackInstance->call(data)" ?
}
The above program compiles and executes successfully as can be seen here.
Summary
Some of the changes that i made are listed below:
Removed unnecessary includes
Added declarations for default constructor in child.hpp and base.hpp
Added include guards in all headers.
|
70,350,675 | 70,351,468 | Understanding more about type_traits | Setup
I asked a question yesterday about template method overloading and resolving issues using type traits. I received some excellent answers, and they led me to a solution. And that solution led me to more reading.
I landed on a page at Fluent CPP -- https://www.fluentcpp.com/2018/05/18/make-sfinae-pretty-2-hidden-beauty-sfinae/ that was interesting, and then I listened to the Stephen Dewhurst talk that Mr. Boccara references. It was all fascinating.
I'm now trying to understand a little more. In the answers yesterday, I was given this solution:
template< class Function, class... Args,
std::enable_if_t<std::is_invocable_v<Function, Args...>, std::nullptr_t> = nullptr>
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
Alternative Answer
After reading the CPP Fluent post and watching the talk, I came to this final solution:
template< class Function, class... Args>
using IsInvocable = std::enable_if_t < std::is_invocable_v<Function, Args...> >;
template< class Function, class... Args, typename = IsInvocable<Function, Args...> >
explicit ThreadHandle( const std::string & name, Function && f, Args &&... args ) {
startWithName(name, f, args...);
}
The first bit just moves some of the syntax into a common include file, but overall, this is simpler. I think this is clean and requires little explanation, even for someone unfamiliar with using type traits.
The Question
What I'm wondering is this. All three answers I received used a more complex form of enable_if_t like this:
std::enable_if_t<std::is_invocable_v<Function, Args...>, std::nullptr_t> = nullptr>
And I'm not sure why they would do that if I can do this instead:
std::enable_if_t< std::is_invocable_v < Function, Args... > >
Are there implications? Or is this simply a matter of the more complex one is C++11, and now C++ 14 and 17 allows a simpler form? Perhaps the people responding were simply helping me out by showing me the complete form.
To add to my confusion, one of the answers did this:
std::enable_if_t<!std::is_convertible_v<Function, std::string>, bool> = true>
And another one did this:
std::enable_if_t<std::is_invocable_v<Function, Args...>, int> = 0>
I don't really understand these implications, either.
Any help getting over the hurdle would be great. I imagine there will be cases I'll want the more complicated versions, so understanding it better would be good.
| Vocabulary
// template-head
template<typename T = T{}>
// ^^^^^^^^^^ ^^^- default template-argument
// \ type template-parameter
// template-head
template<int i = 0>
// ^^^^^ ^- default template-argument
// \ non-type template-parameter
Default template arguments are not part of a function template's type
Default template arguments are not part of a function template's type, meaning you cannot use the following approach:
// BAD: trying to define to SFINAE-mutually exclusive overloads.
template<typename T, typename = std::enable_if_t<some_predicate_v<T>>>
void f(T) {}
template<typename T, typename = std::enable_if_t<!some_predicate_v<T>>>
void f(T) {}
as these define the same function; see e.g.
Default template argument when using std::enable_if as templ. param.: why OK with two template functions that differ only in the enable_if parameter?
for details.
... whereas different types of a non-type template parameters can be used as an alternative
Thus, the approach above is typically used when you do not do overloading of otherwise identical functions, whereas the other family is used when you need to differentiate overloads.
// Variation A.
template<typename T,
// non-type template parameter of type void*,
// defaulted to nullptr
std::enable_if_t<some_predicate_v<T>>* = nullptr>
void f(T) {}
// OK: not the same function.
template<typename T,
std::enable_if_t<!some_predicate_v<T>>* = nullptr>
void f(T) {}
// Variation B.
template<typename T,
// non-type template parameter of type bool,
// defaulted to true or false
std::enable_if_t<some_predicate_v<T>, bool> = true>
void f(T) {}
// OK: not the same function.
template<typename T,
std::enable_if_t<!some_predicate_v<T>, bool> = true>
void f(T) {}
// Variation C.
template<typename T,
// non-type template parameter of type int,
// defaulted to 0
std::enable_if_t<some_predicate_v<T>, int> = 0>
void f(T) {}
// OK not the same function.
template<typename T,
std::enable_if_t<!some_predicate_v<T>, int> = 0>
void f(T) {}
// Variation D (uncommon/noisy).
template<typename T,
// non-type template parameter of type std::nullptr_t,
// defaulted to nullptr
std::enable_if_t<some_predicate_v<T>, std::nullptr_t> = nullptr>
void f(T) {}
// OK: not the same function.
template<typename T,
std::enable_if_t<!some_predicate_v<T>, std::nullptr_t> = nullptr>
void f(T) {}
Note that for variation A we leverage the fact that the 2nd template parameter of std::enable_if (alias via the _t alias template) is defaulted to void.
|
70,351,737 | 70,351,862 | what does '#' mean in cpp code? here's a code for reference . I stuck at " char top = st.empty() ? '#' : st.top(); " | bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.length();i++) {
char top = st.empty() ? '#' : st.top();
The code is the solution for 'Valid Parenthesis' on LeetCode.
| When you wrote:
char top = st.empty() ? '#' : st.top();
The above checks if st is empty. If st is empty then top is initialized with the character literal '#'. Otherwise, top is initialized with the character returned from st.top().
Also, '#' is a character literal.
|
70,352,016 | 70,353,927 | A complex read text file | I have a text file, which emulates the input to my script. Example of the file:
4 15 30
....
....
....
....
1
1 2
3
1 2
2 1
2 2
The first line contains some constants, let's say n, a, and b. Next n rows contain some map nXn. Then there is a line with m - number of new coordinates and then m rows of these coordinates. I need to read these lines consequently and output some results. I found that I can read the file using
string myText;
ifstream MyReadFile("01");
while (getline (MyReadFile, myText)) {
cout << myText << "\n";
}
MyReadFile.close();
but I don't understand how to implement a more complex reading of the input, as I need.
| Based on your description, your input problem seems to consist of 4 stages:
read one line which specifies n, a and b
read n lines which represents the "map"
read one line which specifies m
read m lines which represents "new coordinates"
Although it is possible to solve the problem using only a single loop and using a variable to indicate in which stage the input currently is (which would have to be checked in every loop iteration), a simpler and more intuitive solution would be to simply write code for each individual stage one after another.
Since only stages 2 and 4 can consist of multiple lines, it makes sense to only use a loop for these two stages, and to only use a single call to std::getline for stages 1 and 3.
In your question, it seems unclear how the input in the file after stage 4 should be interpreted. My guess is that you want to want to jump back to stage 3 and continue processing input, until end-of-file is encountered.
#include <iostream>
#include <fstream>
#include <sstream>
void do_input()
{
int n, a, b;
int m;
std::ifstream input_file( "input.txt" );
std::string line;
std::stringstream ss;
//STAGE 1
//attempt to read one line
if ( !getline( input_file, line ) )
throw std::runtime_error( "error reading from file" );
//prepare stringstream object
ss = std::stringstream( line );
//attempt to read data
ss >> n >> a >> b;
if ( !ss )
throw std::runtime_error( "error reading from file" );
//display converted input
std::cout << "STAGE 1: " <<
"n = " << n << " " <<
"a = " << a << " " <<
"b = " << b << "\n" ;
//STAGE 2
// read n lines
for ( int i = 0; i < n; i++ )
{
if ( !getline( input_file, line ) )
throw std::runtime_error( "error reading from file" );
//display input line
std::cout << "STAGE 2: Found map line: " << line << "\n";
}
//continue reading input, until end-of-file is encountered
while ( true )
{
//STAGE 3
//attempt to read one line
if ( !getline( input_file, line ) )
break;
//prepare stringstream object
ss = std::stringstream( line );
//attempt to read data
ss >> m;
if ( !ss )
break;
//display converted input
std::cout << "STAGE 3: " <<
"m = " << m << "\n";
//STAGE 4
// read m lines
for ( int i = 0; i < m; i++ )
{
if ( !getline( input_file, line ) )
throw std::runtime_error( "error reading from file" );
//display input line
std::cout << "STAGE 4: Found coordinates line: " << line << "\n";
}
}
std::cout << "Could not read further input, stopping.\n";
}
int main()
{
try
{
do_input();
}
catch ( std::runtime_error &err )
{
std::cout << "Runtime error occurred: " << err.what() << std::endl;
}
}
With the sample input specified in the question, the program has the following output:
STAGE 1: n = 4 a = 15 b = 30
STAGE 2: Found map line: ....
STAGE 2: Found map line: ....
STAGE 2: Found map line: ....
STAGE 2: Found map line: ....
STAGE 3: m = 1
STAGE 4: Found coordinates line: 1 2
STAGE 3: m = 3
STAGE 4: Found coordinates line: 1 2
STAGE 4: Found coordinates line: 2 1
STAGE 4: Found coordinates line: 2 2
Could not read further input, stopping.
|
70,352,308 | 70,356,913 | How to use untwister? | https://github.com/altf4/untwister
I wanted to use the above program to predict some PRNG. I have read the 'usage' part, I though I should use it in cmd.exe by entering the path of the untwister. I entered the path of main.cpp, only MSVC pops up. Also, MSVC doesn't allow me to debug/compile the file, so I cannot run it. I searched 'how to use untwister' on google, but there is no further instruction. I am a beginner of programming, please forgive my ignorance.
| OK, based on @drescherjm comment's, I've successfully build it.
I installed msys2 and use mingw to build it. But the .exe file has
error "_zst28__throw_bad_array_new_lengthv"
I searched the error message on google, and discover that the problem
may caused by gcc version.
I downloaded an old version (10.3.0) of gcc and mingw here:
https://winlibs.com/
I typed "cd /d D:\abc" then "mingw64\bin\mingw32-make.exe" in cmd, it
showed "Nothing to be done for" error.
I discover that I can use option to force the mingw32-make.exe to
read the Makefile. I added .am to the filename of Makefile, then type
mingw64\bin\mingw32-make.exe -f D:\abc\untwister-master\Makefile.am
The mingw32-make.exe thinks that files in
D:\abc\untwister-master\prng are in D:\abc\prng, and tells me it
can't find the files.
I moved all files and folder to D:\abc, then success!
|
70,352,772 | 70,352,915 | Why is 2 not > 0 ?? It is instead <= 0, but not < 0, nor == 0 | I was messing around a bit in C++ when I came across an issue that made absolutely no sense to me. For some reason with a variable equal to 2, 2 > 0 returns false, but 2 <= 0 and 2 >= 0 return true, while also somehow 2 < 0 and 2 == 0 return false. However, if I use just a static 2, everything works as intended.
Here's the entire code:
#include <iostream>
using namespace std;
long long f (long long n)
{
while (n > 0);
{
n /= 10;
}
cout << n << ": " << endl;
cout << n << " > 0 = " << (n > 0) << endl;
cout << n << " < 0 = " << (n < 0) << endl;
cout << n << " >= 0 = " << (n >= 0) << endl;
cout << n << " <= 0 = " << (n <= 0) << endl;
cout << 2 << ": " << endl;
cout << 2 << " > 0 = " << (2 > 0) << endl;
cout << 2 << " < 0 = " << (2 < 0) << endl;
cout << 2 << " >= 0 = " << (2 >= 0) << endl;
cout << 2 << " <= 0 = " << (2 <= 0) << endl;
return 0;
}
int main()
{
long long n = 27;
f(n);
}
This returns:
2:
2 > 0 = 0
2 < 0 = 0
2 >= 0 = 1
2 <= 0 = 1
2:
2 > 0 = 1
2 < 0 = 0
2 >= 0 = 1
2 <= 0 = 0
| The compiler assumes that n is a zero when evaluating the conditionals.
It's allowed to do that since while (n > 0); is undefined for positive n, and a compiler is allowed to assume there is no undefined behaviour.
This is plausible since conditionals can cause branch prediction failures whereas outputting n (which is 2 once you've taken the integer division by 10) does not. A lot of compiler optimisation these days is centred around not dumping the pipeline.
With something like this, check the generated assembly.
With a less aggressively optimising compiler, you would probably end up with an infinite loop with no output.
|
70,352,776 | 70,353,051 | Function To Count occurrence of given string | #include<iostream>
using namespace std;
void check_exist_get_count(string str,char ch)
{
int counter=0;
for(int x=0;x<str.length();x++)
{
if(str[x]==ch)
counter++;
}
cout<<ch<<" : "<<counter;
}
int main ()
{
string str;
cin>>str;
for(int x=0;x<str.length();x++)
{
check_exist_get_count(str,str[x]);
}
return 0;
}
Without built in function i need to to count the occurence of letter but i have problem what condition i should use to check which make for loop not sending letter more than one time
example:in my code i get
input
aaabbc
output
a : 3 a : 3 a : 3 b : 2 b : 2 c : 1
but Required answer should be
a : 3 b : 2 c : 1
| You're just iterating over the string once in your main function, and for every character in that string, again go over the whole string and count how many characters like that are in there.
What you don't do is track which characters you already have counted, that's why you count them multiple times. Don't nest loops (calling your function inside the first loop), but tear those things apart:
One option would be to do a first pass over the string, in which you just build a list of characters that are in the string, something like this:
std::set<char> chars;
for (char c: str)
{
chars.insert(c); // a set doesn't allow duplicate entries
// so you don't have to check yourself if it's already in there
}
Then you could, in a second loop, call count for each of the characters in the set. That would still be inefficient, though; you can use a map for keeping track what characters are as well as their count so far. Something like this:
Code to compute the histogram of character frequencies then could look something like this:
#include <iostream>
#include <map>
#include <string>
int main ()
{
std::string str("aaabbc");
std::map<char, size_t> charHistogram;
for (char c: str)
{
// if c not contained in map yet, it's automatically initialized to 0
++charHistogram[c];
}
for (auto const & p: charHistogram)
{
std::cout << p.first << " : " << p.second << " ";
}
return 0;
}
See code in cpp.sh
|
70,352,803 | 70,354,846 | Microsoft speech NuGet package doesn't work in C++ project | I'm trying to use the Azure cognitive services speech api in a C++ project and followed the instructions to install the NuGet package (Microsoft.CognitiveServices.Speech) via this page. After that, I followed one of the basic tutorials, but my C++ project doesn't recognise the Microsoft namespaces, like
No references seem to be added to the project and no files were added in the external dependencies directory. What am I doing wrong?
Thanks in advance :)
| I see you only #include <iostream>. Indeed, the iostream header does not contain any Microsoft namespaces. As is described in Get started with speech translation, you need to #include <speechapi_cxx.h>.
There seems to be an omission in the Get started with speech-to-text documentation: it doesn't contain the Import dependencies section similar to the one in the Get started with text-to-speech and other related documentation pages there (like Speech Translation, Speaker Recognition, etc.). You may want to submit a bug report to Microsoft.
|
70,352,884 | 70,353,734 | C++ Boost Priority Queue Behavior | I tried to find out exactly how the boost priority queue is implemented and I am confused.
Header file (main.hpp):
#ifndef MAIN_HPP
#define MAIN_HPP
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <boost/heap/priority_queue.hpp>
typedef std::int32_t int32_t;
typedef struct st {
int32_t num;
int32_t f;
st() {
std::cout << "DEFAULT" << std::endl;
this->f = 0;
}
st(int32_t num) {
std::cout << "creation\t" << num << std::endl;
this->num = num;
this->f = 0;
}
~st() {
std::cout << "del\t" << num << std::endl;
f = 1;
}
} st;
typedef struct st_c0 {
bool operator()(const st& st0, const st& st1) const {
return (st0.num > st1.num);
}
} st_c0;
typedef struct st_c1 {
bool operator()(const st* st0, const st* st1) const {
return (st0->num > st1->num);
}
} st_c1;
#endif
#include "main.hpp"
int main() {
boost::heap::priority_queue<st, boost::heap::compare<st_c0>> q0;
boost::heap::priority_queue<st*, boost::heap::compare<st_c1>> q1;
st y = st(5);
q0.push(st(44));
q0.push(y);
q0.empty();
std::cout << y.f << std::endl;
return 0;
}
The output I get is:
creation 5
creation 44
del 44
del 44
del 44
del 44
del 44
del 5
del 5
del 5
0
del 5
del 5
del 44
The order of object creation and deletion does not make sense. How do the internals of the priority queue work, and what is the best practice for them (storing pointers vs storing objects)?
| You aren't accounting for the copy-constructor that will automatically be created for your class.
In your case you wouldn't automatically get a move-constructor, but it's still nice to see where the compiler could do a move instead of a copy.
If you change your st to e.g.:
struct st {
int32_t num;
int32_t f;
st() {
std::cout << this << "\tctor default" << std::endl;
this->f = 0;
}
st(int32_t num) : num(num), f(0) {
std::cout << this << "\tctor num\t" << num << std::endl;
}
st(st const& other) : num(other.num), f(other.f) {
std::cout << this << "\tctor copy\t" << num << "\t (from " << &other << ")" << std::endl;
}
st(st&& other): num(other.num), f(other.f) {
std::cout << this << "\tctor move\t" << num << "\t (from " << &other << ")" << std::endl;
}
st& operator=(st const& other) {
num = other.num;
f = other.f;
std::cout << this << "\tassign copy\t" << num << "\t (from " << &other << ")" << std::endl;
return *this;
}
st& operator=(st&& other) {
num = other.num;
f = other.f;
std::cout << this << "\tassign move\t" << num << "\t (from " << &other << ")" << std::endl;
return *this;
}
~st() {
std::cout << this << "\tdtor\t\t" << num << std::endl;
}
};
godbolt example
you'll get a better picture of what's going on:
// construct y
0x7fffd8f3b1e8 ctor num 5
// call to push(st(44))
0x7fffd8f3b238 ctor num 44
0x7fffd8f3b1b4 ctor copy 44 (from 0x7fffd8f3b238)
0x97cec0 ctor move 44 (from 0x7fffd8f3b1b4)
0x7fffd8f3b1b4 dtor 44
0x7fffd8f3b164 ctor move 44 (from 0x97cec0)
0x7fffd8f3b178 ctor move 44 (from 0x7fffd8f3b164)
0x97cec0 assign move 44 (from 0x7fffd8f3b178)
0x7fffd8f3b178 dtor 44
0x7fffd8f3b164 dtor 44
0x7fffd8f3b238 dtor 44
// call to push(y)
0x7fffd8f3b1b4 ctor copy 5 (from 0x7fffd8f3b1e8)
0x97cee8 ctor move 5 (from 0x7fffd8f3b1b4)
0x97cee0 ctor copy 44 (from 0x97cec0)
0x97cec0 dtor 44
0x7fffd8f3b1b4 dtor 5
0x7fffd8f3b164 ctor move 5 (from 0x97cee8)
0x7fffd8f3b178 ctor move 5 (from 0x7fffd8f3b164)
0x97cee8 assign move 44 (from 0x97cee0)
0x97cee0 assign move 5 (from 0x7fffd8f3b178)
0x7fffd8f3b178 dtor 5
0x7fffd8f3b164 dtor 5
// after main()
0x7fffd8f3b1e8 dtor 5
0x97cee0 dtor 5
0x97cee8 dtor 44
So to break it down:
pushing the first element
your st is constructed and after that copied & moved a few times.
it finally ends up in 0x97cec0 (the allocated storage from the heap)
pushing the second element
the second call triggers a resize, so the 44 must be moved to a new allocation
the 5 also gets copied & moved a bit
the 5 & 44 are swaped into place, so the priority queue is correctly sorted
empty()
does nothing (would return true, because the container contains elements)
if you want to delete all elements use clear().
after main returns
y gets destructed
the priority queue gets destructed and calls the destructor for both st's
There are no guarantees though how many copies / moves the implementation of boost::heap::priority_queue<st, boost::heap::compare<st_c0>> does, so this might change at any time.
Pointers vs Objects
In general you would use objects whenever they are small and easy to copy / move.
If you use pointers your object won't be copied or moved at all, only the pointer to it, so this would be better if your objects are large and / or expensive to copy / move.
But with bare pointers you also need to delete them manually, if possible i would recommend to use smart pointers instead, e.g.:
boost::heap::priority_queue<boost::shared_ptr<st>, boost::heap::compare<TODO>> q0;
that way your ``st`'s autmatically get freed & you don't have to manually delete them.
|
70,352,966 | 70,354,840 | Qt c++ Issue receiving data weighing scale Ohaus aviator 7000 | I am trying to establisch a serial port connection to my Aviator 7000 weighing scale using Qt c++. The expected result would be a succesfull communication through the use of a byte command.
Sadly I don't receive any bytes back from the scale. below you can find what I tried so far:
const int Max_attempts = 5;
const int Max_sleep = 125;
int attemps;
attemps = 0;
while (true)
{
int enq {5};
QByteArray bytes;
bytes.setNum(enq);
m_serial->write(bytes);
m_serial->waitForReadyRead(Max_sleep);
if (m_serial->bytesAvailable() !=0)
{
qDebug() << m_serial->bytesAvailable() ;
qDebug() << "connected" << m_serial->readAll();
break;
}
attemps += 1;
if (attemps == Max_attempts)
{
qDebug() << "no connection established";
break;
}
}
Kind regards,
Tibo
| According to this manual you are supposed to send a byte 0x05 but you are sending 0x35 (the character "5").
Use
bytes.append('\X05');
|
70,353,162 | 70,353,294 | VS Code on Mac Using C++ Debugger Not Working Properly | I am having an odd issue. I am working in C++ and I have coderunner installed and the basic C/C++ extension from Microsoft, but I am having an issue with my debugger.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers{10,20,30,40,50};
for(int i = 0; i < numbers.size(); i++)
{
cout << numbers[i] << endl;
}
return 0;
}
At the moment hit Run Code it runes just fine displaying the output I was expecting, but when I run the debugger I choose g++. This is what displays in the debug console:
But I still have a problem listed as:
vec.cpp:7:24: error: expected ';' at end of declaration
vector<int> numbers{10,20,30,40,50};
^
;
1 error generated.
Build finished with error(s).
It seems to be running an older version of C++, but my configurations are as list
"C_Cpp_Runner.cCompilerPath": "clang",
"C_Cpp_Runner.cppCompilerPath": "clang++",
"C_Cpp_Runner.cppStandard": "c++17",
"C_Cpp_Runner.cStandard": "c17",
"C_Cpp_Runner.debuggerPath": "lldb",
"C_Cpp.default.cppStandard": "c++17",
"C_Cpp.default.cStandard": "c17",
// "liveServer.settings.CustomBrowser": "chrome",
"code-runner.executorMap":{
"cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
}
Any ideas on why this would happen? Really confused why it would execute in the debug console, but not in the debugger. My compilers, g++ and clang++ are both up to date.
| If the compiler supports C++11 standards then vector<int> numbers{1, 2, 3}; can be used.
You should not get this error when you try the following usage:
std::vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
numbers.push_back(40);
numbers.push_back(50);
If you are using Clang compiler you should use the following command to compile:
clang++ -std=c++11 -stdlib=libc++ vec.cpp
You can learn about the clang++ command's options by reading the "Clang Command Line Reference".
|
70,353,631 | 70,353,803 | Rabin Karp Algorithm Negative Hash | I have this Rabin Karp implementation. Now the only thing I'm doing for rolling hash is subtract power*source[i] from the sourceHash. power is 31^target.size()-1 % mod
But I can't understand why we're adding mod to sourceHash when it becomes negative. I have tried adding other values but it doesn't work and it only works when we add mod. Why is this? Is there a specific reason why we're adding mod and not anything else (like a random big number for example).
int rbk(string source, string target){
int m = target.size();
int n = source.size();
int mod = 128;
int prime = 11;
int power = 1;
int targetHash = 0, sourceHash = 0;
for(int i = 0; i < m - 1; i++){
power =(power*prime) % mod;
}
for(int i = 0; i < target.size(); i++){
sourceHash = (sourceHash*prime + source[i]) % mod;
targetHash = (targetHash*prime + target[i]) % mod;
}
for(int i = 0; i < n-m+1; i++){
if(targetHash == sourceHash){
bool flag = true;
for(int j = 0; j < m; j++){
if(source[i+j] != target[j]){
flag = false;
break;
}
}
if(flag){
return 1;
}
}
if(i < n-m){
sourceHash = (prime*(sourceHash - source[i]*power) + source[i+m]) % mod;
if(sourceHash < 0){
sourceHash += mod;
}
}
}
return -1;
}
| When using modulo arithmetics (mod n) we have just n distinct numbers: 0, 1, 2, ..., n - 1.
All the other numbers which out of 0 .. n - 1 are equal to some number in 0 .. n - 1:
-n ~ 0
-n + 1 ~ 1
-n + 2 ~ 2
...
-2 ~ n - 2
-1 ~ n - 1
or
n ~ 0
n + 1 ~ 1
n + 2 ~ 2
...
2 * n ~ 0
2 * n + 1 ~ 0
In general case A ~ B if and only if (A - B) % n = 0 (here % stands for remainder).
When implementing Rabin Karp algorithm we can have two potential problems:
Hash can be too large, we can face integer overflow
Negative remainder can be implemented in different way on different compilers: -5 % 3 == -2 == 1
To deal with both problems, we can normalize remainder and operate with numbers within safe 0 .. n - 1 range only.
For arbitrary value A we can put
A = (A % n + n) % n;
|
70,353,963 | 70,365,820 | CMake - Copy specific files in custom target | i want to copy specific files for code coverage from sub directories, which are generated during the build process via custom target.
Is there a possibility, to do a recursive copy via add_custom_target and COMMAND, e.g.:
add_custom_target(copyFiles
COMMAND ${CMAKE_COMMAND} -E copy **/*.gcda ./
DEPENDS ${TARGET_NAME}
)
| Your custom target may run a CMake script (e.g., ${CMAKE_COMMAND} -P find_and_copy.cmake) which is going to perform file(GLOB_RECURSE...) and then do file(COPY...) on found files.
|
70,354,413 | 70,355,580 | Automatic template parameter deduction in unique_ptr and make_unique | Why do I get automatic template parameter deduction if I call class constructor directly but I do not get it in std::unique_ptr and std::make_unique? Here is an example:
#include <memory>
template <class T>
class C
{
public:
C(const T * const t_) : t(t_) {}
~C(void) { delete t; }
private:
const T * const t;
};
Example 1 (works):
int main(void)
{
const int * const t = new int;
auto * const c = new C(t);
return 0;
}
Example 2 (does not compile):
int main(void)
{
const int * const t = new int;
auto * const c = new C(t);
std::unique_ptr p(c); // class template argument deduction failed
return 0;
}
Example 3 (works):
int main(void)
{
const int * const t = new int;
const auto c = std::make_unique<C<int>>(t);
return 0;
}
Example 4 (does not compile):
int main(void)
{
const int * const t = new int;
// no matching function for call to ‘make_unique<template<class T> class C>(const int* const&)
const auto c = std::make_unique<C>(t);
return 0;
}
The code was compiled with g++ -std=c++17 (gcc-11.2.0).
What is the problem in examples 2 and 4? How can one fix them?
Thank you very much for your help!
| This is one way to solve it:
template <class T>
auto MakeUnique(T t)
{ return std::unique_ptr<std::remove_reference_t<decltype(*t)>>(t); }
int main(void)
{
const int * const t = new int;
auto * const c = new C(t);
auto p = MakeUnique(c);
return 0;
}
|
70,354,647 | 70,354,906 | What is meant by the statement that std::declval cannot be called? | On the cppreference-page for std::declval it says the following:
Return value
Cannot be called and thus never returns a value.
What does this mean? Surely we call it when we use it?
struct Foo { int func(){} };
decltype(std::declval<Foo>().func()) integer;
/* ^
| */
| The program is ill-formed if std::declval<T> is odr-used. However, cppreference tries to phrase this in a way that most users will find easier to understand.
A call to a function, or taking the address of the function, will normally odr-use that function. However, this is only the case if the call/address is actually evaluated. Thus, it is legal to call std::declval<T> as long as the call isn't evaluated. (Note that it's not enough merely to prove that the call will never occur at runtime. Rather, the call must occur in certain types of contexts in which the rules of the language prevent it from being evaluated. Therefore, the compiler can always check this condition.)
decltype does not evaluate its operand, so it is usually legal to place a call to std::declval<T> inside decltype. However, there are some situations where parts of the operand are evaluated anyway. For example, decltype(std::array<int, std::declval<int>()>) won't compile, because it will try to evaluate std::declval<int>() in order to get the size of the array.
|
70,355,069 | 70,355,738 | synchronization primitives: Equal latencies between atomics and mutex lock | I'm trying to improve my understanding of synchronization primitives in C++. I've measured latencies of various concurrent operations, such as:
For a raw std::mutex, the time between .unlock() and the return of .lock()
For a std::condition_variable, the time between .notify_one() and the return of .wait()
For a std::binary_semaphore, the time between .release() and .acquire()
For a std::atomic_flag, the time from .clear() and .notify_one() to .wait() as well as from .test_and_set() and .notify_one() to .wait()
All of these latencies are identical (~4µs-15µs). After digging a bit I found that semaphores are implemented with an atomic, and condition_variables boil down to a mutex. So it boils down to atomics vs mutex. When stepping into the relevant functions (on windows/MSVC), I found that atomics use WaitOnAddress/WakeByAddress while mutex uses SRW locks (AcquireSRWLockExclusive).
Naively I would have assumed atomics (especially atomic_flag) to have the best latency characteristics of all since they're so limited in what they do. So my questions:
Why are they equally fast? Might be my limited testing.
What are the differences between WaitOnAddress/WakeByAddress and SRW locks? They're both limited to a single process I think. I only found this article on WaitOnAddress, but it barely touches on differences to SRW locks.
| In an uncontended state an SRWLock is just an atomic int. So it's unsurprising that it performs the same as an atomic.
You should see very different timings once you introduce some contention in your tests.
An SRWLock is essentially a Windows version of a futex - a synchronization primitive that remains fully in user-space until a contention occurs.
WaitOnAddress / WakeByAddress and SRWLock are very similar internally, but the use-case is different - SRWLock directly implements a mutex/shared_mutex and WaitOnAddress / WakeByAddress are more useful for condition_variable.
|
70,355,294 | 70,355,423 | Seg Fault with Binary Heap Class when running on Linux, Insert Heap problems | I have implemented a binary heap class in C++ for school. I am having trouble with the program running on the school Linux server. My code outputs 100% correctly on my Mac. It appears to SegFault after the first line of code is printed from the main.cpp. I have tried using GDB and haven't been able to pin point the issue. Running GDB gives me the following issue: Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7ae8d68 in std::string::assign(std::string const&). Any help trying to correct this would be truly appreciated.
EDIT:
I figured out it was the insert function causing the issues: I have updated the function to this:
UPDATED Insert Function:
template <class typ>
void Heap<typ>::insert(typ k) {
if (size == 0) {
size = size + 1;
heap[size] = k;
return;
}
if (size == cap-1) {
cap = cap * 2;
typ *tempHeap = new typ [cap];
for (int i = 1; i <= size; i++)
tempHeap[i] = heap[i];
delete [] heap;
heap = tempHeap;
}
size = size + 1;
heap[size] = k; // insert item at end of heap
int i = size; // set i to size
while (i != 1 && heap[parent(i)] > heap[i]) { // move up to parents until heap property is restored all the way to the root
swapKeys(&heap[parent(i)], &heap[i]); // swap items
i = parent(i); // set i to parent of i
}
}
This fixes the segfault that was happening and correctly outputs the heap.
| When inserting your first element you change cap from 0 to cap * 2, this is still 0 causing the subsequent heap[size] = k to have undefined behaviour. You should also presumably at this point also update cap to the new size of your array.
Your next bug is that you do:
size = size + 1; // update size
heap[size] = k; // insert item at end of heap
Before this size could be equal to cap - 1, after incrementing it size then becomes cap causing heap[size] to have undefined behaviour.
The comment on this line doesn't match the code suggesting another bug?
int i = size; // set i to one less than size
I'm not sure of the intended behaviour of your program but the following code at least doesn't crash any more:
template <class typ>
void Heap<typ>::insert(typ k) {
if (size == cap) { //resize the array when full
cap = cap == 0 ? 2 : cap * 2;
typ* tempHeap = new typ[cap];
for (int i = 0; i < size; i++)
tempHeap[i] = heap[i];
delete[] heap;
heap = tempHeap;
}
heap[size] = k; // insert item at end of heap
int i = size; // set i to one less than size
size = size + 1; // update size
while (i != 1 && heap[parent(i)] > heap[i]) { // move up to parents until heap property is restored all the way to the root
swapKeys(&heap[parent(i)], &heap[i]); // swap items
i = parent(i); // set i to parent of i
}
}
On an unrelated note avoid #includeing cpp files, only header files should be included. Even if you rename Heap.cpp to Heap.h then you should also remove using namespace std;, this can lead to hard to track down compiler errors, see Why is "using namespace std;" considered bad practice?
|
70,355,767 | 70,355,897 | Binding a class method to a method of another class | I have two classes where one is logic and one is the model. After initializing both, I would like to bind a b.funB()to a.funA() where A a; B b;.
class A{
public:
bool funA() { doStuff(); }
}
class B{
public:
bool funB();
Template<class T>
void bindBtoA((bool (B::*fun2)(), bool (T::*fun1)(), T *t){
funB=std::bind( ?);
// (fun1, t), (&T::fun1, &t), (T::fun1, t), ... ?
}
}
How do I bind these correctly and get rid of "can't convert" errors (I did use typedef in my actual code)
An answer using lambda is acceptable. But, funB needs to be a callable as another engine needs to grab this (hint: Q_INVOKABLE), so using std::function for A::funA might not work for my case.
| You can achieve this via the magic of std::function, which would be hidden inside class B and type-erases the function to be called, thereby giving you the generality you seek.
Here's a fully-worked example:
#include <iostream>
#include <functional>
class A
{
public:
bool funA () { std::cout << "funA\n"; return true; }
};
class B
{
public:
bool funB ()
{
return f ();
}
template <class T>
void bindBtoA (bool (T::*fun1) (), T *t)
{
f = [t, fun1] { return (t->*fun1) (); };
}
private:
std::function <bool ()> f;
};
int main()
{
A a;
B b;
b.bindBtoA <A> (&A::funA, &a);
std::cout << b.funB ();
}
Live demo
I would think this would work with Q_INVOKABLE, but I don't actually know anything about it so you'd have to try it. But if it does work, it's a good way to do it.
Note: With the code as posted, you are responsible for keeping a alive for as long as b is alive. If you can't guarantee that, a better bet would be to use a std::shared_ptr instead. Or copy a inside bindBtoA if that is a practical solution for you (which I'm guessing it isn't).
|
70,355,938 | 70,356,755 | Thread pools not working with large number of tasks | I am trying to create a thread pool with native C++ and I am using the code listings from the book "C++ Concurrency in Action". The problem I have is that when I submit more work items than the number of threads, not all the work items get done. In the simple example below, I am trying to submit the runMe() function 200 times but the function is run only 8 times.
It seems like this shouldn't happen because in the code, the work_queue is separate from the work threads. Here is the code:
#include "iostream"
#include "ThreadPool.h"
void runMe()
{
cout << "testing" << endl;
}
int main(void)
{
thread_pool pool;
for (int i = 0; i < 200; i++)
{
std::function<void()> myFunction = [&] {runMe(); };
pool.submit(myFunction);
}
return 0;
}
ThreadPool.h class
#include <queue>
#include <future>
#include <list>
#include <functional>
#include <memory>
template<typename T>
class threadsafe_queue
{
private:
mutable std::mutex mut;
std::queue<T> data_queue;
std::condition_variable data_cond;
public:
threadsafe_queue() {}
void push(T new_value)
{
std::lock_guard<std::mutex> lk(mut);
data_queue.push(std::move(new_value));
data_cond.notify_one();
}
void wait_and_pop(T& value)
{
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
value = std::move(data_queue.front());
data_queue.pop();
}
bool try_pop(T& value)
{
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty())
return false;
value = std::move(data_queue.front());
data_queue.pop();
return true;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(mut);
return data_queue.empty();
}
int size()
{
return data_queue.size();
}
};
class join_threads
{
std::vector<std::thread>& threads;
public:
explicit join_threads(std::vector<std::thread>& threads_) : threads(threads_) {}
~join_threads()
{
for (unsigned long i = 0; i < threads.size(); i++)
{
if (threads[i].joinable())
{
threads[i].join();
}
}
}
};
class thread_pool
{
std::atomic_bool done;
threadsafe_queue<std::function<void()> > work_queue;
std::vector<std::thread> threads;
join_threads joiner;
void worker_thread()
{
while (!done)
{
std::function<void()> task;
if (work_queue.try_pop(task))
{
task();
numActiveThreads--;
}
else
{
std::this_thread::yield();
}
}
}
public:
int numActiveThreads;
thread_pool() : done(false), joiner(threads), numActiveThreads(0)
{
unsigned const thread_count = std::thread::hardware_concurrency();
try
{
for (unsigned i = 0; i < thread_count; i++)
{
threads.push_back(std::thread(&thread_pool::worker_thread, this));
}
}
catch (...)
{
done = true;
throw;
}
}
~thread_pool()
{
done = true;
}
template<typename FunctionType>
void submit(FunctionType f)
{
work_queue.push(std::function<void()>(f));
numActiveThreads++;
}
int size()
{
return work_queue.size();
}
bool isQueueEmpty()
{
return work_queue.empty();
}
};
Any idea on how to use the work_queue properly?
| When pool is destroyed at the end of main, your destructor sets done, making your worker threads exit.
You should make the destructor (or possibly main, if you want to make this optional) wait for the queue to drain before setting the flag.
|
70,355,988 | 70,356,036 | Is there a more idiomatic way to "insert or accumulate" into an unordered_map representing item counts? | Consider code like the following:
#include <iostream>
#include <unordered_map>
std::unordered_map<char, int> get_letter_frequencies(const std::string& str) {
std::unordered_map<char, int> freqs;
for (char ch : str) {
auto iter = freqs.find(ch);
if (iter == freqs.end()) {
freqs[ch] = 1;
} else {
iter->second++;
}
}
return freqs;
}
int main()
{
std::string str = "AABBDBCABDA";
auto freqs = get_letter_frequencies(str);
std::cout << freqs['B'] << "\n";
return 0;
}
which stores counts of letters in an unordered_map. My question is is there a snippet of terser/more idiomatic code with which i can replace
auto iter = freqs.find(ch);
if (iter == freqs.end()) {
freqs[ch] = 1;
} else {
iter->second++;
}
I could write a function insert_or_accumulate( ... ) but it seems like overkill.
| Just do:
for (char ch : str) {
++freqs[ch];
}
Just accessing freqs[ch] will create the key-value pairing if it's missing, using the default constructor (for int, that makes 0), and returns a reference to the value (new or existing), so ++freqs[ch] will increment existing values, and both create and increment missing values.
Note: I'm using prefix ++ by preference; it doesn't matter here since we're incrementing a primitive built-in type, but in C++ you want to get in the habit of using prefix increment by default, as classes overloading increment cannot implement postfix increment as efficiently as prefix increment (postfix requires making a copy of the instance, prefix can operate in place with no copies).
|
70,356,077 | 70,356,403 | Overriding multiplication operator for different datatypes | I created the following class
template<typename T, typename S>
class Polar{
private:
T rad;
S phi;
public:
Polar(T r, S p) : rad{r}, phi{p} {}
template<typename A, typename B>
friend std::ostream& operator<<(std::ostream&, const Polar<A,B>&);
And i want to override the multiplication function for different datatypes for example int and double like this
int main() {
Polar<int,int> p{2,3};
Polar<int,int> w{4,5};
Polar<float,double> z{6,7};
std::cout << p*w << std::endl;
std::cout << p*z << std::endl;
return 0;
}
I declared the function as a friend in Polar like this:
template<typename A, typename B, typename C, typename D>
friend auto operator*(const Polar<A,B>&, const Polar<C,D>&);
And then implemented it as the following:
template<typename A, typename B, typename C, typename D>
auto operator*(const Polar<A,B>& p, const Polar<C,D>& w) -> Polar<decltype(p.rad * w.rad),decltype(p.phi + w.phi)>
{
return Polar<decltype(p.rad * w.rad),decltype(p.phi + w.phi)> {(p.rad * w.rad),(p.phi + w.phi)};
}
But i am getting an error because of using auto before deduction.
I dont know how to get the return-type to work and i dont want to write a function for each possible combination.
Is there an easy way to tackle this?
| Using std::common_type_t> may serve here. It gives you "the common type among all types T..., that is the type all T... can be implicitly converted to."
[Demo]
#include <iostream> // cout
#include <ostream>
#include <type_traits> // common_type_t
template<typename T, typename S>
class Polar
{
public:
Polar(T r, S p) : rad{r}, phi{p} {}
template<typename A, typename B>
friend std::ostream& operator<<(std::ostream&, const Polar<A, B>&);
template<typename A, typename B, typename C, typename D>
friend auto operator*(const Polar<A, B>& p, const Polar<C, D>& w);
private:
T rad;
S phi;
};
template<typename A, typename B>
std::ostream& operator<<(std::ostream& os, const Polar<A, B>& p)
{
return os << "(" << p.rad << ", " << p.phi << ")";
}
template<typename A, typename B, typename C, typename D>
auto operator*(const Polar<A, B>& p, const Polar<C, D>& w)
{
using RT = std::common_type_t<A, C>;
using RS = std::common_type_t<B, D>;
return Polar<RT, RS>{p.rad * w.rad, p.phi + w.phi};
}
int main()
{
Polar<int, int> p{2, 3};
Polar<int, int> w{4, 5};
Polar<float, double> z{6.5, 7.5};
std::cout << p* w << std::endl;
std::cout << p*z << std::endl;
}
|
70,356,526 | 70,357,088 | asio: how to pass object from one io context to another | I'm trying to understand a bit better how async asio works.
I have the following code, where I'm calling async_read on a socket to read the next 10 bytes of data.
struct SocketReader {
void do_read_body()
{
asio::async_read(socket_,
asio::buffer(msg_, 10),
[this](asio::error_code ec, std::size_t length)
{
if (!ec)
{
//messages_to_work_on.emplace_back(msg_); // <-- I'm trying to send this msg_ instance to another io_context
do_read_body(); // call again
}
else
{
socket_.close();
}
});
}
std::vector<uint8_t> msg_;
asio::tcp::socket _socket;
}
These reads are done inside an io_context running in his own std::thread, where I'm collecting in a queue all messages read from the socket. So far so good.
I have also another "worker" class that just executes some work based on what is available in his queue:
struct Worker
{
asio::io_context& io_context_;
std::deque< std::vector<uint8_t> > queue;
Worker(asio::io_context& io_context)
: io_context_(io_context) {
asio::post(io_context_, [this]() {doWork();});
}
void doWork() {
if (!queue.empty())
{
// do some work with front()
queue.pop_front();
}
asio::post(io_context_, [this]() {doWork();});
}
};
That one is also executing in his own io_context, running in his own thread. So there is concurrency between the socket thread and the worker thread.
What is the correct way to post the data received from the socket, to the worker class ?
I'm thinking I should be able to call from the socket completion handler, something like:
asio::post(worker_io_context, [this]() {worker.queue.push_back(msg_)});
That way, I'm at least sure that the worker queue is not used concurently.
But I'm not sure if I'm allowed to post from one io_context to the other, and also if I won't create another race condition this way.
I also don't really understand where the memory for my message should be located, especially "in between" the transfer from one io_context to the other. Is it required I pass the message by value (since this.msg_ can be modified before the post handler is executed) ?
Thanks!
|
I should be able to call from the socket completion handler,
something like:
asio::post(worker_io_context, [this]() {worker.queue.push_back(msg_)});
Sure.
That way, I'm at least sure that the worker queue is not used concurently. But I'm not sure if I'm allowed to post from one io_context to the other,
io_context are not magic. They're basically cooperative task queues.
and also if I won't create another race condition this way.
I'm not going to sit here and pass a verdict without seeing your code (I might not want to read all of it anyways), but let me repeat: io_context are not magic. You can reason about them the way you already know how to in terms of threads, tasks and resources.
I also don't really understand where the memory for my message should be located, especially "in between" the transfer from one io_context to the other. Is it required I pass the message by value (since this.msg_ can be modified before the post handler is executed) ?
Yes. Indeed. Something like
post(worker_io_context, [this, msg=std::move(msg_)]() {worker.queue.push_back(std::move(msg)); });
If moving isn't cheap, there's the option of having a refcounted smart pointer (like shared_ptr). Consider making it smartpointer<T const> if you actually share ownership between threads.
Shower thought: maybe you can do without the "worker" queues. Since you're moving to reactor-style asynchrony (using Asio), you might focus on queueing the tasks, instead of the data. Reasons to not do that would include when you want to have priority queuing, load balancing/back pressure etc. [In principle all these can be implemented using custom executors, but I would stick to what I know before doing that.]
|
70,357,080 | 70,357,357 | Why template function with 'const' from left of parameter type is misbehaving against the rule of type deduction for pointer argument? | Consider this pseudo code for a type deduction case:
template<typename T> void f(ParamType param);
Call to function will be:f(expr);
According to type deduction case where ParamType is not a reference, pointer, nor a universal reference
(see S. Meyers "Effective Modern C++", p.14), but passed by value, to determine type T, one needs firstly
to ignore the reference and const part of 'expr' and then pattern-match exprs type to determine T.
The driver will be:
void PerformTest() {
int i = 42;
int* pI = &i;
f_const_left(pI);
f_non_template_left(pI);
f_const_right(pI);
f_non_template_right(pI);
}
Now consider these functions, which, using this deduction rule, are showing some counter-intuitive results while being called with pointer as an argument:
template<typename T> void f_const_left(const T t) {
// If 'expr' is 'int *' then, according to deduction rule for value parameter (Meyers p. 14),
// we need to get rid of '&' and 'const' in exp (if they exist) to determine T, thus T will be 'int *'.
// Hence, ParamType will be 'const int *'.
// From this it follows that:
// 1. This function is equivalent to function 'func(const int * t){}'
// 2. If ParamType is 'const int *' then we have non-const pointer to a const object,
// which means that we can change what pointer points to but cant change the value
// of pointer address using operator '*'
*t = 123;// compiler shows no error which is contradiction to ParamType being 'const int *'
t = nullptr; // compiler shows error that we cant assign to a variable that is const
// As we see, consequence 2. is not satisfied:
// T is straight opposite: instead of being 'const int *'
// T is 'int const *'.
// So, the question is:
// Why T is not 'const int*' if template function is f(const T t) for expr 'int *' ?
}
Consider consequence 1.:
Lets create an equivalent non-template function:
void f_non_template_left(const int* t) {
// 1. Can we change the value through pointer?
*t = 123; // ERROR: expression must be a modifiable lvalue
// 2. Can we change what pointers points to?
t = nullptr; // NO ERROR
// As we can see, with non-template function situation is quite opposite.
}
For for completeness of the experiment, lets also consider another pair of functions but with 'const' being placed from the right side of a T: one template function and its non-template equivalent:
template<typename T> void f_const_right(T const t) {
// For expr being 'int *' T will be 'int *' and ParamType will be 'int * const',
// which is definition of a constant pointer, which cant point to another address,
// but can be used to change value through '*' operator.
// Lets check it:
// Cant point to another address:
t = nullptr; // compiler shows error that we cant assign to a variable that is const
// Can be used to change its value:
*t = 123;
// So, as we see, in case of 'T const t' we get 'int * const' which is constant pointer, which
// is intuitive.
}
Finally, the non-template function with 'const' from the right side of type:
void f_non_template_right(int* const t) {
// 1. Can we change the value through pointer?
*t = 123; // No errors
// 2. Can we change what pointers points to?
t = nullptr; // ERROR: you cant assign to a variable that is const
// As we can see, this non-template function is equivalent to its template prototype
}
Can someone explain why there is such insonsistency between template and non-template functions ?
And why template function with 'const' on the left is behaving not according to the rule of deduction?
| (Referencing the C++14 Standard)
Your f_non_template_* functions aren't entirely correct.
Since T is a template parameter, it'll behave as if it is a unique type:
14.5.6.2 Partial ordering of function templates
(3) To produce the transformed template, for each type, non-type, or template template parameter (including
template parameter packs (14.5.3) thereof) synthesize a unique type, value, or class template respectively
and substitute it for each occurrence of that parameter in the function type of the template.
So to correctly test this your non-template functions would need to defined like this:
using TT = int*;
void f_non_template_left(const TT t) {
/* ... */
}
void f_non_template_right(TT const t) {
/* ... */
}
godbolt example
at which point you'll get exactly the same behaviour as with the templated functions.
Why it works that way
In this case T would be deduced to int*, which as a unique type would be a compound type:
3.9.2 Compound types
(1) Compound types can be constructed in the following ways:
[...]
(1.3) — pointers to void or objects or functions (including static members of classes) of a given type
[...]
And the cv-rules for compound types are as following:
3.9.3 CV-qualifiers
(1) A type mentioned in 3.9.1 and 3.9.2 [Compound Type] is a cv-unqualified type. Each type which is a cv-unqualified complete
or incomplete object type or is void (3.9) has three corresponding cv-qualified versions of its type: a constqualified version, a volatile-qualified version, and a const-volatile-qualified version.
(2) A compound type (3.9.2) is not cv-qualified by the cv-qualifiers (if any) of the types from which it is compounded. Any cv-qualifiers applied to an array type affect the array element type, not the array type (8.3.4).
So your cv-qualifiers for T in your template function refer to the top-level constness of the compound-type T in both your cases, so
template<typename T> void f_const_left(const T t);
template<typename T> void f_const_right(T const t);
are actually equivalent.
The only exception to this would be if T would be an array-type, in which case the cv-qualifier would apply to the elements of the array instead.
If you want to specify the constness of the pointed-to value, you could do it like this:
//const value
template<class T>
void fn(const T* value);
// const pointer
template<class T>
void fn(T* const value);
// const value + const pointer
template<class T>
void fn(const T* const value);
|
70,358,185 | 70,358,201 | C++: use string& and unique_ptr<SomeClass>& for map<string, unique_ptr<SomeClass>> | I have following string& and unique_ptr&
const FilePath& path; // given as parameter
auto key = path.BaseName().value();
auto value = make_unique<SomeClass>();
I would like to use these in the following map
map<string, unique_ptr<SomeClass>> myMap;
When I do the following,
myMap.emplace(key, value);
I get this error:
note: in instantiation of function template specialization 'std::map<std::string, std::unique_ptr<SomeClass>>::emplace<const std::string &, std::unique_ptr<SomeClass> &>' requested here
I think this means that I am trying to put string& and unique_ptr& where string and unique_ptr is needed.
Would there be a way to use &-variable to a non-&-parameter?
Full code:
map<string, unique_ptr<SomeClass>> myMap;
void function (const FilePath& path) {
auto key = path.BaseName().value();
auto value = make_unique<SomeClass>();
myMap.emplace(key, value);
}
| std::unique_ptr can't be copied, but only moved. You can use std::move to convert value to rvalue:
myMap.emplace(key, std::move(value));
|
70,358,592 | 70,359,022 | How to embed a DLL into a DLL? | I managed to create a program in C++ / Visual Studio 2010, 2017. And now I have to embed a DLL (B.dll) inside of another DLL (A.dll).
I succeed in executing another program (C.exe) that uses A.dll. But I don't know how to embed a DLL into a DLL.
Is it possible ? If it is possible, what should I do?
I have solutions for A.dll, B.dll, C.exe.
| If you truly want to embed B.dll inside of A.dll, you can define B.dll as a resource of A.dll via an .rc script in A.dll's project. Then you can use B.dll at runtime by first using (Find|Load|Lock)Resource() to access the bytes for B.dll's resource and writing them to a tempory file using (Create|Write)File() before then loading that file with LoadLibrary().
|
70,358,909 | 70,358,961 | a C++ template question: choose the unexpect function | I am writing my list like the std::list so I have functions like this:
template <typename _Tp>
class list {
public:
// ...
iterator insert(iterator __pos, const _Tp &__val) {
// ...
}
template <typename _InputIter>
iterator insert(iterator __pos, _InputIter __begin, _InputIter __end) {
if (__begin == __end) return __pos;
// here I use the *__begin... so ...
iterator __ret = insert(__pos, *__begin);
while (++__begin != __end) insert(__pos, *__begin);
return __ret;
}
iterator insert(iterator __pos, size_t __cnt, const _Tp &__val) {
// ...
}
}
this is the main function
int main() {
tinystd::list<int> mylist;
tinystd::list<int>::iterator it;
it = mylist.begin();
// error happens here
mylist.insert(it, 2, 20);
}
It seems like the compiler will choose the function template <typename _InputIter> iterator insert(iterator __pos, _InputIter __begin, _InputIter __end) and cause an error says that indirection requires pointer operand ('int' invalid)
I want to know why this happens and how to modify it.
Thank U so much ^^
| Because the 2nd insert wins in overload resolution; given mylist.insert(it, 2, 20); the template parameter _InputIter could be deduced as int and then it's an exact match. On the other hand, the 3rd insert requires an implicit conversion from int to size_t.
You can use std::input_iterator (since C++20) to specify that _InputIter must satisfy the requirements as an input iterator.
template <std::input_iterator _InputIter>
iterator insert(iterator __pos, _InputIter __begin, _InputIter __end) {
// ...
}
Before C++20 you can impose restrictions on _InputIter, e.g. must be usable with operator*.
template <typename _InputIter, std::void_t<decltype(*std::declval<_InputIter>())>* = nullptr>
iterator insert(iterator __pos, _InputIter __begin, _InputIter __end) {
// ...
}
|
70,359,086 | 70,363,014 | Boost read_json is not working with wptree from std::wstring | I have a simple code which is not working and I don't really know why... here it's:
std::wstring CDbFilterSerializer::DeserializeFromString(const std::wstring& jsonStr)
{
std::wistringstream ss{ jsonStr };
boost::property_tree::read_json(ss, m_root);
return m_root.data();
}
The problem here is that after calling m_root.read_json(...) the wptre object is empty. The return statement is an example, cause the real code after populating the wptree object, I call m_root.get("MyKey") to start reading values and this throw an exception cause the object is empty.
The json received as parameter is:
{
"type":{
"className":"NumericFilterSerializerHelper: NumericType => unsigned int, DbSerializer => class CDbFilterSerializerByNumericValue",
"description":""
},
"data":{
"int_number":"45"
}
}
Is there something wrong here?
| Yes. The assumptions are wrong. .data() returns the value at the root node, which is empty (since it's an object). You can print the entire m_tree to see:
Live On Coliru
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
struct CDbFilterSerializer {
std::wstring DeserializeFromString(const std::wstring& jsonStr);
boost::property_tree::wptree m_root;
};
std::wstring CDbFilterSerializer::DeserializeFromString(const std::wstring& jsonStr)
{
std::wistringstream ss{ jsonStr };
read_json(ss, m_root);
return m_root.data();
}
int main() {
CDbFilterSerializer obj;
obj.DeserializeFromString(LR"({
"type":{
"className":"NumericFilterSerializerHelper: NumericType => unsigned int, DbSerializer => class CDbFilterSerializerByNumericValue",
"description":""
},
"data":{
"int_number":"45"
}
})");
write_json(std::wcout, obj.m_root, true);
}
Which prints
{
"type": {
"className": "NumericFilterSerializerHelper: NumericType => unsigned int, DbSerializer => class CDbFilterSerializerByNumericVa
lue",
"description": ""
},
"data": {
"int_number": "45"
}
}
As you can see the object is not empty. You probably have the path misspelled (we can't tell because MyKey is not in your document).
SIDE NOTE
Do not abuse Property Tree for JSON "support". Instead use a JSON library! Boost JSON exists. Several others are freely available.
|
70,360,319 | 70,363,779 | Measure time for function-runtime in tests with compiler optimization in c++ | I want to measure the time a function I programmed takes when executed. While there are many threads on SO on how to measure time in c++, I did not find any that explains how to prevent the compiler optimization to clear away my function-call.
So right now I do something like:
bool testFunctionSpeed() {
auto input = loadInput();
auto start = std::chrono::high_resolution_clock::now();
for (int i; i < num_iterations; i++) {
auto result = function(input);
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
}
It appears to work right now, but I'm not sure if this is stable, because:
Doing this, the compiler can see that the result stored in "result" is not used outside of the loop's scope, so it might just optimize the code away (...right?).
I am aware that there are flags to not optimize the code, however I want to benchmark my code under "real" conditions! One way would be to randomly printf out parts of the result, however that does not seem to be a "correct" solution.
What is the right approach to this?
| To prevent compiler from optimizing away function calls just make input and output of that function a volatile variable.
Result is guaranteed to be computed and stored in volatile output variable on each loop run.
While volatile input will prevent optimizer from precomputing value of your function in advance, if you don't mark input as volatile then compiler may just write a constant to output result variable on each loop iteration.
Click Try it online! linke below to see program in action and also assembly listing.
Your code example with improvements is below:
Try it online!
#include <cmath>
#include <iostream>
#include <chrono>
int function(int x) {
return int(std::log2(x));
}
bool testFunctionSpeed() {
size_t const num_iterations = 1 << 20;
auto volatile input = 123;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < num_iterations; ++i) {
auto volatile result = function(input);
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(
end - start).count() / num_iterations;
std::cout << duration << " ns per iteration" << std::endl;
return true;
}
int main() {
testFunctionSpeed();
}
Output:
8 ns per iteration
|
70,360,621 | 70,360,765 | returning pointer to a function inline without typedef | I'm running into syntax errors with C++ where I have to return a pointer to a function inline.
struct Note{}
Observer.hpp
class Observer {
protected:
void (*notify)(Note *note); // should this be *(*notify...)?
public:
void (*(*getNoteMethod)())(Note *note);
};
Observer.cpp
void (*Observer::getNoteMethod())(Note*) { //error: non-static data member defined out-of-line
return this->notify;
}
I'm getting this error, error: non-static data member defined out-of-line
I'm new to C++ and attempting to define the return function signature correctly.
| The problem is the declaration syntax for the member function (which returns function pointer). Declare it as:
class Observer {
protected:
void (*notify)(Note *note);
public:
void (*getNoteMethod())(Note *note);
};
Better to declare the function pointer type in advance via using or typedef, which looks much clearer. E.g.
class Observer {
using function_pointer_type = void(*)(Note*); // the function pointer type
protected:
function_pointer_type notify; // the data member with function pointer type
public:
function_pointer_type getNoteMethod(); // the member function returns function pointer
};
// Out-of-class member function definition
Observer::function_pointer_type Observer::getNoteMethod() {
return this->notify;
}
|
70,360,837 | 70,361,032 | Build incremental std::string | I try to build an std::string in the form of "start:Pdc1;Pdc2;Pdc3;"
With following code I can build the repeated "Pdc" and the incremental string "123" but I'm unable to combine the two strings.
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>
int main()
{
std::ostringstream ss;
std::string hdr("start:");
std::fill_n(std::ostream_iterator<std::string>(ss), 3, "Pdc;");
hdr.append(ss.str());
std::string v("abc");
std::iota(v.begin(), v.end(), '1');
std::cout << hdr << std::endl;
std::cout << v << std::endl;
std::cout << "Expected output: start:Pdc1;Pdc2;Pdc3;" << std::endl;
return 0;
}
How can I build this string? Preferable without a while or for loop.
The expected output is: start:Pdc1;Pdc2;Pdc3;
| std::strings can be concatenated via their operator+ (or +=) and integers can be converted via std::to_string:
std::string res("start:");
for (int i=0;i<3;++i){
res += "Pdc" + std::to_string(i+1) + ";";
}
std::cout << res << "\n";
If you like you can use an algorithm instead of the handwritten loop, but it will still be a loop (your code has 2 loops, but only 1 is needed).
|
70,361,181 | 70,361,392 | Check if a string is a number without regex or try catch | I want to implement a simple is_number function that checks if it's an integer, float or an unsigned long int using this method:
bool isNumber(const std::string& str)
{
size_t idx = 0;
//Check if it's an integer
std::stoi(str,&idx);
if (idx == str.size())
return true;
//Check if it's a float
std::stof(str,&idx);
if (idx == str.size() || str[str.size()-1] == 'f' && idx == str.size()) //Cause I do have some float numbers ending with 'f' in the database
return true;
//Check if it's an unsigned long int
std::stoul(str,&idx);
if (idx == str.size())
return true;
return false;
}
But if I test it with a pure string like "test" or "nan", it will throw an error because I'm trying to change a pure string to an integer.
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
However if I test it with "0nan" for example, stoi or the others will retrieve the first number and assign the index position of the first found number to the idx variable.
Is it possible to find a workaround for pure strings like "nan" or any other?
Or is there a better method to implement this without regex or try-catch?
| std::stoi throws when it fails. Instead of using C i/o you can use C++ streams, try to read from the stream and check if there is something left in the stream:
#include <string>
#include <sstream>
#include <iostream>
enum Number {Float,Signed,Unsigned,NotANumber};
template <typename T>
bool is_only_a(const std::string& str){
std::stringstream ss(str);
T x;
return (ss >> x && ss.rdbuf()->in_avail() ==0);
}
Number isNumber(const std::string& str)
{
size_t idx = 0;
if (is_only_a<unsigned long>(str)) return Unsigned;
else if (is_only_a<int>(str)) return Signed;
else if (is_only_a<float>(str)) return Float;
return NotANumber;
}
int main() {
std::cout << isNumber("1.2") << "\n";
std::cout << isNumber("12") << "\n";
std::cout << isNumber("-12") << "\n";
std::cout << isNumber("asd") << "\n";
std::cout << isNumber("nan") << "\n";
}
Order is important, because 12 could be a float as well.
|
70,361,272 | 70,365,618 | Spiral matrix, i am getting extra elements while printing spiral matrix order. Don't know why? | // printing in spiral order matrix
#include<iostream>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int arr[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>arr[i][j];
}
}
// print
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// spiral print
int row_start=0,row_end=n-1,col_start=0,col_end=m-1;
while(row_start<=row_end && col_start<=col_end){
for(int j=col_start; j<=col_end; j++){
cout<<arr[row_start][j]<<" ";
}
row_start++;
for(int i=row_start; i<=row_end; i++){
cout<<arr[i][col_end]<<" ";
}
col_end--;
for(int j=col_end; j>=col_start; j--){
cout<<arr[row_end][j]<<" ";
}
row_end--;
for(int i=row_end; i>=row_start; i--){
cout<<arr[i][col_start]<<" ";
}
col_start++;
}
return 0;
}
My output is:
PS C:\Users\anmol\Desktop\c++projectwork> ./a
3 4
1 2 3 4 5 6 7 8 9 0 1 2
1 2 3 4
5 6 7 8
9 0 1 2
1 2 3 4 8 2 1 0 9 5 6 7 6
I am getting an extra '6' at the end.
which is not required however this type of problem only come when matrix is rectangular.
But code works fine for square matrix.
Please tell me where i went wrong..
| Suppose you have a below matrix. Let's dry run your code on below example.
1 2 3 4
5 6 7 8
9 10 11 12
Dry Run
1st for loop: prints 1 2 3 4 row_start=1,row_end=2,col_start=0,col_end=3
2nd for loop: prints 8 12 row_start=1,row_end=2,col_start=0,col_end=2
3rd for loop: prints 11 10 9 row_start=1,row_end=1,col_start=0,col_end=2
4th for loop: prints 5 row_start=1,row_end=1,col_start=1,col_end=2
All condition of while loop are true 2nd Iteration of while loop:
1st for loop: prints 6 7 row_start=2,row_end=1,col_start=1,col_end=2
2nd for loop: won't do anything row_start=2,row_end=1,col_start=1,col_end=1
3rd for loop: prints 6
DO you see the problem?
you should run 3rd for loop only if
"row_start < row_end"
similarly you should check for
"col_start<col_end"
before running the 4th loop
|
70,361,687 | 70,361,948 | Having Trouble with Inheritance in C++ | I'm having a little trouble with inheritance.
Main.cpp
#include <iostream>
#include "Shapeclass.h"
using namespace std;
int main() {
int shapecount, shapetype[200],i,height[200], width[200];
string name;
cout << "AREA CALULATOR";
cout << "Enter Your Name ";
cin >> name;
cout << "Enter the amount of Shapes you want to calculate Area of: ";
cin >> shapecount;
Shape *p1[200];
cout << "Enter 1 for Circle Enter 2 for Rectangle and 3 for Triangle";
for ( i = 0; i < shapecount; i++)
{
cin >> shapetype[i];
}
for ( i = 0; i < shapecount; i++)
{
if (shapetype[i]==1)
{
cout << "Enter Radius of circle";
cin >> width[i];
p1[i] = new sphere(width[i]);
}
else if (shapetype[i] == 2) {
cout << "Enter width of rectangle";
cin >> width[i];
cout << "Enter height of rectangle";
cin >> height[i];
}
else if (shapetype[i] == 3) {
cout << "Enter base of triangle";
cin >> width[i];
cout << "Enter height of triangle";
cin >> height[i];
}
}
}
Shapeclass.h
#include <iostream>
using namespace std;
class Shape
{
protected:
double area ;
int height, width;
string nama;
void virtual calculate() = 0;
public:
void display() {
calculate();
}
private:
};
class sphere :public Shape {
void calculate(double height, double width) {
}
};
class rectangle :public Shape {
public:
rectangle(int width1, int height1)
{
width = width1;
height = height1;
}
void calculate(double height, double width) {
area = height * width;
}
};
class triangle :public Shape {
public:
triangle(int width1, int height1)
{
width = width1;
height = height1;
}
void calculate(double height, double width) {
area = height * width*0.5;
}
};
class sphere :public Shape {
public:
sphere(int width1)
{
width = width1;
}
void calculate(double width) {
area = width*width*3.14 ;
}
};
I have no idea why it says object of abstract class type "sphere" is not allowed. Specifically line 42.
I'm trying to initialize pointer array objects but it doesn't want to work.
I'm trying to send the width of the sphere to the class but I can't initialize the value of width with the pointer array. To be more specific.
| The Shape::calculate() method is declared as pure virtual:
void virtual calculate() = 0;
So, it must be overloaded in derived classes to have them considered by the compiler as concrete ones you'd able to call.
In your case, the overloaded method would be responsible to determine the area of each shape according to its kind and update the instance property.
for example:
void rectangle::calculate() {
area = height * width;
}
and
void triangle::calculate() {
area = height * width * 0.5;
}
would compute the right area for given shapes.
Shape* s1 = new triangle(w, h);
s1->calculate(); // effective call to triangle::calculate()
Shape* s2 = new rectangle(w, h);
s2->calculate(); // effective call to rectangle::calculate()
|
70,362,057 | 70,362,153 | Allocation of incomplete type error in QT c++ | I am trying to implement my very first project of a mediaplayer using QT c ++ , currently i have this issue where it says "error: allocation of incomplete type 'Ui::About_display'"
.h
#ifndef PLAYERFRAME_H
#define PLAYERFRAME_H
#include <QDialog>
namespace Ui {
class About_display;
}
class About_display : public QDialog
{
Q_OBJECT
public:
explicit About_display(QWidget *parent = nullptr);
~About_display();
private:
Ui::About_display *ui;
};
#endif // PLAYERFRAME_H
.cpp
include "playerframe.h"
#include "ui_about_display.h"
About_display::About_display(QWidget *parent) :
QDialog(parent),
ui(new Ui::About_display) ..> where error occurs
{
ui->setupUi(this);
}
About_display::~About_display()
{
delete ui;
}
Thank you for the help !!
| You are declaring class Ui::About_display; but defining class About_display. Make sure the class definition is in the Ui namespace:
#ifndef PLAYERFRAME_H
#define PLAYERFRAME_H
#include <QDialog>
namespace Ui {
class About_display : public QDialog
{
Q_OBJECT
public:
explicit About_display(QWidget *parent = nullptr);
~About_display();
private:
About_display *ui; // `Ui::` not needed
};
} // namespace Ui
#endif // PLAYERFRAME_H
And also in the .cpp file:
#include "playerframe.h"
#include "ui_about_display.h"
namespace Ui {
About_display::About_display(QWidget *parent) :
QDialog(parent),
ui(new About_display) // `Ui::` not needed
{
ui->setupUi(this);
}
About_display::~About_display()
{
delete ui;
}
} // namespace Ui
Note: While placing the class definition and implementation of the member functions in the Ui namespace will make it compile, you are recursively creating a new About_display for every About_display you create. I suspect you should use the QDialogs constructor and remove the About_display *ui; member.
Header:
#ifndef PLAYERFRAME_H
#define PLAYERFRAME_H
#include <QDialog>
namespace Ui {
class About_display : public QDialog
{
Q_OBJECT
public:
using QDialog::QDialog; // add the QDialog constructors
};
#endif
The member functions you've defined in your original code are already covered by QDialog so with what you've shown, you don't need to implement them in the .cpp file.
|
70,362,195 | 70,376,503 | GetAsyncKeyState() returns wrong value for VK_LCONTROL parameter when right alt is held down | I wonder if I did something incorrectly, or if this is a Windows bug. Here is my code:
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
bool quit = false;
while (!quit)
{
bool rightAltMod = GetAsyncKeyState(VK_RMENU);
bool leftControlMod = GetAsyncKeyState(VK_LCONTROL);
//press and hold right alt to see the bug
cout << "rAlt pressed " << rightAltMod << ", lCtrl pressed " << leftControlMod << "\n";
quit = GetAsyncKeyState(VK_ESCAPE);
}
return 0;
}
The bug(?) is when I press and hold Right-Alt, GetAsyncKeyState() also detects it as Left-Ctrl.
If this is a bug, is there any workaround for it?
I have no ideas except direct access to keyboard buffer using assembler.
I'm developing on Windows 10 x64 21H1.
| I have found what causes the behavior - it is related to keyboard layout. The bug occurrs on Polish-programmers layout, after switching to EN-US layout it works fine.
Well, still I'll need to solve the problem, but for that I'll create a separate question.
|
70,362,365 | 70,376,691 | How to fix memory leak when passing object from C# COM library to a C++ application | I have a C++ MFC application which consumes C# COM wrapper. The issue is whenever I invoke a function inside wrapper, I am experiencing memory leak. Can anyone explain how to clean up the allocations that are made within the C# COM wrapper.
Below code blocks mimic what I was trying to do, can anyone provide me the references/rightway to pass the structure object/ clean up the memory allocation
C# wrapper exposed as COM
using System;
using System.Runtime.InteropServices;
namespace ManagedLib
{
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct comstructure
{
public string[] m_strName;
public UInt32[] m_nEventCategory;
}
[Guid("4BC57FAB-ABB8-4b93-A0BC-2FD3D5312CA8")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[ComVisible(true)]
public interface ITest
{
comstructure TestBool();
}
[Guid("A7A5C4C9-F4DA-4CD3-8D01-F7F42512ED04")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class Test : ITest
{
public comstructure TestBool( )
{
comstructure testvar = new comstructure();
testvar.m_strName = new string[100000];
testvar.m_nEventCategory = new UInt32[100000];
return testvar;
}
}
}
C++ code
#include <iostream>
#include <afx.h>
#include <afxwin.h>
#include <afxext.h>
#include <afxdtctl.h>
#include "windows.h"
#include "psapi.h"
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>
#endif // _AFX_NO_AFXCMN_SUPPORT
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
#include <atlbase.h>
#import "..\comlibrary\bin\Debug\comlibrary.tlb"
comlibrary::ITest* obj;
class mleak
{
public:
void leakmemory()
{
comlibrary::comstructure v2;
v2 = obj->TestBool();
}
};
int main()
{
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
CLSID clsid;
HRESULT hResult = ::CLSIDFromProgID(L"ManagedLib.Test", &clsid);
hResult = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
__uuidof(comlibrary::ITest), (void**)&obj);
std::cout << hResult;
if (FAILED(hResult))
{
std::cout << "COM import failed!\n";
}
mleak m1;
for (int i = 0; i < 600; i++)
{
m1.leakmemory();
Sleep(100);
}
return 0;
}
| You should release memory if it's allocated and no-one else frees it, obviously. Here, the allocated memory is the .NET's string[] and uint[] which are represented as SAFEARRAY* in the native world.
But, long story short: you can't really use structs as return type for COM methods. It's causes not only copy semantics issues (who owns struct's field memory, etc.), but in general, it won't even work depending on struct size, etc. lots of trouble, COM methods should return 32/64 bit-sized variables (or void).
So you can fix this using COM objects instead of structs. For example:
[ComVisible(true)]
public interface IOther
{
string[] Names { get; set; }
uint[] EventCategories { get; set; }
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Other : IOther
{
public string[] Names { get; set; }
public uint[] EventCategories { get; set; }
}
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITest
{
Other TestOther();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Test : ITest
{
public Other TestOther()
{
var other = new Other();
other.Names = new string[100000];
other.EventCategories = new UInt32[100000];
return other;
}
}
and in C++ side:
#include "windows.h"
#import "..\ManagedLib\bin\Debug\ManagedLib.tlb"
using namespace ManagedLib;
int main()
{
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
{
ITestPtr test; // see https://stackoverflow.com/a/16382024/403671
auto hr = test.CreateInstance(__uuidof(Test));
if (SUCCEEDED(hr))
{
IOtherPtr other(test->TestOther());
auto names = other->Names;
// do what you want with safe array here
// but in the end, make sure you destroy it
SafeArrayDestroy(names);
}
}
CoUninitialize();
return 0;
}
Note: you can also use CComSafeArray to ease SAFEARRAY programming.
|
70,362,661 | 70,364,008 | The program doesn't give any output on VS Code if I use 'const int ' and assign it a big value like 1e6 | #include <bits/stdc++.h>
using namespace std ;
int main () {
int n ;
cin >> n ;
int a [n] ;
for ( int i = 0 ; i < n ; i++ ) {
cin >> a [i] ;
}
const int N = 1e6 + 2 ; // This is where the problem is...
bool check [N] ;
for ( int i = 0 ; i < N ; i++ ) {
check [i] == 0 ;
}
for ( int i = 0 ; i < N ; i++ ) {
if ( a [i] >= 0 ) {
check [a[i]] = 1 ;
}
}
int ans = -1 ;
for ( int i = 0 ; i < N ; i++ ) {
if ( check [i]==0 ) {
ans = i ;
break;
}
}
cout << ans ;
return 0 ;
}
When I run the above program in the VS Code terminal I get no output... :
PS C:\Users\LENOVO\Desktop\C++ Programs> cd "c:\Users\LENOVO\Desktop\C++ Programs\" ; if ($?) { g++ smallest_positive_missing_number.cpp -o smallest_positive_missing_number } ; if ($?) { .\smallest_positive_missing_number }
6
0 -9 1 3 -4 5
PS C:\Users\LENOVO\Desktop\C++ Programs>
| First, stop using VLA because it is NOT supported in c++ standard. Use vector or new instead.
int *a = new int[n];
bool *check = new bool[N];
And use them just like a normal array.
As for your problem, it is clearly caused by VLA with big size, and it will run perfectly once you switch to new or vector.
Edit:
However, like the comment below said, the array cited this problem is not VLA. They just act the same and mess up your stack.
|
70,362,713 | 70,362,794 | map.erase(it) causes double free when it comes from map.find in template | I am trying to run the following:
#include <algorithm>
#include <iostream>
#include <map>
template <class T>
auto first(T t){
return t.find(0);
}
void f(bool b){
std::map<int, int> map;
map.insert({0, 0});
auto it = b ? first(map) : map.find(0);
std::cout << "About to erase" << std::endl;
map.erase(it); // Line 15
}
int main(void){
f(false);
std::cout << "Exited g(false) sucessfully" << std::endl;
f(true); // Line 21
std::cout << "Exited g(true) sucessfully" << std::endl;
}
The function f should:
Initalise a map
Add an element to that map
Get an iterator to that element
Erase that element
However, compiling with g++ -g (g++ version 9.3.0) prints:
About to erase
Exited g(false) sucessfully
About to erase
free(): double free detected in tcache 2
Aborted
so when it = map.find(0) everything works as expected, but when it = first(map), calling map.erase(it) generates a double free error.
Running this with gdb gives the backtrace:
(gdb) bt
#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1 0x00007ffff77ec859 in __GI_abort () at abort.c:79
#2 0x00007ffff78573ee in __libc_message (action=action@entry=do_abort,
fmt=fmt@entry=0x7ffff7981285 "%s\n") at ../sysdeps/posix/libc_fatal.c:155
#3 0x00007ffff785f47c in malloc_printerr (
str=str@entry=0x7ffff79835d0 "free(): double free detected in tcache 2")
at malloc.c:5347
#4 0x00007ffff78610ed in _int_free (av=0x7ffff79b2b80 <main_arena>, p=0x55555556d2e0,
have_lock=0) at malloc.c:4201
#5 0x0000555555556b62 in __gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<int const, int> > >::deallocate (this=0x7fffffffe120, __p=0x55555556d2f0)
at /usr/include/c++/9/ext/new_allocator.h:128
#6 0x00005555555569d1 in std::allocator_traits<std::allocator<std::_Rb_tree_node<std::pair<int const, int> > > >::deallocate (__a=..., __p=0x55555556d2f0, __n=1)
at /usr/include/c++/9/bits/alloc_traits.h:470
#7 0x000055555555655b in std::_Rb_tree<int, std::pair<int const, int>, std::_Select1st<std::pair<int const, int> >, std::less<int>, std::allocator<std::pair<int const, int> > >::_M_put_node (this=0x7fffffffe120, __p=0x55555556d2f0)
at /usr/include/c++/9/bits/stl_tree.h:584
#8 0x0000555555555e0c in std::_Rb_tree<int, std::pair<int const, int>, std::_Select1st<std::pair<int const, int> >, std::less<int>, std::allocator<std::pair<int const, int> > >::_M_drop_node (this=0x7fffffffe120, __p=0x55555556d2f0)
at /usr/include/c++/9/bits/stl_tree.h:651
#9 0x00005555555564c8 in std::_Rb_tree<int, std::pair<int const, int>, std::_Select1st<std::pair<int const, int> >, std::less<int>, std::allocator<std::pair<int const, int> > >::_M_erase_aux (this=0x7fffffffe120, __position=...) at /usr/include/c++/9/bits/stl_tree.h:2511
#10 0x0000555555555d7b in std::_Rb_tree<int, std::pair<int const, int>, std::_Select1st<std::pair<int const, int> >, std::less<int>, std::allocator<std::pair<int const, int> > >::erase[abi:cxx11](std::_Rb_tree_iterator<std::pair<int const, int> >) (this=0x7fffffffe120,
__position=...) at /usr/include/c++/9/bits/stl_tree.h:1220
#11 0x0000555555555955 in std::map<int, int, std::less<int>, std::allocator<std::pair<int const, int> > >::erase[abi:cxx11](std::_Rb_tree_iterator<std::pair<int const, int> >) (
this=0x7fffffffe120, __position=...) at /usr/include/c++/9/bits/stl_map.h:1037
#12 0x000055555555544c in f (b=true) at test.cpp:15
#13 0x00005555555554f9 in main () at test.cpp:21
What is causing this problem, and how should I change the template to fix it?
| template <class T>
auto first(T t){
return t.find(0);
}
The first function is pass by value, so when t.find(0) is returned, the local variable t will be destroyed, and it will be initialized by a dangling iterator that points to the destroyed container.
You should pass by reference:
template <class T>
auto first(T& t){
return t.find(0);
}
|
70,362,802 | 70,363,298 | Using type in template class of derived template class | Try to implement the CRTP pattern. Therefore I created two template classes. With the first draft of only one template class PDerived everything is fine. But for my purpose in a bigger project I need two template classes. Which results in an error: All types of the PDerivced class are not found. But I have no idear why. In the following the is a minimalistic example.
In this example myType can not be found? If TDerived is no template class everything is fine. Is there some namespace needed?
#include <iostream>
template< typename PDerived >
class TBase
{
public:
using myType = uint8_t;
void Foo( void )
{
static_cast< PDerived* > ( this )->Bar();
}
};
template< typename Derived > class TDerived : public TBase< TDerived<Derived> >
{
friend class TBase< TDerived > ;
protected:
void Bar( void )
{
std::cout << "in Bar" << std::endl;
}
private:
myType myVariable;
};
int main( void )
{
TDerived<uint8_t> lD;
lD.Foo();
return ( 0 );
}
Error message:
error: 'myType' does not name a type
| If you want to refer to some templated stuff of your base class, you have to give the compiler a hint how to find it.
Change your line:
myType myVariable;
to
TBase< TDerived<Derived> >::myType myVariable;
The underlying problem is, that unqualified names are not resolved during this stage until the template is fully defined. You get the same problem if you try to call member functions or variables from your base class. In this case you can simply use this->MemberFunc().
|
70,362,895 | 70,363,394 | Make a function that autodetects when unique | I need to have a function in c++ that gets an element from a vector of strings as soon as the input is unique.
For example, my vector contains {"DELETE", "HELP", "GO FORWARD", "GO BACKWARDS"}.
If my input is then "H", the function should output "HELP" If the input is "H 55", it should ignore the 55 and still output "HELP".
However, when I add a new element "HELLO" to my vector, it should return "NOT UNIQUE".
I already tried a bunch of things, but I am not really getting anywhere.
I think a 2 dimensional vector would be a possible solution, but I have not been able to make it work:
["DELETE", "D"]
["DELETE", "DE"]
["DELETE", "DEL"]
["DELETE", "DELE"]
["DELETE", "DELET"]
["DELETE", "DELETE"]
["HELP", "HELP"]
["HELLO", "HELL"]
["HELLO", "HELLO"]
...
|
Make a function that autodetects when unique
One possible way of doing this is as shown below:
#include <iostream>
#include <vector>
#include <string>
std::string checkUnique(const std::string& searchString, const std::vector<std::string>& inputVector)
{
int count = 0;
std::string foundString;
for(const std::string &element: inputVector)
{
if(element.at(0) == searchString.at(0))
{
foundString = element;
++count; //increment count
}
}
if(count == 0)
{
return "NOT FOUND";
}
else if(count == 1)
{
return foundString;
}
else
{
return "NOT UNIQUE";
}
}
int main()
{
std::vector<std::string> inputVector{"DELETE", "HELP", "GO FORWARD", "GO BACKWARDS"};
std::string searchString = "H";
//call the function for different cases
std::cout << checkUnique(searchString, inputVector) <<std::endl;;//prints HELP
std::cout << checkUnique("H", inputVector) << std::endl; //prints HELP
std::cout << checkUnique("H 55", inputVector) << std::endl; //prints HELP
//add "HELLO" into the vector
inputVector.push_back("HELLO");
std::cout << checkUnique("H", inputVector) << std::endl; //prints NOT UNIQUE
std::cout << checkUnique("H 55", inputVector) << std::endl; //prints NOT UNIQUE
return 0;
}
The output of the program can be seen here.
|
70,362,925 | 70,363,616 | Downcasting pointer to pointer | I'm learning polymorphism in C++ and I can't downcast a pointer to a pointer. I have a class Base and a class Derived that extends Base. And I want to do a pool of Derived objects using a function Base **derivedFactory(size_t size). I tried doing Base** array = new Derived*[size]; but the compiler says that it can't convert from Derived** to Base**. So I tried the next:
Base **derivedFactory(size_t size)
{
Base* array = new Derived[size];
for (size_t idx = 0; idx < size; ++idx)
{
Derived derived = Derived();
array[idx] = derived;
}
Base** arrayBase = &array;
return arrayBase;
}
And it compiles. But then when I want to access all Derived objects the main.cc throws a Segmentation fault (core dumped). It executes hello(cout) but then it throws before ending the first iteration of the loop.
Could you please help me?
Main.cc
#include "main.ih"
int main()
{
Base **bp = derivedFactory(10);
for (size_t idx = 0; idx <= 10; ++idx)
{
bp[idx]->hello(cout);
cout << "Not printing\n";
}
}
Class Base:
class Base
{
private:
virtual void vHello(std::ostream &out)
{
out << "Hello from Base\n";
}
public:
void hello(std::ostream &out)
{
vHello(out);
}
};
Class Derived:
class Derived : public Base
{
std::string d_text;
private:
void vHello(std::ostream &out) override
{
out << d_text << '\n';
}
public:
Derived()
{
d_text = "hello from Derived";
}
virtual ~Derived()
{}
};
Thank you!
| There are multiple fundamental problems with the shown code.
Base* array = new Derived[size];
This creates an array of Derived objects. This kind of an array in C++ is represented by a pointer to the first value in array. In this case this would be a Derived *, which is what you get from new.
It is valid in C++ to downcast a pointer to a derived class into a pointer to a base class.
But that's it. That's all you get.
That doesn't mean that a pointer to the first derived object in an array can be downcasted to a pointer to a base class, and then the pointer to the base class be used to access every derived object in the actual array. Pointers don't work this way in C++. Attempting to access any other object besides the first object, that the pointer points to, is undefined behavior. This is the first fundamental problem with the shown code.
Base** arrayBase = &array;
array is an object that's declared as a local object in this function. When this function returns, array gets destroyed, like any other variable declared in this function. It will be destroyed. It will be no more. It will cease to exist. It will pine for the fjords. It will become an ex-object.
The shown code attempts to take an address of this object and return it from this function. After the function returns this pointer becomes a pointer to a destroyed object, and any attempt to access it will be undefined behavior.
Doing this correctly requires a completely different approach. Instead of using new to create an array of derived objects, this should be done by using new to create an array of pointers to the base object. Then, each pointer gets initialized, individually, by newing an individual derived object, something like:
Base **array = new Base *[size];
// ...
array[i] = new Derived{};
|
70,363,432 | 70,377,641 | Unresolved external when trying to link openSSL in a VMWare shared folder | I have built openSSL and put the static libraries under version control (shared objects are not an option).
When I try to build the project while it resides on a shared folder of a vmware Ubuntu VM, it throws me all kinds of unresolved externals, which seemingly stem from 'being unable to find libcrypto.a'.
Strangely enough however, everything works fine, if I copy that exact same folder to the native HDD.
I am using QMake as makefile generator.
The (truncated) command being passed to the command line is as follows:
arm-none-linux-gnueabi-g++ -o ../../../build/appl .obj/src/appl.o -L/mnt/hgfs/Programming/Project/Modules/build/ARM -L/mnt/hgfs/Programming/Project/ThirdParty/lib/ARM -L/mnt/hgfs/Programming/Project/build/ /mnt/hgfs/Programming/Project/build/libCore.a -lSQLite -lJSON -lcurl -lssl -lcrypto -lpthread -lrt -lz
All libraries being listed are static libraries, appl is the resulting binary.
Error messages include:
/mnt/hgfs/Programming/Project/build/libCore.a(Task.o): Task.cpp:(.text+0x298): undefined reference to `EVP_aes_256_cbc'
Task.cpp:(.text+0x145c): undefined reference to `EVP_sha1'
And many more like it. And yes, I am sure that the library is available and readable, because, as stated above, linking works just fine, as long as it is done 'natively'.
My host operating system is Windows, Ubuntu is the guest.
Any ideas what could be the cause of this?
Thank you.
| I have not found the reason behind the original issue, but I have found a way around it.
Using the GNU Buildtools, you can combine the two openSSL libraries into one static library and link that instead.
For this purpose, I used this link for the basic instructions. My openSSL build script (in Python) therefor now has the following extra step:
subprocess.run(["ar", "-M" ], input="\n".join([
"create "+ os.path.join(libDir, 'libOpenSSL.a'),
"addlib "+ os.path.join(installDir, 'lib', 'libcrypto.a'),
"addlib "+ os.path.join(installDir, 'lib', 'libssl.a'),
"save",
"end"
]), text=True, check=True)
libDir is where you want the resulting file to be, installDir is the prefix path, you passed to openSSL configure.
|
70,363,508 | 70,363,962 | How to iterate through a directory_iterator in parallel? | std::filesystem::directory_iterator is a LegacyInputIterator and apparently it can't be used in a parallel std::for_each
I can iterate through the directory_iterator, get the items, place them in a vector and use that vector for parallel iteration.
Can the above step be omitted? Is there a way to iterate through a directory_iterator in parallel like this:
std::for_each(
std::execution::par_unseq, // This is ignored currently
std::filesystem::begin(dir_it),
std::filesystem::end(dir_it),
func
);
| directory_iterator is an input iterator, which means it generates values during the traversal. Furthermore, multiple traversals over the same directory may produce different sequences of values (both in terms of order and values themselves), which means the traversal is not restartable.
For parallel algorithms this means that the sequence cannot be partitioned, the iteration must happen sequentially, in one thread. The only opportunity to parallelize the processing is to offload func execution to separate thread(s), which may or may not be efficient. Filesystem iteration is expensive, and may be even more expensive than the processing in func. In this case you may observe func to be called sequentially, when each call manages to complete before the iterator increment does.
Standard library implementation is permitted to ignore the execution policy argument and execute the algorithm serially. For example, the implementation may simply not bother parallelizing the function calls if the input sequence cannot be partitioned.
|
70,363,513 | 70,406,269 | Multiple prerequisites in partially ordered mock calls in googletest | I was reading partially ordered calls for googletest here and I understoond how their example works. So we can use:
using ::testing::Sequence;
...
Sequence s1, s2;
EXPECT_CALL(foo, A())
.InSequence(s1, s2);
EXPECT_CALL(bar, B())
.InSequence(s1);
EXPECT_CALL(bar, C())
.InSequence(s2);
EXPECT_CALL(foo, D())
.InSequence(s2);
to show the following DAG:
+---> B
|
A ---|
|
+---> C ---> D
But I wondered how we can define multiple prerequisites of a call. For example, how I can add DAG constraints for E node in following DAG?
+---> B ----------+
| |
A ---| |---> E
| |
+---> C ---> D ---+
Will it be something like this?
using ::testing::Sequence;
...
Sequence s1, s2, s3;
EXPECT_CALL(foo, A())
.InSequence(s1, s2);
EXPECT_CALL(bar, B())
.InSequence(s1, s3);
EXPECT_CALL(bar, C())
.InSequence(s2);
EXPECT_CALL(foo, D())
.InSequence(s2, s3);
EXPECT_CALL(foo, E())
.InSequence(s3);
| You can use After method to expect some call after certain other call(s).
https://google.github.io/googletest/reference/mocking.html#EXPECT_CALL.After
So in your case it will be like this:
Mocked mock;
Sequence s1, s2;
EXPECT_CALL(mock, A).InSequence(s1, s2);
Expectation exp_b = EXPECT_CALL(mock, B).InSequence(s1);
EXPECT_CALL(mock, C).InSequence(s2);
Expectation exp_d = EXPECT_CALL(mock, D).InSequence(s2);
EXPECT_CALL(mock, E).After(exp_b, exp_d);
Full runnable example:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::Sequence;
using ::testing::Expectation;
class Mocked {
public:
MOCK_METHOD(void, A, ());
MOCK_METHOD(void, B, ());
MOCK_METHOD(void, C, ());
MOCK_METHOD(void, D, ());
MOCK_METHOD(void, E, ());
};
TEST(Sequences, ABCDE)
{
Mocked mock;
Sequence s1, s2;
EXPECT_CALL(mock, A).InSequence(s1, s2);
Expectation exp_b = EXPECT_CALL(mock, B).InSequence(s1);
EXPECT_CALL(mock, C).InSequence(s2);
Expectation exp_d = EXPECT_CALL(mock, D).InSequence(s2);
EXPECT_CALL(mock, E).After(exp_b, exp_d);
mock.A();
mock.B();
mock.C();
mock.D();
mock.E();
}
P.S. You can completely replace InSequence with After to have a little bit simpler code.
|
70,363,669 | 70,365,845 | CMake fatal error: CMakeFiles/<path>.dir/main.cpp.d: No such file or directory | I am trying to compile a simple C++ program with CMake on Ubuntu 18.04, but all of my CMake projects fails when I run the make command.
Below is a minimum working example.
The directory structure looks like this:
- project directory
|-build
|-main.cpp
|-CMakeLists.txt
main.cpp
int main(void)
{
return 0;
}
CMakeLists.txt
cmake_minimum_required (VERSION 3.1)
project(Test-Project)
add_executable(a
main.cpp
)
target_compile_options(a
PUBLIC -Wall -o -std=c++11
)
Building
cd build
cmake ../ # this works without any error
make # this fails
Error
[ 50%] Building CXX object CMakeFiles/a.dir/main.cpp.o
cc1plus: fatal error: CMakeFiles/a.dir/main.cpp.d: No such file or directory
compilation terminated.
CMakeFiles/a.dir/build.make:75: recipe for target 'CMakeFiles/a.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/a.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/a.dir/all' failed
make[1]: *** [CMakeFiles/a.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2
I get this error when try to compile any CMake based program on the system.
However, if I just used g++ directly to compile the program, it compiles without any complaints.
For example:
g++ ../main.cpp
compiles the program, and runs the program without any errors.
cmake --version: cmake version 3.22.1
g++ --version: g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
g++ -print-prog-name=cc1plus: /usr/lib/gcc/x86_64-linux-gnu/7/cc1plus
uname -a: Linux <computer name> 5.4.0-91-generic #102~18.04.1-Ubuntu SMP <date+time> x86_64 x86_64 x86_64 GNU/Linux
EDIT
Terminal output when compiled with make VERBOSE=1:
/home/kani/.local/lib/python2.7/site-packages/cmake/data/bin/cmake -S/home/kani/Documents/test -B/home/kani/Documents/test/build --check-build-system CMakeFiles/Makefile.cmake 0
/home/kani/.local/lib/python2.7/site-packages/cmake/data/bin/cmake -E cmake_progress_start /home/kani/Documents/test/build/CMakeFiles /home/kani/Documents/test/build//CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make[1]: Entering directory '/home/kani/Documents/test/build'
make -f CMakeFiles/a.dir/build.make CMakeFiles/a.dir/depend
make[2]: Entering directory '/home/kani/Documents/test/build'
cd /home/kani/Documents/test/build && /home/kani/.local/lib/python2.7/site-packages/cmake/data/bin/cmake -E cmake_depends "Unix Makefiles" /home/kani/Documents/test /home/kani/Documents/test /home/kani/Documents/test/build /home/kani/Documents/test/build /home/kani/Documents/test/build/CMakeFiles/a.dir/DependInfo.cmake --color=
make[2]: Leaving directory '/home/kani/Documents/test/build'
make -f CMakeFiles/a.dir/build.make CMakeFiles/a.dir/build
make[2]: Entering directory '/home/kani/Documents/test/build'
[ 50%] Building CXX object CMakeFiles/a.dir/main.cpp.o
/usr/bin/c++ -Wall -o -std=c++11 -MD -MT CMakeFiles/a.dir/main.cpp.o -MF CMakeFiles/a.dir/main.cpp.o.d -o CMakeFiles/a.dir/main.cpp.o -c /home/kani/Documents/test/main.cpp
cc1plus: fatal error: CMakeFiles/a.dir/main.cpp.d: No such file or directory
compilation terminated.
CMakeFiles/a.dir/build.make:75: recipe for target 'CMakeFiles/a.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/a.dir/main.cpp.o] Error 1
make[2]: Leaving directory '/home/kani/Documents/test/build'
CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/a.dir/all' failed
make[1]: *** [CMakeFiles/a.dir/all] Error 2
make[1]: Leaving directory '/home/kani/Documents/test/build'
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2
| Despite the error message about absent .d file seems to be internal to CMake (such files are used for collect header dependencies generated by the compiler), its usual reason is specifying some output-controlling compiler options in the CMakeLists.txt.
In your case it is -o option which damages the command line generated by CMake. CMake by itself uses this option for specify object file which will be created as a result of the compilation. So adding another -o is wrong.
|
70,363,847 | 70,365,877 | Why doesn't std::ranges::upper_bound accept heterogenous comparing? | This code works and returns an iterator to foo{5} from the vector:
struct foo {
int value;
};
auto main() -> int {
auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}};
std::ranges::sort(ints, {}, &foo::value);
auto it = std::upper_bound(
ints.begin(), ints.end(),
4,
[](const int v, const foo f) {
return v < f.value;
}
);
}
This, however, doesn't compile:
struct foo {
int value;
};
auto main() -> int {
auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}};
std::ranges::sort(ints, {}, &foo::value);
auto it = std::ranges::upper_bound( // the only change - added ::ranges
ints,
4,
[](const int v, const foo f) {
return v < f.value;
}
);
std::cout << it->value;
}
Is the alteration of the behavior intentional or accidental?
The error message boils down to not satisfying the following constraint:
note: the expression 'is_invocable_v<_Fn, _Args ...> [with _Fn = main::._anon_76&; _Args = {int&, int&}]' evaluated to 'false'
Well, yeah, you can't call that with two int&s. I suspect it may be intentional since the "standard" way would be to use the projection like so:
struct foo {
int value;
};
auto main() -> int {
auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}};
std::ranges::sort(ints, {}, &foo::value);
auto it = std::ranges::upper_bound(ints, 4, {}, &foo::value); // using projection
std::cout << it->value;
}
Is this the rationale? Looking at the fairly complilated signature of template parameters of std::ranges::upper_bound didn't really shine any light on it for me.
|
I suspect it may be intentional since the "standard" way would be to use the projection like so:
This is basically the motivation for projections. From N4128:
The Adobe Source Libraries (ASL)[1] pioneered the use of “projections” to make the algorithms more powerful and expressive by increasing interface symmetry. Sean Parent gives a motivating example in his “C++ Seasoning” talk[15], on slide 38. With today’s STL, when using sort and lower_bound together with user-defined predicates, the predicate must sometimes differ. Consider:
std::sort(a, [](const employee& x, const employee& y)
{ return x.last < y.last; });
auto p = std::lower_bound(a, "Parent", [](const employee& x, const string& y)
{ return x.last < y; });
Notice the different predicates used in the invocations of sort and lower_bound. Since the predicates are different, there is a chance they might get out of sync leading to subtle bugs.
By introducing the use of projections, this code is simplified to:
std::sort(a, std::less<>(), &employee::last);
auto p = std::lower_bound(a, "Parent", std::less<>(), &employee::last);
Every element in the input sequence is first passed through the projection &employee::last. As a result, the simple comparison predicate std::less<> can be used in both places.
Whereas std::sort takes a homogeneous comparison and std::lower_bound and std::upper_bound each take a heterogeneous comparison (with the arguments in opposite order), the std::ranges:: versions of these algorithms all take homogeneous comparisons. std::ranges::lower_bound and std::ranges::upper_bound achieve heterogeneity with the projection, which is simply internally applied to the range's element before passing it into the homogeneous comparison, while std::ranges::sort applies the projection to both arguments.
This is a lot easier to use, less code to write, and less error prone: because you just have the one comparison that you use for all three algorithms, and you don't have to remember the order of arguments for the two bound algorithms.
|
70,363,885 | 70,364,183 | How to declare manually uint512_t in boost? | i wanna declare this:
uint512_t qwe = 0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E;
but c++ don't think so(vscode hints too):
integer constant is too large for its type
and its print like:
x: 0x514c0ce9dae23b7e
can you help me please?
| You can use user-defined literals to initialize Boost.Multiprecision numbers, for example:
uint512_t qwe =
0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E_cppui512;
Alternatively, you could use a constructor from string, but this is less efficient as it will require run time parsing. It can be useful if the number is not a compile-time constant.
|
70,364,283 | 70,364,802 | Fast way of copying multidimensional array in C++ | I have multidimensional array of Struct in C++.
#define TOTALSTREAMS 5
#define SEQUENCEHISTORY 20
#define PROCESSINGSIZE 5
#define OVERLAPPINGSIZE 1
#define X_GRID 100//X_GRID and Y_GRID represents the whole building in CM
#define Y_GRID 70
typedef struct {
uint64_t localid;
uint64_t globalid;
int posture;
std::vector<float> feature;
} person;
typedef struct {
std::vector<person> people;
} griddata;
griddata History_host[SEQUENCEHISTORY][TOTALSTREAMS][Y_GRID][X_GRID];
griddata Processed_Array[PROCESSINGSIZE][TOTALSTREAMS][Y_GRID][X_GRID];
Need to copy from one array to another. What I did was just copy in simple way as follows. It is slow. How can I copy such array in faster way?
for(int i=0; i<PROCESSINGSIZE; i++){
for(int j=0; j<TOTALSTREAMS; j++){
for(int k=0; k<Y_GRID; k++){
for(int m=0; m<X_GRID; m++){
for(int n=0; n<History_host[i][j][k][m].people.size(); n++){
Processed_Array[i][j][k][m].people.push_back(History_host[i][j][k][m].people.back());
}
}
}
}
}
| The code you have posted does not copy the arrays content properly.
The assignment
Processed_Array[i][j][k][m].people.push_back(History_host[i][j][k][m].people.back());
will not copy the arrays content, but only add the last element of the source array several times. You should use the index n to access the appropriate element.
Here are some hints to increase the copy speed:
use std::vector<>.reserve() to allocate the vectors elemets before using std::vector<>.push_back(). Vectors will grow dynamicaly of no initial Size is given, this is a costly operation.
Try to avoid the usage of std::vector<> and use fixed size arrays (if possible). Fixed size arrays can easily copied with memcpy()
|
70,364,332 | 70,365,535 | lock of openmp seems not to work when dong summation | I am new to openMP and mutli-threading. I need to do some summation work and I know that when writing to the shared variable, it need to use lock like omp_lock_t. But when I do so, the result still goes wrong.
The code is:
#include <omp.h>
#include <cstdio>
struct simu
{
public:
simu() : data{ nullptr }
{
omp_init_lock(&lock);
}
~simu()
{
omp_destroy_lock(&lock);
}
void calcluate()
{
omp_set_lock(&lock);
(*data) += 1;
omp_unset_lock(&lock);
}
public:
omp_lock_t lock;
int *data;
};
int main()
{
printf("thread_num = %d\n", omp_get_num_procs());
const int size = 2000;
int a = 1;
int b = 2;
simu s[size];
simu *ps[size];
for (int i = 0; i < size; ++i)
{
s[i].data = (0 == i % 2) ? &a : &b;
ps[i] = &s[i];
}
for (int k = 0; k < size; ++k)
{
ps[k]->calcluate();
}
printf("a = %d, b = %d\n", a, b);
a = 1;
b = 2;
#pragma omp parallel for default(shared) num_threads(4)
for (int k = 0; k < size; ++k)
{
ps[k]->calcluate();
}
printf("a = %d, b = %d\n", a, b);
return 0;
}
And the result is
thread_num = 8
a = 1001, b = 1002
a = 676, b = 679
I run this code on Win10. Can anyone explain why the result is wrong?
| A lock protects the actual data item from simultaneous writes. Your lock is in the object that points at the item, so this is pointless. You need to let you data point to an object that contains a lock.
|
70,364,855 | 70,365,075 | operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer typeC/C++ | In a lambda function, instead of this, I was trying to use weak_ptr to access all member function and variable, but I'm getting this error:
operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer type
| std::weak_ptr<T> by design safely refers to an object which may or may not still exist. It does not offer operator-> or operator* since you have to make sure the object still exists before you can try to access it.
To access an object referred to by a std::weak_ptr you first call lock() which returns a std::shared_ptr. Then, you need to check if that std::shared_ptr refers to an object. If it does, then the object is safe to access and won't be deleted until that returned pointer is destroyed (because there will still exist a std::shared_ptr for it). If it doesn't then the std::weak_ptr was referring to a destroyed object which you can't access anymore.
Example :
#include <memory>
class foo
{
public:
void bar(){}
};
void test(std::weak_ptr<foo> ptr)
{
// Get a shared_ptr
auto lock = ptr.lock();
// Check if the object still exists
if(lock)
{
// Still exists, safe to dereference
lock->bar();
}
}
|
70,364,977 | 70,367,541 | Understanding the reasoning between copy/move constructors and operators | I am trying to get the grasp of rvalue references and move semantics with a simple self-made example but I can't understand a specific part. I have created the following class:
class A {
public:
A(int a) {
cout << "Def constructor" << endl;
}
A(const A& var) {
cout << "Copy constructor" << endl;
}
A(A&& var) {
cout << "Move constructor" << endl;
}
A& operator=(const A& var) {
cout << "Copy Assignment" << endl;
return *this;
}
A& operator=(A&& var) {
cout << "Move Assignment" << endl;
return *this;
}
};
I tried the following experiments to see if I can predict how the constructors/operators are going to be called:
A a1(1) - The default constructor is going to be called.
PREDICTED.
A a2 = a1 - The copy constructor is going to be called. PREDICTED.
a1 = a2 - The copy assignment operator is going to be called.
PREDICTED.
Now, I created a simple function that just returns an A object.
A helper() {
return A(1);
}
A a3 = helper() - The default constructor is going to be called in
order to create the object that the helper returns. The move
constructor is not going to be called due to RVO. PREDICTED.
a3 = helper() - The default constructor is going to be called in
order to create the object that the helper returns. Then, the move
assignment operator is going to be called. PREDICTED.
Now comes the part I don't understand. I created another function that is completely pointless. It takes an A object by value and it just returns it.
A helper_alt(A a) {
return a;
}
A a4 = helper_alt(a1) - This will call the copy constructor, to
actually copy the object a1 in the function and then the move
constructor. PREDICTED.
a4 = helper_alt(a1) - This will call the copy constructor, to
actually copy the object a1 in the function and then I thought that
the move assignment operator is going to be called BUT as I saw,
first, the move constructor is called and then the move assignment
operator is called. HAVE NO IDEA.
Please, if any of what I said is wrong or you feel I might have not understood something, feel free to correct me.
My actual question: In the last case, why is the move constructor being called and then the move assignment operator, instead of just the move assignment operator?
| Congratulations, you found a core issue of C++!
There are still a lot of discussions around the behavior you see with your example code.
There are suggestions like:
A&& helper_alt(A a) {
std::cout << ".." << std::endl;
return std::move(a);
}
This will do what you want, simply use the move assignment but emits a warning from g++ "warning: reference to local variable 'a' returned", even if the variable goes immediately out of scope.
Already other people found that problem and this is already made a c++ standard language core issue
Interestingly the issue was already found in 2010 but not solved until now...
To give you an answer to your question "In the last case, why is the move constructor being called and then the move assignment operator, instead of just the move assignment operator?" is, that also C++ committee does not have an answer until now. To be precise, there is a proposed solution and this one is accepted but until now not part of the language.
From: Comment Status
Amend paragraph 34 to explicitly exclude function parameters from copy elision. Amend paragraph 35 to include function parameters as eligible for move-construction.
|
70,365,084 | 70,365,145 | How to Ensure proper initialization of Non Static Data Members within a Class Template in C++ | I am working with templates in C++ and want to know how can we properly(value) initialize the non static data members in a class template. For example, consider the following snippet:
template<typename T>
class MyVector
{
T x; // x has undefined value for a built in type
};
Now i know that the data member x has garbage value for built in types in local/block scope unless explicitly initialized.
So i want to value initialize the data member. If i modify the above code to:
template<typename T>
class MyVector
{
T x(); // now x becomes a member function
};
As can be seen in the above modified code snippet, x is now a member function. How can i value initialize the data member x for type T?
| There are different way to do what you want depending upon which C++ version you're using. This is explained in more detail below:
C++11
template<typename T>
class MyVector
{
T x{};
};
Pre C++11
template<typename T>
class MyVector
{
T x;
MyVector(): x()
{
}
};
C++11
From C++11 and onwards, you can also write(using constructor initializer list):
template<typename T>
class MyVector
{
T x;
MyVector(): x{}
{
}
};
C++11
Note that this version won't work if the constructor for copy initialization is explicit since there is no mandatory copy elison.
#include <iostream>
using namespace std;
struct Name
{
explicit Name(const Name&)
{
}
Name() = default;
};
template<typename T>
class MyVector
{
public:
T x = T();
};
int main()
{
cout<<"Hello World";
MyVector<int> p; // works with C++11,C++17 etc
MyVector<Name> n; //error with C++11 and C++14
return 0;
}
But the above version will work with C++17 since there is mandatory copy elison in C++17.
#include <iostream>
using namespace std;
struct Name
{
explicit Name(const Name&)
{
}
Name() = default;
};
template<typename T>
class MyVector
{
public:
T x = T();
};
int main()
{
cout<<"Hello World";
MyVector<int> p; // works with C++11,C++17 etc
MyVector<Name> n; //works with C++17 due to mandatory copy elison
return 0;
}
|
70,365,696 | 70,365,734 | How do i set x to be a negative value if x is positive, and if x is positive how do i set it to be negative. c++ | I am making an AI/algorithm to find a checker pattern in a 2x2 square. I need them to be negative for hidden_1 and hidden_3, but positive for the other 2.
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int main (){
int x;
int y;
int a;
int b;
int x1 = -x;
int y1 = -y;
int a1 = -a;
int b1 = -b;
cout << "Is there a square in the top left?\n1 for Yes/-1 for No\n";
cin >> x;
cout << "Is there a square in the bottom right?\n1 for Yes/-1 for No\n";
cin >> y;
cout << "Is there a square in the bottom left?\n1 for Yes/-1 for No\n";
cin >> a;
cout << "Is there a square in the top right?\n1 for Yes/-1 for No\n";
cin >> b;
int hidden_1 << x1 + y1 + -1;
int hidden_2 << x + y + -1;
int hidden_3 << a1 + b1 + -1;
int hidden_4 << a + b + -1;
| You initialised x1, y1, a1, b1 with negatives of variables that weren't read. Try declare them after you read x, y, a, b.
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int main () {
int x;
int y;
int a;
int b;
cout << "Is there a square in the top left?\n1 for Yes/-1 for No\n";
cin >> x;
cout << "Is there a square in the bottom right?\n1 for Yes/-1 for No\n";
cin >> y;
cout << "Is there a square in the bottom left?\n1 for Yes/-1 for No\n";
cin >> a;
cout << "Is there a square in the top right?\n1 for Yes/-1 for No\n";
cin >> b;
int x1 = -x;
int y1 = -y;
int a1 = -a;
int b1 = -b;
int hidden_1 = x1 + y1 + -1;
int hidden_2 = x + y + -1;
int hidden_3 = a1 + b1 + -1;
int hidden_4 = a + b + -1;
|
70,365,812 | 70,366,629 | returning a std::string from a variant which can hold std::string or double | I have the following code:
#include <variant>
#include <string>
#include <iostream>
using Variant = std::variant<double, std::string>;
// helper type for the visitor
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
// explicit deduction guide (not needed as of C++20)
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
std::string string_from(const Variant& v)
{
return std::visit(overloaded {
[](const double arg) { return std::to_string(arg); },
[](const std::string& arg) { return arg; },
}, v);
}
int main()
{
Variant v1 {"Hello"};
Variant v2 {1.23};
std::cout << string_from(v1) << '\n';
std::cout << string_from(v2) << '\n';
return 0;
}
I have a function called string_from() which takes a variant and converts its inner value to a string.
The variant can hold either a std::string or a double.
In case of a std::string, I just return it.
In case of a double, I create a std::string from the double and then return it.
The problem is, I don't like the fact that I'm returning a copy of the std::string in case of a string-variant. Ideally, I would return a std::string_view or another kind of string observer.
However, I cannot return a std::string_view because in case of a double-variant I need to create a new temporary std::string and std::string_view is non-owning.
I cannot return a std::string& for the same reason.
I'm wondering if there's a way to optimize the code so that I can avoid the copy in case of a string-variant.
Note in my actual use case, I obtain strings from string-variants very frequently, but very rarely from double-variants.
But I still want to be able to obtain a std::string from a double-variant.
Also, in my actual use case, I usually just observe the string, so I don't really need the copy every time. std::string_view or some other string-observer would be perfect in this case, but it is impossible due to the reasons above.
I've considered several possible solutions, but I don't like any of them:
return a char* instead of a std::string and allocate the c-string somewhere on the heap in case of a double. In this case, I would also need to wrap the whole thing in a class which owns the heap-allocated strings to avoid memory leaks.
return a std::unique_ptr<std::string> with a custom deleter which would cleanup the heap-allocated strings, but would do nothing in case the string resides in the variant. Not sure how this custom deleter would be implemented.
Change the variant so it holds a std::shared_ptr<std::string> instead. Then when I need a string from the string-variant I just return a copy of the shared_ptr and when I need a string from the double-variant I call std::make_shared().
The third solution has an inherent problem: the std::string no longer resides in the variant, which means chasing pointers and losing performance.
Can you propose any other solutions to this problem? Something which performs better than copying a std::string every time I call the function.
| You can return a proxy object. (this is like your unique_ptr method)
struct view_as_string{
view_as_string(const std::variant<double, std::string>& v){
auto s = std::get_if<std::string>(&v);
if(s) ref = s;
else temp = std::to_string(std::get<double>(v));
}
const std::string& data(){return ref?*ref:temp;}
const std::string* ref = nullptr;
std::string temp;
};
Use
int main()
{
std::variant<double, std::string> v1 {"Hello"};
std::variant<double, std::string> v2 {1.23};
std::cout << view_as_string(v1).data() << '\n';
view_as_string v2s(v2);
std::cout << v2s.data() << '\n';
}
|
70,365,959 | 70,375,654 | Using CMake, how to rebuild Swig wrapper when header file changes | I have a C++ library (called myfibo) and I want to make a python binding modue (called myfibopy) using CMake and Swig.
The first build works perfectly. But if I rename an exposed C++ function, the python module doesn't build anymore because the Swig wrapper (PYTHON_wrap.cxx) is not regenerated.
I have already tried using SWIG_USE_LIBRARY_INCLUDE_DIRECTORIES as explained here but with no success.
What I am doing wrong?
Here is the toy example to reproduce the error:
Directory tree
.
├── CMakeLists.txt
├── myfibo
│ ├── CMakeLists.txt
│ ├── fibo.cpp
│ └── include
│ └── fibo.hpp
└── myfibopy
├── CMakeLists.txt
└── fibo.i
fibo.hpp
#pragma once
void fib(int n);
fibo.cpp
#include "fibo.hpp"
#include <iostream>
void fib(int n)
{
int a = 0;
int b = 1;
while (a < n)
{
std::cout << a << " ";
a = b;
b = a+b;
}
std::cout << std::endl;
}
fibo.i
%module myfibopy
%include fibo.hpp
%{
#include "fibo.hpp"
%}
./CMakeLists.txt
project(myfibopy)
cmake_minimum_required(VERSION 3.15)
add_subdirectory(myfibo)
add_subdirectory(myfibopy)
myfibo/CMakeLists.txt
add_library(myfibo SHARED fibo.cpp)
target_include_directories(myfibo
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include> # unused
)
myfibopy/CMakeLists.txt
find_package(PythonLibs 3 REQUIRED)
include_directories(${PYTHON_INCLUDE_PATH})
find_package(SWIG 4.0 REQUIRED)
include(${SWIG_USE_FILE})
set(SRC fibo.i)
set_source_files_properties(${SRC} PROPERTIES CPLUSPLUS ON)
swig_add_library(myfibopy LANGUAGE python SOURCES ${SRC})
target_link_libraries(myfibopy PUBLIC myfibo)
# See https://gitlab.kitware.com/cmake/cmake/-/issues/18003
set_target_properties(myfibopy PROPERTIES SWIG_USE_TARGET_INCLUDE_DIRECTORIES TRUE)
First compilation
> cmake -Bbuild -H.
[...]
> cmake --build build
[...]
Perfect. Now, build directory exists and I can play with myfibopy module.
After renaming fib into fib2 in fibo.hpp and fibo.cpp
> cmake --build build
Consolidate compiler generated dependencies of target myfibo
[ 20%] Building CXX object myfibo/CMakeFiles/myfibo.dir/fibo.cpp.o
[ 40%] Linking CXX shared library libmyfibo.so
[ 40%] Built target myfibo
[ 60%] Built target myfibopy_swig_compilation
Consolidate compiler generated dependencies of target myfibopy
[ 80%] Building CXX object myfibopy/CMakeFiles/myfibopy.dir/CMakeFiles/myfibopy.dir/fiboPYTHON_wrap.cxx.o
./build/myfibopy/CMakeFiles/myfibopy.dir/fiboPYTHON_wrap.cxx: In function ‘PyObject* _wrap_fib(PyObject*, PyObject*)’:
./build/myfibopy/CMakeFiles/myfibopy.dir/fiboPYTHON_wrap.cxx:2968:3: error: ‘fib’ was not declared in this scope
fib(arg1);
^~~
./build/myfibopy/CMakeFiles/myfibopy.dir/fiboPYTHON_wrap.cxx:2968:3: note: suggested alternative: ‘fib2’
fib(arg1);
^~~
fib2
myfibopy/CMakeFiles/myfibopy.dir/build.make:75: recipe for target 'myfibopy/CMakeFiles/myfibopy.dir/CMakeFiles/myfibopy.dir/fiboPYTHON_wrap.cxx.o' failed
make[2]: *** [myfibopy/CMakeFiles/myfibopy.dir/CMakeFiles/myfibopy.dir/fiboPYTHON_wrap.cxx.o] Error 1
CMakeFiles/Makefile2:170: recipe for target 'myfibopy/CMakeFiles/myfibopy.dir/all' failed
make[1]: *** [myfibopy/CMakeFiles/myfibopy.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2
| Did you try:
USE_SWIG_DEPENDENCIES
New in version 3.20.
If set to TRUE, implicit dependencies are generated by the swig tool itself. This property is only meaningful for Makefile, Ninja, Xcode, and Visual Studio (Visual Studio 11 2012 and above) generators. Default value is FALSE.
New in version 3.21: Added the support of Xcode generator.
New in version 3.22: Added the support of Visual Studio Generators.
or
USE_TARGET_INCLUDE_DIRECTORIES
New in version 3.13.
If set to TRUE, contents of target property INCLUDE_DIRECTORIES will be forwarded to SWIG compiler. If set to FALSE target property INCLUDE_DIRECTORIES will be ignored. If not set, target property SWIG_USE_TARGET_INCLUDE_DIRECTORIES will be considered.
src: https://cmake.org/cmake/help/git-stage/module/UseSWIG.html
|
70,366,126 | 70,385,516 | inline function with empty parameter | I'm studying on Boost library. Can someone help me understand below code.
/*!
\fn ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest)
\brief Equivalent of <code>std::uninitialized_copy</code> but with explicit specification of value type.
*/
template<class InputIterator, class ForwardIterator, class Alloc>
inline ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a)
{
ForwardIterator next = dest;
BOOST_TRY {
for (; first != last; ++first, ++dest)
boost::allocator_construct(a, boost::to_address(dest), *first);
} BOOST_CATCH(...) {
for (; next != dest; ++next)
boost::allocator_destroy(a, boost::to_address(next));
BOOST_RETHROW
}
BOOST_CATCH_END
return dest;
}
and the function allocator_construct as below:
template<class A, class T, class V>
inline void allocator_construct(A&, T* p, const V& v)
{
::new((void*)p) T(v);
}
Can some one help to understand the purpose of calling boost::allocator_construct(a, boost::to_address(dest), *first); in unitialized_copy and why the function author trying to leave empty param at first param A& in allocator_construct.
Thanks for your help.
| The short answer is: this function puts values in memory that has already been allocated, but not yet initialized. That's also why this particular allocator_construct implementation does not use the allocator parameter, but others probably do.
For an explanation of why this is useful, consider std::vector, which has both the type to be stored and a corresponding allocator as template parameters. It can use this information to manage its own memory, allowing it to allocate memory in chunks instead of separately for every element you add, which would be much slower. If you copy a sequence of values, it will first ensure that enough memory is available, then call a function like uninitialized_copy to do the actual work.
|
70,366,415 | 70,366,870 | How does Visual studio know which library to link if both static and dynamic libraries exist? | When linking with external libraries, if both static and dynamic libraries exist in the same folder, which library will Visual Studio link?
As an example, for the boost filesystem library, the x64 static library file is libboost_filesystem-vc142-mt-x64-1_77.lib and the x64 dynamic library files are boost_filesystem-vc142-mt-x64-1_77.dll and boost_filesystem-vc142-mt-x64-1_77.lib. All these files are located in the same folder. When linking, how does Visual Studio linker know which one to use? Is it determined by the flag Runtime Library (/MT and /MD)?
| TLDR: Yes, in case of boost choise is based on selected runtime in the project options (/MT or /ST).
Long version: =)
Boost library has an autolinking feature. This mechanism is defined in the header file config/auto_link.hpp. There boost is trying to determine full lib name basing on selected build architecture, toolset, threading options and so on. There are defines like BOOST_DYN_LINK, BOOST_AUTO_LINK_NOMANGLE which allow you to control this process. Also process could be controlled by library section specific defines for example: BOOST_ASIO_DYN_LINK for the boost::asio
Relevant section for selecting static/runtime library looks like this:
#if (defined(_DLL) || defined(_RTLDLL)) && defined(BOOST_DYN_LINK)
# define BOOST_LIB_PREFIX
#elif defined(BOOST_DYN_LINK)
# error "Mixing a dll boost library with a static runtime is a really bad idea..."
#else
# define BOOST_LIB_PREFIX "lib"
#endif
Basicaly it depends on _DLL or _RTLDLL preprocessor option. According to MSDN
_DLL Defined as 1 when the /MD or /MDd (Multithreaded DLL) compiler option is set. Otherwise, undefined.
For other libraries you must specify exact library name to link against. This is done either in project options window (Linker/Input in case of MSVC), or by using directive #pragma comment(lib libname) directly in the source code. Failure to do that will lead to linker errors
|
70,366,648 | 70,366,769 | How to recursively split a linked list after k nodes in C++? | I have an ordinary linked list with:
struct node{
int info;
node* next;
};
I need to write a recursive function that splits in 2 a given linked list passed by reference after k elements, leaving the first k nodes in this list and returning the second list with the rest of the nodes.
My iterative solutions looks like this:
node* split(node*&L, int k){
node* M;
node* head = L;
while(k>1){
head=head->next;
k--;
}
M = head->next;
head->next = NULL;
return M;
}
Output:
L: 1 2 3 4 5 6
after split with: k = 3
L: 1 2 3
M: 4 5 6
Which seems to work just fine. Now i can't really think of a recursive solution for this. I was trying with:
node* splitL(node*&L, int k){
if(!L) return 0;
if(k<=1){
node* x = L->next;
L->next = NULL;
return x;
}
L->next = splitL(L->next, k-1);
return L;
}
Which is obviously wrong because it's returning x into L->next so both lists become 1 2 3 4 5 6.
How do I write a recursive function for this? The parameters and the return type should stay the same. Also it would be great if someone could explain how I could translate my iterative solution to a recursive one.
| You currently have
node* split(node*&L, int k){
node* M;
node* head = L;
while(k>1){
head=head->next;
k--;
}
M = head->next;
head->next = NULL;
return M;
}
You want something like
node* split(node*&L, int k){
node* M;
node* head = splitPoint(L, k);
M = head->next;
head->next = NULL;
return M;
}
node* splitPoint(node*&L, int k){
if (k <= 0)
return L;
return splitPoint(L->next, k - 1);
}
Note neither this nor your original guards for k greater than the length of the list.
Single-function version:
node* split(node*&L, int k){
if (k <= 0)
{
node* head = L;
node* M = head->next;
head->next = NULL;
return M;
}
return split(L->next, k - 1);
}
|
70,366,716 | 70,366,878 | How can I call a function from an array of functions via its index? | A beginner's question I couldn't find answered online, likely because I don't know the terminology.
I want to call one of a list of procedures based on a computed index value. That is, given a '1', invoke firstProc(), '2' invokes secondProc() and so on.
All the procedures are void functions with no arguments.
I can implement that with switch/case, but what I'd prefer is something like:
void* action[2] {*firstProc, *secondProc};
(This compiles, but warns: invalid conversion from 'void (*)()' to 'void*')
and then later:
action[get_index()]();
The compiler objects that 'action' can't be used as a function.
This must be possible, right? I've tried several variations but I can't get past the use of the selected ('action[index]') as a function.
| There are two equivalent ways to do what you want. The explanation is given as comments in the code snippets.
Method 1
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything
void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything
//create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
void (*arr[2])() = { a, b};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 1 can be executed here.
In method 1 above void (*a)() = foo; means that a is a pointer to a function that takes no parameter and also does not return anything.
Similarly, void (*b)() = foo2; means that b is a pointer to a function that takes no parameter and also does not return anything.
Next, void (*arr[2])() = { a, b}; means that arr is an array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter.
Method 2
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
//create array(of size 2) that can hold pointers to functions that does not return anything
void (*arr[2])() = { foo, foo2};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 2 can be executed here.
|
70,366,907 | 70,369,699 | I'm trying to sum up the numbers in a given array, using recursion , tried this code but it isn't working. Why? | #include <iostream>
using namespace std;
int sumByRecursion( int arr[]) {
int sum = 0;
int n = sizeof(arr)/sizeof(arr[0]);
//n is the size of the array
if (n == 0) {
return sum;
} else {
n -= 1;
for (int i=0;i=n;++i){
arr[i]=arr[i+1];
}
return (sum + arr[0] + sumByRecursion( arr));
}
}
int main() {
int arr[]={2, 4, 6};
sumByRecursion( arr);
return 0;
}
sumByRecursion working based on this idea:
1-if the size of the array is 0 "empty array", return the sum.
2-if size isn't 0 "array isn't empty", sum up the first element on sum, then call the function, reduce the array's size by 1, sumByRecursion on the new array.
| A (sadly) common mistake:
int sumByRecursion( int arr[] )
{ // What do you think ^^^^^ this is?
int n = sizeof(arr)/sizeof(arr[0]);
// ^^^^^^^^^^^ Sorry, too late.
// ...
}
As already noted in the comment section
Inside the function the parameter arr has decayed to type int* and knows nothing about the number of elements in the array. (Richard Critten)
In short: int sumByRecursion( int arr[]) is exactly the same as int sumByRecursion( int *arr). That [] syntax in the parameter list is nothing more than syntax sugar. (PaulMcKenzie)
The solution is to pass the size alongside the pointer, either explicitly as a separate function argument or inside an object like std::span or std::ranges::range.
An alternative, of course, is to pass the couple of iterators returned by std::cbegin() and std::cend().
The code used to "reduce the array's size by 1" is probably a result of the same misunderstanding:
int sum = 0;
// ...
if (n == 0) { // Ok...
return sum;
} else {
n -= 1; // Okayish...
for (int i=0;i=n;++i){ //
arr[i]=arr[i+1]; // <-- There's NO need to do all those copies!
} //
return (sum + arr[0] + sumByRecursion( arr));
// ^^^^ This does NOT pass an array
}
Eljay's answer shows how to correctly implement OP's algorithm.
Just for fun(1), a stack-friendlier implementation
#include <iostream>
int sumByRecursion(size_t n, int const* arr)
{
// Stop the bloody recursion
if ( n == 0 )
return 0;
if ( n == 1 )
return arr[0];
// Divide et impera
size_t middle = n / 2;
return sumByRecursion(middle, arr)
+ sumByRecursion(n - middle, arr + middle);
}
int main()
{
int arr[] {2, 4, 6};
std::cout << sumByRecursion(std::size(arr), arr) << '\n';
}
(1) Seriously, do NOT use this. It's utterly inefficient and uselessly convoluted. Use the right algorithm instead.
|
70,367,073 | 70,367,606 | How to define a single copy constructor for template classes? | #include <iostream>
template <typename T>
class Matrix
{
public:
Matrix() = default;
template <typename U>
Matrix(const Matrix<U>& matrix) {
std::cout << "Copying internal data..." << std::endl;
}
// Matrix(const Matrix<T>& matrix) {
// std::cout << "Copying internal data..." << std::endl;
// }
Matrix(Matrix<T>&& matrix) {
std::cout << "Moving internal data..." << std::endl;
}
};
int main() {
Matrix<int> m1{};
Matrix<double> m2 = m1;
Matrix<int> m3 = m1;
}
Here, I have a matrix class, it can be a matrix of int, a double, or any numerical value.
I want to define a copy constructor that accepts a matrix with any numerical type and copies its elements.
For example, suppose m1 is a Matrix<double> = {1.1, 2.2, 3.3, ...}, Matrix<int> m2 = m1 should set m2 to be {1, 2, 3, ...}.
Also, I want to have a move constructor, but it doesn't make any sense to have a move constructor for any type except for its own type (in this example, it's T).
This is because I'm going to steal the pointer pointing to the array of numbers, and to do so, it has to be of the same type.
Defining a move constructor that accepts only Matrix<T> automatically deletes the copy constructor for Matrix<T>.
I realized that since the parameter in the copy constructor I tried to make isn't necessarily of the same type, it's not considered to be a copy constructor, and unless I write a copy constructor specifically for Matrix<T> (the commented copy constructor), the code won't compile.
But even if I don't have a copy constructor, I have a constructor that accepts a matrix of any type. Why is it looking specifically for the copy constructor?
How do I define my copy constructor only once, and have it deal with matrices of any type?
|
But even if I don't have a copy constructor, I have a constructor that accepts a matrix of any type. Why is it looking specifically for the copy constructor?
In overload resolution it is not find the best usable function. Instead, it is find the best function and try to use it. If it can't because of access restrictions or being deleted, then you get a compiler error.
In your case, you have the template constructor that stamps out Matrix(const Matrix<double>& matrix) (#1), and it also finds Matrix(const Matrix<double>& matrix) = delete (#2) which was implicitly generated by the compiler because you have a user provided move constructor. In overload resolution, if two functions have the exact same signature, and one of those is a specialization of a template, the non template version is chosen. In this case that is #2 which is deleted, so you get an error for accessing a deleted function.
So to answer
How do I define my copy constructor only once, and have it deal with matrices of any type?
You can't. If you want Foo<T> to be copyable from another Foo<T> then you need to provide a copy constructor. If you want Foo<T> to be copyable from a Foo<U>, then you need to add a converting constructor for that. Ideally you would use something like a std::vector as the underlying storage for the matrix elements, and if you do, then you can just follow the rule of zero and your class becomes
template <typename T>
class Matrix
{
public:
Matrix() = default;
template <typename U>
Matrix(const Matrix<U>& other) data(other.data.begin(), other.data.end()) {}
private:
std::vector<T> data;
};
|
70,367,406 | 70,367,506 | Generically return a optional<T> / nullopt | I am trying to implement a generic find_if_opt method which is virtually identical to std::ranges::find_if (however it return an Optional)
So far this is my implementation.
template <typename X, typename Z>
inline auto find_if_opt(const X& ds, const Z& fn) {
const auto it = ranges::find_if(ds, fn);
if (it != end(ds)) {
return std::make_optional(*it);
}
return {};
}
auto test() {
std::vector v{1,2,3,4,5};
return ranges::find_if_opt(v, [](auto i){
return i == 2;
});
}
This is a part of a larger std::ranges like wrapper around c++17 algorithms. See https://godbolt.org/z/3fEe8bbh9 (for entire relevant header)
When using {} the compiler error is:
<source>:29:16: error: cannot deduce return type from initializer list
return {};
^~
I have also tried using std::nullopt, which causes:
<source>:41:6: required from here
<source>:30:21: error: inconsistent deduction for auto return type: 'std::optional<int>' and then 'std::nullopt_t'
return std::nullopt;
^~~~~~~
PS: if you have suggestions regarding my ranges:: wrapper while I'm still stuck on c++17, feel free to.
| You can use ranges::range_value_t to get value_type of X
template <typename X, typename Z>
inline std::optional<std::ranges::range_value_t<X>>
find_if_opt(const X& ds, const Z& fn) {
const auto it = std::ranges::find_if(ds, fn);
if (it != end(ds)) {
return *it;
}
return {};
}
Or using std::iter_value_t to get value_type of iterator
template <typename X, typename Z>
inline auto
find_if_opt(const X& ds, const Z& fn) {
const auto it = std::ranges::find_if(ds, fn);
if (it != end(ds)) {
return std::make_optional(*it);
}
return std::optional<std::iter_value_t<decltype(it)>>{};
}
Or pre-C++20
template <typename X, typename Z>
inline auto find_if_opt(const X& ds, const Z& fn) {
const auto it = ranges::find_if(ds, fn);
if (it != end(ds)) {
return std::make_optional(*it);
}
return std::optional<std::decay_t<decltype(*it)>>{};
}
|
70,367,965 | 70,368,833 | how to know if a http request is partial and how to fully parse it before generating a response c++ | I am working on a C++ project where i listen on sockets and generate HTTP responses based on the requests i get from my clients on my fds, in short i use my browser to send a request, i end up getting the raw request, i parse it and generate the corresponding http response.
However in the case of large POST requests, usually what happens is that i get partial requests, so in the first part i will usually only find the first line (version/method/uri), some headers but no body, and i guess am supposed to get the rest of the body somehow, however i am unable to figure out two things,
first of all how do i know if the request i am getting is partial or completed from just the first part ? i am not getting any information relating to range, here's the first part i get when my client sends me a POST request.
POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 8535833
Cache-Control: max-age=0
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Origin: http://127.0.0.1:8081
Upgrade-Insecure-Requests: 1
DNT: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryOs6fsdbaegBIumqh
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://127.0.0.1:8081/
Accept-Encoding: gzip, deflate, br
Accept-Language: fr,en-US;q=0.9,en;q=0.8
how can i figure out just from this whether or not am getting a partial request or just a faulty request (I need to generate a 400 error in the case of a request that says it has X content-length but the body size is different)
second question is, suppose i already know whether or not its partial, how do i proceed with storing the entire request in a buffer before sending it to my parser and generating a response ? here's my reception function (i already know the client's fd, so i just recv on it
void Client::receive_request(void)
{
char buffer[2024];
int ret;
ret = recv(_fd, buffer, 2024, 0);
buffer[ret] = 0;
_received_request += buffer;
_bytes_request += ret;
std::cout << "Raw Request:\n" << _received_request << std::endl;
if (buffer[ret-1] == '\n')
{
_ready_request = true;
_request.parse(_received_request, _server->get_config());
}
}
and here's the code that checks whether or not a client is attempting to send a request, parse and generate a response
int Connections::check_clients() {
int fd;
for (std::vector<Client*>::iterator client = clients.begin();
client != clients.end() && ready_fd != 0 ; client++)
{
fd = (*client)->get_fd();
if (FD_ISSET(fd, &ready_rset))
{
ready_fd--;
(*client)->receive_request();
if ((*client)->request_is_ready())
{
(*client)->wait_response();
close(fd);
FD_CLR(fd, &active_set);
fd_list.remove(fd);
max_fd = *std::max_element(fd_list.begin(), fd_list.end());
free(*client);
client = clients.erase(client);
}
}
}
return 0;
}
as you can see am coding everything in C++ (98) and would rather not get answers that just dismiss my questions and refer me to different technologies or libraries, unless it will help me understand what am doing wrong and how to handle partial requests.
for info, am only handling HTTP 1.1(GET/POST/DELETE only) and i usually only get this issue when am getting a large chunked file or a file upload that has a very large body. thank you
PS : if needed i can link up the github repo of the current project if you wanna look further into the code
|
how can i figure out just from this whether or not am getting a partial request or just a faulty request (I need to generate a 400 error in the case of a request that says it has X content-length but the body size is different)
The body size is, by definition, the size of the Content-Length field. Any bytes that you receive afterwards belong to the next HTTP request (see HTTP pipelining). If you do not receive Content-Length bytes within a reasonable time period, then you can make the server issue a 408 Request Timeout error.
second question is, suppose i already know whether or not its partial, how do i proceed with storing the entire request in a buffer before sending it to my parser and generating a response ? here's my reception function (i already know the client's fd, so i just recv on it
Your posted code has at least the following problems:
You should check the return value of recv to determine whether the function succeeded or failed, and if it failed, you should handle the error appropriately. In your current code, if recv fails with the return value -1, then you will write to the array buffer out of bounds, causing undefined behavior.
It does not seem appropriate to use the line if (buffer[ret-1] == '\n'). The HTTP request header will be over when you encounter a "\r\n\r\n", and the HTTP request body will be over when you have read Content-Length bytes of the body. The ends of the header and body will not necessarily occur at the end of the data read by recv, but can also occur in the middle. If you want to support HTTP pipelining, then the additional data should be handled by the handler for the next HTTP request. If you don't want to support HTTP pipelining, then you can simply discard the additional data and use Connection: close in the HTTP response header.
You seem to be using a null terminating character to mark the end of the data read by recv. However, this will not work if a byte with the value 0 is part of the HTTP request. It is probably safe to assume that such a byte should not be part of the HTTP request header, but it is probably not safe to assume that such a byte won't be part of the HTTP request body (for example when using POST with binary data).
|
70,368,012 | 70,368,097 | Deduced type with 'auto &&' as function return type | In the following snippet, the function B::f() is a "wrapper" around the function A::f(). But I assume that A::f() return type is an "opaque" type which I don't know if it has a value or reference semantics. So I cannot use auto or const auto & as return type for B::f(). I thought that auto && would do the trick, but it does not as auto && is deduced as A::OpaqueType &... Is it possible here to avoid writing A::OpaqueType?
#include <iostream>
struct A {
using OpaqueType=int; // But it could have been `const int &`
OpaqueType f() const {
return i;
}
int i=42;
};
struct B {
// how could I use `auto` here to avoid writing the `A::OpaqueType`?
// I would have expected that `auto &&` would do the trick but it does not
A::OpaqueType f() const {
return a.f();
}
A a;
};
int main()
{
B b;
std::cout << b.f() << std::endl;
}
The following snippet confuses me, as I would have expected that the return type of f() and g() would be int, but it is int & for f() and int && for g() (I don't even understand why it is not the same)... How this can be explained?
#include <iostream>
auto &&f() {
int i=42;
return i;
}
struct A {
int f() {return i;}
int i=42;
};
auto &&g() {
A a;
return a.f();
}
int main()
{
if (std::is_same_v<decltype(f()), int &>) {
std::cout << "f() return type is 'int &'\n";
}
if (std::is_same_v<decltype(g()), int &&>) {
std::cout << "g() return type is 'int &&'\n";
}
}
Thanks!
| Pretty sure what you are looking for is decltype(auto). This will return by value if the expression in the return statement returns by value, and it will return by reference if the expression in the return statement returns by reference. That would give you
decltype(auto) f() const {
return a.f();
}
|
70,368,103 | 70,370,811 | How to Rotate a Quad | I'm trying to make a quad rotate around its center. I am using glm::rotate() and setting the quad to rotate on the z axis. However when I do this it gives this weird effect. The quad stretches and warps. It almost looks 3d but since I am rotating it around the z axis that shouldn't happen right?
Here's relevant code for context:
float rotation = 0.0f;
double prevTime = glfwGetTime();
while (!glfwWindowShouldClose(window))
{
GLCall(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
GLCall(glClear(GL_COLOR_BUFFER_BIT));
updateInput(window);
shader.Use();
glUniform1f(xMov, x);
glUniform1f(yMov, y);
test.Bind();
double crntTime = glfwGetTime();
if (crntTime - prevTime >= 1 / 60)
{
rotation += 0.5f;
prevTime = crntTime;
}
glm::mat4 model = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(rotation), glm::vec3(0.0f, 0.0f, 1.0f));
int modelLoc = glGetUniformLocation(shader.id, "model");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
vao.Bind();
vBuffer1.Bind();
iBuffer1.Bind();
GLCall(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0));
glfwSwapBuffers(window);
glfwPollEvents();
}
Shader:
#version 440 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aColor;
layout(location = 2) in vec2 aTex;
out vec3 color;
out vec2 texCoord;
uniform float xMove;
uniform float yMove;
uniform mat4 model;
void main()
{
gl_Position = model * vec4(aPos.x + xMove, aPos.y + yMove, aPos.z, 1.0);
color = aColor;
texCoord = aTex;
}
| Without you showing the graphical output it is hard to say.
Your first issue is, you are not rotating around the center, to rotate by the center you must, offset the quad so that its center is at 0,0. then rotate, then offset back to the original position, but you have this line:
gl_Position = model * vec4(aPos.x + xMove, aPos.y + yMove, aPos.z, 1.0);
Under the assumption that the quad as at the origin to begin with you are rotating it around the point (-xMove, -yMove).
|
70,369,048 | 70,369,111 | Where are the functions inside of structs stored in memory? | Let's say I have a struct like this:
struct 64BitStruct
{
uint64_t value;
void SomeFunction(bool enable);
bool SomeOtherFunction();
};
sizeof(64BitStruct) returns 8 bytes, which is 64 bits. I assume those 64bits are the value variable in the struct, but then where are the functions stored?
| Member functions are common functions of all objects of the structure type. So they are stored separately from objects. The size of the structure in your example is in fact the size of its data member. If a structure has virtual functions then it implicitly includes a pointer to the table of virtual function pointers as a data member for each object of the structure type.
|
70,369,264 | 70,369,524 | Thread 1: Breakpoint 1.1(1) | I'm trying to do a small project and I came over a breakpoint issue. I had it previously on char dirname[256] when I had a char holding it. However, after I removed the char it changed the breakpoint to the cout, which I never had before. I fairly new in c++ somewhat in-depth explanations would be nice. Thank you.
Code: C++
// main.cpp
// File Creator and Sorter
//
// Created by yared yohannes on 12/15/21.
//
#include <stdio.h>
#include <cstdio>
#include <dirent.h>
#include <iostream>
using namespace std;
int main(){
char dirname[256];
cout << "What is the name of the file: ";
cin >> dirname;
DIR *d = opendir(dirname);
if( ! d)
{ std:: cout << "ERROR: Please provide a valid directory path.\n"; }
}
| I think your problem is related to using XCode editor rather than coding. I recommend reading this article.
|
70,369,847 | 70,371,171 | Is there a way to programmatically find the current used GPU (C, C++)? | In the case of CPUs, the (linux specific) sys calls getcpu() or sched_getcpu() can be used inside a program to obtain the ID of the core executing them. For example, in the case of a 4 processors system, the logical index returned by the mentionned calls makes it possible to deduce which one of the 4 CPUs is being used (let's say every CPU contains 10 cores, therefore if sched_getcpu() returns 20, that means the CPU #2 is being used since the core number 20 is in the 3rd CPU).
How can I achieve a similar thing in the case of GPUs? Is there a way to find which one is being used in real time from inside an application?
| C++ has no concept of a GPU. You got a great comment pointing you to the right direction of getting some GPU info using OpenGL, I'm sure there are other cross platform libraries as well.
Take a look at the source code of neofetch which is a command-line system info tool which, among other things, gets your GPU(s). It uses a bunch of different methods to get the GPU on the current system, some of which may help point you to the right direction. For example, for linux systems it gets the gpu info using lspci -mm:
echo $(lspci -mm | awk -F '\"|\" \"|\\(' \
'/"Display|"3D|"VGA/ {
a[$0] = $1 " " $3 " " ($(NF-1) ~ /^$|^Device [[:xdigit:]]+$/ ? $4 : $(NF-1))
}
END { for (i in a) {
if (!seen[a[i]]++) {
sub("^[^ ]+ ", "", a[i]);
print a[i]
}
}}')
which returns NVIDIA Corporation GP107 [GeForce GTX 1050 Ti] for my system. But this is not cross platform. If you wanted to do it yourself you would thus have to either:
implement a way for every system your application will run on
lose cross-platform ability
Or simply use OpenGL as mentioned above.
|
70,370,506 | 70,511,481 | OpenCV threshold color image (by brightness, not per channel) | openCV seems to be doing per-channel threshold if I use cv::threshold on color image.
I use it to get rid of pixels that are not bright enough (cv::THRESH_TOZERO), and then overlay that (cv::add) on other image.
Works almost OK, but the problem is that it obviously works per-channel, so the colors get sometimes distorted (i.e. some of the channels get zeroed and others not). What I need is "zero out pixels whose brightness is not large enough".
Now I know I could iterate over the image in for cycle and just overwrite the pixel with zero if the sum of the channels is not over the threshold. But that's almost certainly not going to be performant enough to be run real-time on the low-power device I target (nVidia Jetson Xavier NX). OpenCV functions seem to be much better optimized.
Thanks!
| As suggested in the comments, the solution is to convert to grayscale, do the threshold which gives you a mask, and then do bitwise_and to only keep the pixels you want. Like this:
cv::UMat mask;
cv::cvtColor(img, mask, cv::COLOR_BGR2GRAY);
cv::threshold(mask, mask, threshold, 255, cv::THRESH_BINARY);
cv::cvtColor(mask, mask, cv::COLOR_GRAY2BGR);
cv::bitwise_and(img, mask, img);
|
70,370,782 | 70,686,551 | Can't set keep_alive to socket in asio | I'm trying to create a ServerSocket as a singleton. Here's the code:
ServerSocket.h
#pragma once
#include <asio.hpp>
#include <iostream>
#include <optional>
using asio::ip::tcp;
class ServerSocket
{
public:
ServerSocket(ServerSocket& otherSingleton) = delete;
void operator= (const ServerSocket& copySingleton) = delete;
tcp::acceptor* InitAcceptor();
tcp::socket* InitSocket();
void StartServerSocket();
void SendData(std::string);
std::optional<std::string> RecieveData();
static ServerSocket* GetInstance();
private:
static ServerSocket* instance;
tcp::acceptor* acceptor;
tcp::socket* socket;
asio::io_context io_context;
ServerSocket()
{
acceptor = InitAcceptor();
socket = InitSocket();
}
~ServerSocket() {
delete socket;
delete acceptor;
std::cout << "Server closed";
}
};
ServerSocket.cpp
#include "ServerSocket.h"
#include <optional>
tcp::acceptor* ServerSocket::InitAcceptor()
{
try
{
return new tcp::acceptor(io_context, tcp::endpoint(tcp::v4(), 27015));
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return nullptr;
}
tcp::socket* ServerSocket::InitSocket()
{
try
{
tcp::socket* deReturnat = new tcp::socket(io_context);
asio::socket_base::keep_alive option(true);
deReturnat->set_option(option);
return deReturnat;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return nullptr;
}
void ServerSocket::StartServerSocket()
{
try
{
std::cout << "Server started";
acceptor->accept(*socket);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
void ServerSocket::SendData(std::string)
{
}
std::optional<std::string> ServerSocket::RecieveData()
{
try
{
char data[5000];
asio::error_code error;
size_t length = socket->read_some(asio::buffer(data), error);
if (error == asio::error::eof) return std::nullopt; // Connection closed cleanly by peer.
else if (error)
throw asio::system_error(error); // Some other error.
return std::string{ data, length };
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return {};
}
ServerSocket* ServerSocket::instance(nullptr);
ServerSocket* ServerSocket::GetInstance()
{
if (instance == nullptr)
{
instance = new ServerSocket();
}
return instance;
}
The problem is that in InitSocket, when running a debugger, it seems like set_option doesn't work for some reason, and then an exception is thrown - and I can't understand why.
The exception that is thrown is: set_option: The file handle supplied is not valid.
How can I set the keep_alive option to true in my socket? It seems like this way doesn't work.
| @Vasile, your problem, as @dewaffed told you, is that you are setting the options before the socket has been opened.
I don't know what you are trying to do but I can see that you creating a new socket, which is not open, and setting the properties, that's the problem. The correct way is:
Create the Socket
Accept the new connection, with the previous socket you've created.
Once the acceptor has ended to accept a new connection, the socket has a valid File Descriptor, which is required to set the option over the socket.
Check these links:
https://en.wikipedia.org/wiki/Berkeley_sockets
Modifying boost::asio::socket::set_option, which talks about your exception.
https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio/tutorial/tutdaytime2.html
|
70,370,912 | 70,370,940 | Remove a Chunk of Items from a Vector? | I have a vector full of words and I am trying to erase a chunk of that vector at a specified beginning and end. For example:
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = { "The", "Quick", "Brown", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" };
remove_chunk(words, 1, 2);
}
Here, remove_chunk(words, 1, 2); would erase the items at index 1 through 2, leaving the vector to be:
{ "The", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" }
How would I go about efficiently writing remove_chunk? Is there an stl function for this or a quick one-liner?
| Use vector::erase:
words.erase(words.begin(), words.begin() + 2);
Note: Second iterator provided is words.begin() + 2 instead of words.begin() + 1 because STL uses [begin, end).
|
70,370,922 | 70,370,993 | C++ Using sizeof() to determine size of an Octree | Let's say Octree() is a container with Elements of type double.
Can I use sizeof(Octree) to determine how much memory in bytes is taken up by my octree?
Sizeof() should change if I change the resolution/depth of my octree - which does not seem to be the case when I test it.
Is there a way I could determine the dynamically allocated memory size of my octree?
| No. sizeof returns the size of the object. Which is the size of the type of the object. Which remains constant through the entire program. sizeof does not return the amount of memory that member functions of the object have allocated dynamically, and it cannot be overloaded to do so.
Is there a way I could determine the dynamically allocated memory size of my octree?
Certainly. You can keep track of all dynamic memory that you allocate, and their sizes together to get the total. This won't include overhead consumed by the data structure used by the allocator itself. There's no standard way to measure that.
|
70,371,091 | 70,371,265 | Silencing stdout/stderr | What is a C equivalent to this C++ answer for temporarily silencing output to cout/cerr and then restoring it?
How to silence and restore stderr/stdout?
(Need this to silence noise from 3rd party library that I am calling, and to restore after the call.)
| This is a terrible hack, but should work:
#include <stdio.h>
#include <unistd.h>
int
suppress_stdout(void)
{
fflush(stdout);
int fd = dup(STDOUT_FILENO);
freopen("/dev/null", "w", stdout);
return fd;
}
void
restore_stdout(int fd)
{
fflush(stdout);
dup2(fd, fileno(stdout));
close(fd);
}
int
main(void)
{
puts("visible");
int fd = suppress_stdout();
puts("this is hidden");
restore_stdout(fd);
puts("visible");
}
|
70,371,170 | 70,371,294 | OpenMP parallel for loop exceptions | I'm quite new to using OpenMP and to stackoverflow, so apologies if this is a stupid question!
I'm trying to set up a large 2d vector to test my CUDA program. The creation for these large vectors is done by looping through all the values of the given dimensions (stored in their own vectors) and creating a row in a new vector, covering all possible permutations. Obviously the time taken to do this increases exponentially as you increase the number of dimensions, so I am looking to parallelize it.
Originally I thought the problem may be an incompatibility between OpenMP and the Thrust library host_vectors, so I switched to using normal vectors and the problem is persisting. Here is the full function:
thrust::host_vector<thrust::host_vector<float>> parallel_create_search_grid(
thrust::host_vector<float> d1,
thrust::host_vector<float> d2,
thrust::host_vector<float> d3,
thrust::host_vector<float> d4) {
std::vector<std::vector<float>> final2;
#pragma omp parallel shared(d1, d2, d3, d4, final2)
{
int j, k, l;
std::vector<float> temp(4);
thrust::host_vector<float> h_temp;
#pragma omp for
for (int i = 0; i < d1.size(); i++)
{
for (j = 0; j < d1.size(); j++)
{
for (k = 0; k < d1.size(); k++)
{
for (l = 0; l < d1.size(); l++)
{
temp[0] = d1[i];
temp[1] = d2[j];
temp[2] = d3[k];
temp[3] = d4[l];
std::cout << i << "," << j << "," << k << "," << l << std::endl;
final2.push_back(temp);
}
}
}
}
}
return final2;
}
It doesn't break immediately, it prints out many iterations before an exception is thrown, giving me the following:
Exception thrown: read access violation. this->_Myproxy was
0xFFFFFFFFFFFFFFFF.
The source of the exception is the following function in xmemory, but what it means is beyond me:
_CONSTEXPR20_CONTAINER void _Container_base12::_Swap_proxy_and_iterators_unlocked(_Container_base12& _Right) noexcept {
_Container_proxy* _Temp = _Myproxy;
_Myproxy = _Right._Myproxy;
_Right._Myproxy = _Temp;
if (_Myproxy) {
_Myproxy->_Mycont = this;
}
if (_Right._Myproxy) {
_Right._Myproxy->_Mycont = &_Right;
}
}
Any help would be greatly appreciated. Thank you!
| Your problem is with the line `final2.push_back(temp)'. You have multiple threads pushing back into the same vector. That is not possible. Create the vector before the loop, and then write to explicit locations in it.
In general, try to avoid push_back as much as possible because it has performance problems. If you know the size of a vector, create it with that size. Scientific applications hardly ever need the dynamicism of push_back.
|
70,371,484 | 70,371,629 | FAST way to determine if first n bits of byte array are "0" | I have a function that computes the checkLeadingZeroBits as follows:
typedef std::array<uint8_t, 32> SHA256Hash;
bool checkLeadingZeroBits(SHA256Hash& hash, unsigned int challengeSize) {
int bytes = challengeSize / 8;
const uint8_t * a = hash.data();
if (bytes == 0) {
return a[0]>>(8-challengeSize) == 0;
} else {
for (int i = 0; i < bytes; i++) {
if (a[i] != 0) return false;
}
int remainingBits = challengeSize - 8*bytes;
if (remainingBits > 0) return a[bytes + 1]>>(8-remainingBits) == 0;
else return true;
}
return false;
}
I've also tried the following which is approximately the same run time:
bool checkLeadingZeroBits(SHA256Hash& hash, unsigned int challengeSize) {
int bytes = challengeSize / 8;
const uint8_t * a = hash.data();
if (bytes == 0) {
return a[0]>>(8-challengeSize) == 0;
} else {
if (memcmp(NULL_SHA256_HASH.data(), a, bytes) != 0) return false;
int remainingBits = challengeSize - 8*bytes;
if (remainingBits > 0) return a[bytes + 1]>>(8-remainingBits) == 0;
else return true;
}
return false;
}
I'd like to optimize this function to run as quickly as possible. Is there a simpler way to check the leading order bits than using the for loops shown in my implementation?
| As written, no. A raw byte array can't be scanned at the bit level faster than a byte by byte comparison operation.
However, if you're targeting a platform with a count leading zeros instruction or equivalent, you can speed up the process by checking blocks the size of a native processor word (32 bit for x86/ARM, 64 bit for AMD64/AA64). This would give you a slight improvement, but overall is likely not significant enough to be useful in this instance.
To do this, you would need to transform the data into a C pointer, then cast that to a pointer the same size as a word on the machine (uintptr_t*). From there, you could read out blocks of memory, and pass them to either the compiler intrinsic that would count the leading zeros of that word.
There are a few caveats to this. For one, you need to be very careful that your last read from the new pointer doesn't overstep into memory you don't own. Additionally, for x86 architectures prior to the introduction of lzcnt (before AMD ABM or Intel Haswell), you need to handle the case where the bsr (bit scan reverse, MSB to LSB) instruction finds no bits, which sets the zero flag instead of returning a real result (this will probably be invisible to you, or automatically transformed by the intrinsic, but I know MSVC's _BitScanReverse function returns true or false based on whether the instruction found a bit or not).
Ultimately, you're likely going to gain a marginal improvement in performance, which will likely be counterbalanced by the memory accesses you'll need to do to read data out of the buffer. Overall, it's not really worth it - the compiler will do a much better job of optimizing the loops than you will with all the instructions in the world. Better to write code that's clear and easily maintained than code that's fragile, obtuse, and reliant on processor specific instructions.
Which is a shame because I really like the lzcnt, bsr/bsf, and clz instructions. They can make scanning bitmaps significantly faster, but they aren't really useful here.
|
70,371,915 | 70,385,570 | FLTK: Clearing a graph when drawing another | I wrote a simple FLTK program to draw a circle when clicking on the "Draw Circle" button and to draw a line when clicking on the "Draw Line" button. I supposed to have only one graph. But I got two graphs in the panel. I want only one showing and the other disappearing. The following is the code:
#include <FL/Fl.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Double_Window.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Box.H>
using namespace std;
int flag = 0;
class Drawing : public Fl_Box {
void draw() {
fl_color(255, 0, 0);
int x, y, x1, y1;
if (flag == 1) {
double radius = 100;
x = (int)(w() / 2);
y = (int)(h() / 2);
fl_circle(x, y, radius);
}
else if (flag == -1) {
x = (int)(w() / 4);
y = (int)(h() / 4);
x1 = (int)(w() *3/ 4);
y1 = (int)(h() *3/ 4);
fl_line(x, y, x1, y1);
}
}
public:
Drawing(int X, int Y, int W, int H) : Fl_Box(X, Y, W, H) {}
};
Drawing* d;
void circle_cb(Fl_Widget*, void*) {
flag = 1;
fl_overlay_clear();
d->redraw();
} // end sumbit_cb
void line_cb(Fl_Widget*, void*) {
flag = -1;
fl_overlay_clear();
d->redraw();
} // end clear_cb
int main(int argc, char** argv) {
Fl_Window* window = new Fl_Window(600, 550); // create a window, originally(400,400)
Drawing dr(0, 0, 600, 600);
d = &dr;
Fl_Button *b, *c;
b = new Fl_Button(150, 80, 100, 25, "&Draw Circle");
b->callback(circle_cb);
c = new Fl_Button(350, 80, 100, 25, "&Draw Line");
c->callback(line_cb);
window->end(); //show the window
window->show(argc, argv);
return Fl::run();
}
I have used fl_overlay_clear() to clear graph. However it is not working. Any help will be appreciated.
| There are several issues that need to be fixed in your program, but first of all using the draw() method as you did is basically correct. However, using fl_overlay_clear(); is useless, you can remove it.
My solution: your widget doesn't have a solid background (boxtype), i.e. your draw method draws over the background over and over again w/o clearing it. There are several ways to solve this, but if you want to learn what happens, try this first: add window->resizable(window); before window->show(argc, argv);, run the program again and resize the window. You'll notice that the previous drawing disappears and only one drawing stays. That's because the background is cleared when you resize the widget.
Next step: add a solid boxtype:
d = &dr;
d->box(FL_DOWN_BOX);
and add Fl_Box::draw(); right at the beginning of your draw() method.
If you do that you may notice that your button(s) disappear when you click one of them - because your buttons are inside the area of your Drawing. The last thing(s) I fixed was to correct the coordinates of buttons and to enlarge the window (it was too small anyway to cover the entire Drawing). Here's my complete result:
#include <FL/Fl.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Double_Window.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Box.H>
using namespace std;
int flag = 0;
class Drawing : public Fl_Box {
void draw() {
Fl_Box::draw();
fl_color(255, 0, 0);
int x, y, x1, y1;
if (flag == 1) {
double radius = 100;
x = (int)(w() / 2);
y = (int)(h() / 2);
fl_circle(x, y, radius);
} else if (flag == -1) {
x = (int)(w() / 4);
y = (int)(h() / 4);
x1 = (int)(w() * 3 / 4);
y1 = (int)(h() * 3 / 4);
fl_line(x, y, x1, y1);
}
}
public:
Drawing(int X, int Y, int W, int H)
: Fl_Box(X, Y, W, H) {}
};
Drawing *d;
void circle_cb(Fl_Widget *, void *) {
flag = 1;
// fl_overlay_clear(); // not useful
d->redraw();
} // end sumbit_cb
void line_cb(Fl_Widget *, void *) {
flag = -1;
// fl_overlay_clear(); // not useful
d->redraw();
} // end clear_cb
int main(int argc, char **argv) {
Fl_Window *window = new Fl_Window(600, 660); // create a window, originally(400,400)
Drawing dr(0, 60, 600, 600); // FIXED
d = &dr;
d->box(FL_DOWN_BOX); // ADDED
Fl_Button *b, *c;
b = new Fl_Button(150, 20, 100, 25, "&Draw Circle"); // FIXED
b->callback(circle_cb);
c = new Fl_Button(350, 20, 100, 25, "&Draw Line"); // FIXED
c->callback(line_cb);
window->end(); // show the window
window->resizable(window); // ADDED
window->show(argc, argv);
return Fl::run();
}
I believe this does what you want.
PS: the official FLTK support forum can be found on our website https://www.fltk.org/ and the direct link to the user forum (Google Groups) is https://groups.google.com/g/fltkgeneral
|
70,373,555 | 70,374,564 | While template deduction, is it possible to detect if a consteval function could be run | Let's say we have a consteval function or a trivial struct with consteval construnctor, which only accept some of the values:
struct A
{
consteval A(int a)
{
// compile error if a < 0
if (a < 0)
throw "error";
}
};
Is there any way to detect if a non-type template parameter of int could be accepted by such a constructor? I have tried the following code but failed.
template <int a> concept accepted_by_A = requires() {A(a);};
int main()
{
std::cout << accepted_by_A<-1> << std::endl; // output 1 (true)
}
| Since a call to a constexpr (or consteval) function that throws is not a constant expression, you can detect this:
template<int I> concept accepted_by_A=
requires() {typename std::type_identity_t<int[(A(I),1)]>;};
static_assert(accepted_by_A<1>);
static_assert(!accepted_by_A<-1>);
It's also possible to use SFINAE (which would allow it to work with constexpr in previous language versions):
template<int,class=void> struct test : std::false_type {};
template<int I> struct test<I,decltype(void((int(*)[(A(I),1)])nullptr))> : std::true_type {};
static_assert(test<1>());
static_assert(!test<-1>());
An alternate specialization
template<int I> struct test<I,typename voided<int[(A(I),1)]>::type> : std::true_type {};
seems like it ought to work but doesn't; substitution of non-type template arguments is weird in some cases.
|
70,373,615 | 70,389,342 | cmake find_package: why cannot find some components in boost | Find_package command is a nightmare to me.
I am trying to include some specified components in boost into my project.
Some components could not be found with find_package command for different error.
Can anyone help to explain the error reported?
case 1:
cmake_minimum_required(VERSION 3.15)
project(tryBoost)
set(CMAKE_CXX_STANDARD 14)
set(BOOST_ROOT "D:\\cygwin64\\home\\yubo\\boost_1_62_0") # either set it here or from the command line
find_package(Boost 1.62.0 REQUIRED COMPONENTS json) # header only libraries must not be added here
add_executable(tryBoost main.cpp)
I try to find json, but error reported:
No header defined for json; skipping header check
case 2:
cmake_minimum_required(VERSION 3.15)
project(tryBoost)
set(CMAKE_CXX_STANDARD 14)
set(BOOST_ROOT "D:\\cygwin64\\home\\yubo\\boost_1_62_0") # either set it here or from the command line
find_package(Boost 1.62.0 REQUIRED COMPONENTS system) # header only libraries must not be added here
add_executable(tryBoost main.cpp)
I try to find system, but error reported:
Could NOT find Boost (missing: Boost_INCLUDE_DIR system)
How boost organizes its components in sub dirs? How find_package command works when scaning boost root dir? why "header only libraries must not be added here".
thanks.
| Please use below CMakeList.txt for reference.
cmake_minimum_required(VERSION 3.15)
project(tryBoost)
set(CMAKE_CXX_STANDARD 14)
#set(Boost_DEBUG ON)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(BOOST_ROOT "/home/yubo/boost_1_78_0")
add_executable(tryBoost main.cpp)
set(Boost_NO_BOOST_CMAKE FALSE CACHE BOOL "" FORCE)
find_package(Boost 1.78.0 REQUIRED COMPONENTS json)
message("${Boost_FOUND}")
message("Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
target_include_directories(tryBoost PUBLIC ${Boost_INCLUDE_DIRS})
message("Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}")
message("Boost_LIBRARIES: ${Boost_LIBRARIES}")
target_link_libraries(tryBoost ${Boost_LIBRARIES})
|
70,373,631 | 70,373,699 | when alignof operator used in struct does it affect sizeof | struct s11
{
alignas(16) char s;
int i;
};
does alignas(n) X x mean it would allocate n bytes to hold a X, when X is actually much smaller than n bytes, the rest memory would be all 0s?
when s11.s is in memory 0x0, does that mean s11.i would be at 0x10? However, the following pdiff is 0x4
s11 o;
ptrdiff_t pdiff = (char*)&o.i - (char*)&o.s;
Please explain why sizeof(s11) is not 16 times 2, while sizeof(s1) is 8 times 3?
struct s1
{
char s;
double d; // alignof(double) is 8.
int i;
}
EDIT:
This is what I found after a lot of digging and code snippets, that how alignas affect struct(class) size.
alignas(n) X x means in memory x is located at a place with an offset of multiple of n bytes, starts from 0x00. Therefore, s11.s can be located at 0x00, 0x10, 0x20 and so on. Because s11.s is the first field, it is at 0x00, and it is a char, so it ocupies 1 bytes.
So is the 2nd field. int has an align 4, therefore it can be located at 0x00, 0x04, 0x08, 0x0c, etc. Because the first byte is taken by s11.s, so s11.i is located at 0x04.
|
No, it means the starting address of the member s must be aligned on a 16-byte boundary. Probably in the case of it being the first member of a struct, this will result in the struct itself adopting that alignment and not affecting the size.
No, there is no specified alignment pertaining to the member i, so normal alignment rules apply. If you're getting 4 then your system is using integers that have a size of 4 bytes, and are similarly aligned. The value of padding bytes is unspecified.
The first explanation is in my answer to #2. Follow-up incorporting the answer to #1, the size will probably be 16 due to the required structure alignment. And sizeof(s1) is 8 times 3 because of the alignment requirements of the double member causing padding elsewhere, combined with the entire structure's alignment. Moving the char member to the end of the structure will reduce the total size.
|
70,373,694 | 70,375,191 | cin: No Operator Found Which Takes A Left-Hand Operand | I'm trying to get two space-separated variables and running into this error, as well as [no operator ">>" matches these operands] and [syntax error: ">>"].
#include <iostream>
#include <string>
#include <vector>
using namespace std;
...
void player(char array[][ROWS_AND_COLUMNS], char letter)
{
bool element_occupied = false;
do
{
int row = 0;
int column = 0;
cout << "Enter player " << letter << ", row and column:";
cin >> inputValidate(row, 1, 3) >> inputValidate(column, 1, 3);
if (array[(row - 1)][(column - 1)] == '*')
{
array[(row - 1)][(column - 1)] = letter;
element_occupied = true;
}
else
{
cout << "Sorry, that spot is taken." << endl;
element_occupied = false;
}
} while (element_occupied == false);
}
inputValidate() takes the input, minimum value, and maximum value, and returns the input value if it is 1, 2, or 3.
EDIT:
int inputValidate(int user_number, int lowest, int highest)
{
while (!(cin >> user_number) || (user_number < lowest || user_number > highest))
{
cout << "Error. Enter a number from " << lowest << " to " << highest << ": ";
cin.clear();
}
return user_number;
}
This is a tic-tac-toe game.
| inputValidate() returns a temporary int, an rvalue, which operator>> can't read into. It expects an lvalue instead (ie, a variable with a name). That is why you are getting errors on the cin >> inputValidate(...) statement.
Even if the statement could compile, it simply doesn't make sense to use. inputValidate() does its own reading of cin, so player() shouldn't be trying to pass the return value of inputValidate() to cin >> to begin with. inputValidate() would read in a validated number and return it, then player would be trying to read in a new unvalidated number to overwrite it.
For that matter, there is no point in passing in the user_number parameter at all. You are passing it in by value, just to immediately overwrite it with user input. So the value passed in by player() is irrelevant. If you want to return the user's input then user_number should be a local variable inside of inputValidate(). Otherwise, it should be an output parameter passed by reference instead, and inputValidate()'s return value should be void.
Also, when operator>> fails inside of inputValidate() due to invalid input, you are not discarding the input that caused it to fail. cin.clear() only resets the stream's error state, it does not discard any data. You need to call cin.ignore() for that.
With that said, try something more like this:
#include <iostream>
#include <string>
#include <vector>
#include <limits>
using namespace std;
...
int inputValidate(int lowest, int highest)
{
int user_number;
do
{
if (!(cin >> user_number))
{
cout << "Invalid. Enter a valid number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (user_number < lowest || user_number > highest)
{
cout << "Error. Enter a number from " << lowest << " to " << highest << ": ";
}
else break;
}
while (true);
return user_number;
}
void player(char array[][ROWS_AND_COLUMNS], char letter)
{
int row, column;
do
{
cout << "Enter player " << letter << ", row and column:";
row = inputValidate(1, 3) - 1;
column = inputValidate(1, 3) - 1;
if (array[row][column] == '*')
break;
cout << "Sorry, that spot is taken." << endl;
}
while (true);
array[row][column] = letter;
}
|
70,374,120 | 70,374,240 | Getting subscript out of range after vector resize | I have a 2D vector of string. It has some data in it already - generally speaking all rows (should) have the same number of columns.
I am looking to resize the matrix by increasing the number of columns by 1.
std::vector<std::vector<std::string>> completeMatrix;
matrixRowNum = completeMatrix.size();
matrixColumnNum = completeMatrix[0].size();
completeMatrix.resize(matrixRowNum, std::vector<std::string>(matrixColumnNum + 1)); //My attempt to resize by 1. Same result if I try 20.
completeMatrix[0][matrixColumnNum] = "inputString"; //getting subscript out of range error here.
completeMatrix[0][matrixColumnNum-1] = "inputString"; //however this works fine. it's like I never called resize.
What am I missing?
(if there's a better way to do this than vectors, I'll take any recommendations along those lines as well).
(if helpful, I am on Windows 10 using Visual Studio 2019).
| Your resize call only affects new rows. All existing rows are unaffected.
But you're not even adding rows! You called resize and passed the same value as the current size. So nothing will happen. It seems you have a misunderstanding of how much magic and mind-reading happens inside this call.
You will need to iterate through your rows and resize each one. Here is one way you could do it:
typedef std::vector<std::vector<std::string>> StringMatrix;
void AddColumns(StringMatrix& m, size_t count = 1, const std::string& val = "inputString")
{
if (m.empty() || count < 1)
return;
size_t cols = m.front().size() + count;
for (auto& row : m)
row.resize(cols, val);
}
|
70,375,007 | 70,375,126 | What is "using namespace::std" in C++ | I am reading some code snippets from others and I find a line:
using namespace::std;
I suspect its purpose is using namespace std;, with some typos. But to my surprise the compiler accepts this code without any complaint. I build with:
$ g++ --version
g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
$ /usr/bin/g++ ${SRC} -std=c++11 -pthread -Wall -Wno-deprecated -o ${OUT}
I wonder why is this code valid, and what effects will it make? I suspect it is a bad practice.
| using namespace::std is the same as using namespace std;
The :: symbol is the scope resolution operator. When used without a scope name before it , it refers to the global namespace. This means that std is a top level namespace, and is not enclosed in another.
The spaces before and after the :: are optional in this case because the lexer can deduce the tokens from the context.
For example, all of the following are valid:
namespace A { namespace notstd{} } // define my own namespaces A and A::notstd
using namespace::std; // the standard library std
using namespace A;
using namespace ::A;
using namespace::A;
using namespace A::notstd;
Update:
As noted in one of the comments, using namespace ::std; and using namespace std; may actually lead to different results if the statement comes inside another namespace which contains its own nested namespace std. See the following (highly unlikely) example:
#include <stdio.h>
namespace A {
namespace std {
int cout = 5;
}
using namespace std;
void f1() {
cout++;
}
}
int main()
{
A::f1();
printf("%d\n",A::std::cout); // prints 6
return 0;
}
|
70,375,087 | 70,375,700 | did const int& pass a reference or a copy | For example,
void func(const int& a);
int main()
{
int b=1;
func(b*2);
}
If the const int& will pass a reference, how can b*2 be a reference?
So it means it only pass a copy of b*2 to func()?
But if so, did func(b) really pass a reference of b?
Am I right?
| It's simple:
int b = 1;
Here, b is an lvalue. so when you write func( b ) then you are passing an lvalue to the func. And it works since func can take an lvalue by reference.
But:
func( b*2 );
Here, b*2 is a prvalue (which is under the rvalue category) and when you write func( b*2 ); then you are passing an rvalue to the func. And it works since void func(const int& a); has a const lvalue reference parameter and const lvalue references can bind to rvalues.
Now if you rewrite your function like this void func(const int&& a); so that it only takes rvalues as its argument (notice the &&), then func( b*2 ) will still compile but func( b ) won't because b is an lvalue and lvalues can not be moved unless you cast it to an xvalue (which is also under the rvalue and glvalue category) like this:
func( std::move( b ) )
In short, std::move casts an lvalue to an xvalue to tell the compiler that it is temporary and thus can be moved from.
For the sake of completeness:
In C++11, expressions that:
have identity and cannot be moved from are called lvalue expressions;
have identity and can be moved from are called xvalue expressions;
do not have identity and can be moved from are called prvalue ("pure rvalue") expressions;
do not have identity and cannot be moved from are not used.
The expressions that have identity are called "glvalue expressions" (glvalue stands for "generalized lvalue"). Both lvalues and xvalues are glvalue expressions.
The expressions that can be moved from are called "rvalue expressions". Both prvalues and xvalues are rvalue expressions.
Check value category for more info.
|
70,375,285 | 70,395,973 | Condition Variable wait_until timeout_time in the past? | If I call std::condition_variable::wait_until and pass a timeout_time that is in the past, is it guaranteed to return std::cv_status::timeout? Or is there a short window in which a notification could be delivered that results in the condition variable being unblocked the "normal" way with std::cv_status::no_timeout?
Context: I'm implementing a timer collection manager, and intend use a wait_until on a condition variable to implement timer expiry. The simplest implementation of my desired semantics may involve passing a timeout_time in the past to std::condition_variable::wait_until and relying on it immediately returning std::cv_status::timeout (for example in case one timer expires while the processing for another timer is ongoing).
Note that my stdlib's implementation of wait_until defers to pthread_cond_timedwait, so any guarantees made by that API are applicable in this case.
| TL;DR: (i) the return value of std::condition_variable::wait_until() does not appear to be guaranteed by C++ under the conditions specified, though the analogous pthreads function does guarantee that a timeout will be signaled under those conditions; (ii) even in the case where the timeout time is already past, the method's return could be delayed for an arbitrary length of time; and (iii) a single execution of the method might both consume a signal and report a timeout.
In more detail:
If I call std::condition_variable::wait_until and pass a timeout_time that is in the past, is it guaranteed to return std::cv_status::timeout?
All versions of the spec since the introduction of <condition_variable> say substantially the same thing about the return value, for example:
Returns: cv_status::timeout if the absolute timeout (32.2.4) specified by abs_time expired, otherwise cv_status::no_timeout.
(C++20 draft 4849, paragraph 32.6.3/21)
The specs overall do not explicitly define what it means for the timeout to have expired, however. I am inclined to think that the timeout already being in the past at the time of the call should count as "the absolute timeout [...] expired", yet many other methods' specifications explicitly address behavior when the absolute timeout is already in the past at the time the method is invoked, whereas this method's do not. I cannot rule out that omission being intentional.
Since you have tagged pthreads, the design of the <condition_variable> API is strongly influenced by those specifications, and UNIX implementations of <condition_variable> typically involve thin wrappers around pthreads functions, it may be illuminating to consider the specifications for pthread_cond_timedwait(). Among them:
an error is returned if the absolute
time specified by abstime passes (that is, system time equals or
exceeds abstime) before the condition cond is signaled or broadcasted,
or if the absolute time specified by abstime has already been passed
at the time of the call.
(Emphasis added)
Thus pthread_cond_timedwait() will definitely return an error signaling a timeout if the timeout time is already in the past when that function is called, and a wait_until() implementation that decides on that basis whether to return cv_status::timeout will behave analogously.
But also, successful completion of pthread_cond_timedwait() does not imply that the timeout has not expired by the time the function returns, and even if the function could make such a guarantee, the thread calling that function could not safely assume that the timeout would not expire between the function returning and the evaluation of a test of its return value.
Do pay careful attention to the additional provisions, as well:
When such timeouts occur,
pthread_cond_timedwait() shall nonetheless release and re-acquire the
mutex referenced by mutex, and may consume a condition signal directed
concurrently at the condition variable.
Such a release and reaquisition of the mutex / lock is also explicitly specified by C++. It says the effects of wait_until() are:
Atomically calls lock.unlock() and blocks on *this.
When unblocked, calls lock.lock() (possibly blocking on the lock), then returns.
The function will unblock [... after] expiration of the absolute timeout [...]
(C++20 draft 4849, paragraph 32.6.3/18)
Thus, wait_until() unconditionally releases the lock, and even if it unblocks right away on account of timeout, it must then reacquire the lock. This leaves open the possibility that another thread acquires the lock in between, in which case that other thread can hold the lock for an arbitrary amount of time, delaying the return of the wait_until(). This might be a more serious problem for your implementation plan than uncertainty about the method's return value.
|
70,375,360 | 70,375,564 | Explicit instantiantion of template member in cpp file doesn't generate symbol (i.e. link error) | Take the following example:
// A.h
class A
{
public:
int v = 2;
template <typename T>
int f(T t);
};
// A.cpp
#include "A.h"
template <typename T>
int A::f(T t)
{
return v + t;
}
template <>
int A::f<int>(int t);
// main.cpp
#include <stdio.h>
#include "A.h"
int main()
{
A a;
printf("%d\n", a.f(3));
return 0;
}
When building this with clang -std=c++14 (or g++), I get the following error:
main.cpp:8: undefined reference to `int A::f<int>(int)'
Indeed, nm A.o doesn't show any symbols. Why didn't the explicit instantiation of A::f<int> inside A.cpp actually instantiate the function?
| I think @JaMiT got the answer.
template <> int A::f<int>(int t)
{
// full specialization of templated thing
}
Is a full specialization.
template <> int A::f<int>(int t);
Is a declaration that such a specialization exists, but doesn't provide the definition.
The form you want is
template int A::f<int>(int t);
Which is an instantiation of the member function.
|
70,376,693 | 70,376,967 | C++ Interface, What's the best way to not duplicate code | I have this problem:
I have an Event Manager that call the event function do()
Event *p;
//p takes it values from an Event Queue
p->do()
Some Events have two attributes Object a and b
class EventX : public Event {
public :
EventX();
void do(){actionX(a, b)}
private :
Object a;
Object b;
bool bothSide;
};
class EventY : public Event {
public :
EventY();
void do(){actionY(a,b);}
private :
Object a;
Object b;
bool bothSide;
};
do() is a function that carries out an action from a to b.
I want to create an interface that can call do() from a to b and do() from b to a if bothSide attribute is true.
Is that possible ? I have many Event with differents do() functions that perform different actions from a to b.
Thank you for reading
| You can have extra layer with another interface
struct EventAB : Event
{
void do() final { if (bothSide) action(b, a); action(a, b); }
virtual void action(Object&, Object&) = 0;
/*...*/
private:
Object a;
Object b;
bool bothSide = false;
};
And then
class EventX : public EventAB {
public:
void action(Object& lhs, Object& rhs) override { actionX(lhs, rhs); }
// ...
};
class EventY : public EventAB {
public:
void action(Object& lhs, Object& rhs) override { actionY(lhs, rhs); }
// ...
};
|
70,376,909 | 70,376,951 | Getting an unusual output for a simple constructor program in C++ | I am a novice at C++ and have encountered an unusual error while trying to learn about constructors. Here I am trying to make x = 5 and y = 6, then have the program print them out to the screen.
This is my program ->
#include <iostream>
using namespace std;
class class1 {
public:
int x;
int y;
class1(int x, int y) {
x = x;
y = y;
}
}
int main() {
class1 class1obj(5, 6);
cout << class1obj.x << endl << class1obj.y;
}
This is my output after 3 runs ->
1st run
172691493
1
2nd run
126890021
1
3rd run
226783269
1
As you can see from the outputs, y seems to be a constant '1' whereas x just seems to change continuously through random numbers.
This program is fairly simple so I have not a clue on what is going wrong here.
It should also be noted that I am on a mac OS big sur and I use g++ -std=c++11 as my compiler as g++ does not seem to work for all my programs (and yes I have tried g++ on its own for this specific program and it still does not work).
Any help will be much Appreciated!
| This :
class1(int x, int y) {
x = x;
y = y;
}
is called shadowing. A variable shadows another one of same name. x = x just assigns the value of the parameter x to itself and the members are left uninitialized. The compiler has no way to know that you want one x to be the member and the other be the parameter, instead the parameter is said to "shadow" the member and in x = x; the x is the parameter. You should use different names:
class1(int a, int b) {
x = a;
y = b;
}
or use the member initializer list (which you should prefer anyhow):
class1(int a, int b) : x(a),y(b) {}
There is no ambiguity in the initializer list about what x refers to:
class1(int x, int y) : x(x),y(y) {}
In x(x) the first x can only refer to the member and the second x can only refer to the argument.
|
70,377,208 | 70,377,711 | Different amount of template variables | I have to implement a class depending on std::multiset. The idea is that when two multisets get into the same "view", my class needs to sort them, make operators and iterators, etc., but I'm stuck on basically the first step. The problem is that I'd need to create the same class, just with different amount of template variables. The main program calls my class like this, for example:
multisets_merge_view<int> mvi(a, b); //a and b are std::multiset<int>
multisets_merge_view<int, std::greater<int>> mvi(ga, gb); //ga and gb are std::multiset<int, std::greater<int>>
I need to use the g++ compiler with -fsanitize=address,leak,undefined -O3 -Wall -Wextra -Werror
| A pretty simple way to solve the issue would be providing a default argument for the comparator:
template <typename T, typename C = std::less<T>>
class multisets_merge_view { /* ... */ };
Since C++17 you can rely on class template argument deduction, which can simplify usage of your template class pretty much – you don't even have to provide a deduction guide for:
template <typename T, typename C>
class multisets_merge_view
{
public:
multisets_merge_view (std::multiset<T, C>& x, std::multiset<T, C>& y);
};
// the deduction guide (but not necessary)
template <typename T, typename C>
multisets_merge_view(std::multiset<T, C>& x, std::multiset<T, C>& y)
-> multisets_merge_view <T, C>;
This allows using your class like:
multisets_merge_view mvi(a, b);
multisets_merge_view mvi_g(ga, gb);
Note: There's no need to specify any template arguments at all any more...
Yet another variant is having your view class totally generic:
template <typename T>
class generic_merge_view
{
using Compare = typename T::key_compare;
public:
generic_merge_view(T& x, T& y)
{
// just for demonstration
Compare c;
for(auto ix = x.begin(), iy = y.begin(); /*...*/; ++ix, ++iy)
{
if(c(*ix, *iy))
{
// do something
}
}
}
};
You profit from duck-typing: As long as a type provides all the features the template requires – in this case the key_compare typedef and the ability to iterate – you can use it, this would comprise e.g. std::set, std::map and std::multimap as well.
The template type then differs, though (it's the set or map itself, not just the set/map's template arguments), but with CTAD you don't need to care for...
|
70,377,521 | 70,377,998 | Default template parameter cannot be used inside another template parameter? | I have a class template with a default value for the template parameter:
template<typename T = int>
class DefaultType : private std::array<T, 5> { };
and since c++17 this can be instantiated like a normal class
DefaultType obj; // equivalent to `DefaultType<>`
The same thing cannot be done if I use this type as an argument for another template:
// error: type/value mismatch at argument 1 in template parameter list for ...
class Foo : public std::vector<DefaultType> { };
yet, the above snippet does compile with DefaultType<>.
(godbolt)
what's the reason for that? would a deduction guide help? and what about NTTPs?
| This:
DefaultType obj;
uses CTAD (class template argument deduction) which is available since C++17 and only in certain contexts:
any declaration that specifies initialization of a variable and variable template
new-expressions
function-style cast expressions
the type of a non-type template parameter:
To instantiate DefaultType with the default argument in other contexts you still need to write DefaultType<>.
I suppose the reason to have CTAD only in certain contexts is that those are the contexts where you always want an instantiation, but never the template.
|
70,378,204 | 70,428,990 | How to catch `abi::__forced_unwind` while keeping UBSan happy? | Like libstdc++, we're checking in some places for abi::__forced_unwind, and just re-throw it instead of taking some other action. Like libstdc++, we catch it by reference:
try {
/* ... */
} catch (abi::__forced_unwind&) {
throw;
} catch (...) {
/* ... */
}
But if we actually pthread_cancel to exercise the code, ubsan complains:
runtime error: reference binding to null pointer of type 'struct __forced_unwind'
Here, it doesn't matter whether we catch by const-ref or mutable ref.
Are we (and libstdc++) actually running into UB here, or is it a False Positive in GCC's UBSan implementation?
| This is a bug in the forced unwinding implementation, which has been filed in the GCC Bugzilla as ticket #100415. (Arguably it should be fixed in GCC itself, as you’re not creating an actual reference binding, only matching on the exception type.)
While it is being fixed, you can decorate the function containing the catch clause with the [[gnu::no_sanitize("null")]] attribute, which will suppress null checking for references and nothing else:
#include <pthread.h>
#include <cxxabi.h>
#include <iostream>
int main() {
pthread_t thrd;
pthread_create(
&thrd, nullptr,
[] [[gnu::no_sanitize("null")]] (void *) -> void * {
try {
pthread_exit(nullptr);
} catch (abi::__forced_unwind const &fu) {
std::cerr << "forced unwind with " << &fu << std::endl;
// does not trigger UBSan
int &x = *static_cast<int *>(nullptr);
// triggers UBSan
1 / 0;
throw;
}
}, nullptr);
pthread_join(thrd, nullptr);
// triggers UBSan
int &x = *static_cast<int *>(nullptr);
return 0;
}
|
70,378,431 | 70,384,089 | Reducing duplicate code for function implementation | Unfortunately, I get stuck with a problem with duplicated source code.
Here is a small example to illustrate my problem:
class cPlayer
{
public:
struct Properties
{
std::vector<cStreet*> Streets;
std::vector<cHouse*> Houses;
std::vector<cComputer*> Computers;
std::vector<cBook*> Book;
};
cPlayer(std::string name) : m_name{name}{};
~cPlayer(){};
std::string m_name{};
Properties m_Properties;
// function overloaded
void buy(cStreet& Street);
void buy(cHouse& House);
void buy(cComputer& Computer);
void buy(cBook& Book);
};
void cPlayer::buy(cStreet& Street)
{
std::cout << m_name.c_str() << " : Do you want buy this Street?" << std::endl;
//Todo: Decision (here yes)
m_Properties.Streets.push_back(&Street);
};
void cPlayer::buy(cHouse& House)
{
std::cout << m_name.c_str() << " : Do you want buy this House?" << std::endl;
//Todo: Decision (here yes)
m_Properties.Houses.push_back(&House);
};
void cPlayer::buy(cComputer& PC)
{
std::cout << m_name.c_str() << " : Do you want buy this PC?" << std::endl;
//Todo: Decision (here yes)
m_Properties.Computers.push_back(&PC);
};
void cPlayer::buy(cBook& Book)
{
std::cout << m_name.c_str() << " : Do you want buy this Book?" << std::endl;
//Todo: Decision (here yes)
m_Properties.Book.push_back(&Book);
};
So the 4 member functions buy() actually all have the same logic. However, an individual text is output and the individual std::vector is always used. It would of course be much more elegant to implement the function only once. But how?
I had only thought of templates, but how can I switch the correct vector() to save the property?
Question after question. Would be great if I could get food for thought, as such a "problem" often appears in my source code.
THANK YOU!
| One possible way of doing this is using templates and std::map. In particular, by making the buy member function to be a member function template as shown below:
Method 1
Step 1
Creating a std::map
std::map<std::type_index, void*> myMap{{typeid(cStreet*), &m_Properties.Streets},
{typeid(cHouse*), &m_Properties.Houses},
{typeid(cComputer*), &m_Properties.Computers},
{typeid(cBook*), &m_Properties.Book}};
Step 2
Add declaration for member function template buy<> inside class cPlayer
template<typename T> void buy(T& Arg);
Step 3
Implement buy<>
template<typename T> void cPlayer::buy(T& Arg) // - STEP 3
{
std::cout << m_name.c_str() << " : Do you want buy this ?" <<typeid(Arg).name() << std::endl;
//Todo: Decision (here yes)
(*static_cast<std::vector<decltype(&Arg)>*>(myMap.at(typeid(&Arg)))).push_back(&Arg);
}
Overall Modification
So the modified code will look something like below:
class cPlayer
{
public:
struct Properties
{
std::vector<cStreet*> Streets;
std::vector<cHouse*> Houses;
std::vector<cComputer*> Computers;
std::vector<cBook*> Book;
};
cPlayer(std::string name) : m_name{name}{};
~cPlayer(){};
std::string m_name{};
Properties m_Properties;
//create std::map - STEP 1
std::map<std::type_index, void*> myMap{{typeid(cStreet*), &m_Properties.Streets},
{typeid(cHouse*), &m_Properties.Houses},
{typeid(cComputer*), &m_Properties.Computers},
{typeid(cBook*), &m_Properties.Book}};
//create member function template - STEP 2
template<typename T> void buy(T& Arg);
};
template<typename T> void cPlayer::buy(T& Arg) // - STEP 3
{
std::cout << m_name.c_str() << " : Do you want buy this ?" <<typeid(Arg).name() << std::endl;
//Todo: Decision (here yes)
(*static_cast<std::vector<decltype(&Arg)>*>(myMap.at(typeid(&Arg)))).push_back(&Arg);
}
Method 2
This uses std::any as the mapped_type of the std::map.
class cPlayer
{
public:
struct Properties
{
std::vector<cStreet*> Streets;
std::vector<cHouse*> Houses;
std::vector<cComputer*> Computers;
std::vector<cBook*> Book;
};
cPlayer(std::string name) : m_name{name}{};
~cPlayer(){};
std::string m_name{};
Properties m_Properties;
//create std::map - STEP 1
std::map<std::type_index, std::any> myMap{ {typeid(cStreet*), std::ref(m_Properties.Streets)},
{typeid(cHouse*), std::ref(m_Properties.Houses)},
{typeid(cComputer*), std::ref(m_Properties.Computers)},
{typeid(cBook*), std::ref(m_Properties.Book)}
};
//create member function template - STEP 2
template<typename T> void buy(T& Arg);
};
template<typename T> void cPlayer::buy(T& Arg) {// - STEP 3
std::cout << m_name.c_str() << " : Do you want buy this ?" <<typeid(Arg).name() << std::endl;
std::any_cast<std::reference_wrapper<std::vector<T*>>>(myMap.at(typeid(T*))).get().push_back(&Arg);
}
|
70,378,650 | 70,378,897 | Does forward declaration fully remove the need for any #including for pointer types? | Let's assume that we have a source file A.cpp where we forward declare a type ClassB, and then we keep using pointers to ClassB without ever #including file B.cpp (where ClassB is defined); And in B.cpp we forward declare ClassA and use a pointer to it without ever #including A.cpp (where ClassA is defined), then is the compiler fully happy with that? and will symbols resolution work just fine? In other words, do these two object files need not know about one another at all before link-time?
(I am assuming compiling C++ code on visual studio without any changes to the default compiler)
PS:
File A.cpp
class ClassB;
class ClassA
{
bool JustTakeAClassBPointAndDoNothingWithIt(ClassB* class_b_pointer)
{
if(class_b_pointer)
return true;
else
return false;
return false;
}
}
File B.cpp
class ClassA;
class ClassB
{
bool JustTakeAClassAPointAndDoNothingWithIt(ClassA* class_a_pointer)
{
if(class_a_pointer)
return true;
else
return false;
return false;
}
}
| This questions is really too general to answer properly, but here's my 2 cents. In general, as long as you only refer to a class as a pointer to it, compilation will work. eg this example compiles fine:
class B;
int main() {
B * tst;
return 0;
}
However, as soon as you try to actually instantiate a the pointer, or access any of its methods, you need a full definition. Those examples will NOT work:
class B;
int main() {
B * tst = new B(); // error: allocation of incomplete type 'B'
return 0;
}
Or:
class B;
int main() {
B * tst;
tst->print(); // error: member access into incomplete type 'B'
return 0;
}
tl;dr; As long as you don't actually interact with it, you can use an incomplete type. If you use any method or function, you need to declare them in advance (including constructors)
|
70,379,103 | 70,379,163 | char pointer and static_cast in c++ code related to virtualalloc | I was searching for some code related to VirtualAlloc and came across this piece of code:
#include<windows.h>
#include<iostream>
using namespace std;
int main() {
size_t in_num_of_bytes,i;
cout<<"Please enter the number of bytes you want to allocate:";
cin>>in_num_of_bytes;
LPVOID ptr = VirtualAlloc(NULL,in_num_of_bytes,MEM_RESERVE | MEM_COMMIT,PAGE_READWRITE); //reserving and commiting memory
if(ptr){
char* char_ptr = static_cast<char*>(ptr);
for(i=0;i<in_num_of_bytes;i++){ //write to memory
char_ptr[i] = 'a';
}
for(i=0;i<in_num_of_bytes;i++){ //print memory contents
cout<<char_ptr[i];
}
VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory
}else{
cout<<"[ERROR]:Could not allocate "<<in_num_of_bytes<<" bytes of memory"<<endl;
}
return 0;
}
This is a piece of code that I am trying to understand. However, I am confused about the following line:
char* char_ptr = static_cast<char*>(ptr);
I am not sure as to why this line is needed. And what does it do?
| Simpler example:
void* allocate_some_stuff(){
return new char[42];
}
int main()
{
void* ptr = allocate_some_stuff();
char* cptr = ptr;
}
Because C++ does not allow implicit conversion from void* to char* it causes the error:
<source>:9:18: error: invalid conversion from 'void*' to 'char*' [-fpermissive]
9 | char* cptr = ptr;
| ^~~
| |
| void*
But is fine when you explicitly cast:
int main()
{
void* ptr = allocate_some_stuff();
char* cptr = static_cast<char*>(ptr);
}
void* can point (almost) anywhere and casting to char* is generally ok (char is an exception with respect to that). When dealing with void* the type system is bypassed and to some large extend it is up to you to know what that pointer actually points to or what it can be used for.
|
70,379,337 | 70,380,745 | Template function ignores members from inherited class | I am trying to write a program that compares some Shapes by their area, Shape being the base class.
The program has 2 other classes that are derived from the Shape class.
This is how I defined them:
class Shape
{
protected:
string color;
public:
Shape();
Shape(string);
virtual double Perimeter();
virtual void printMe();
virtual double Area();
};
class Square:
public Shape
{
int x, y;
double side;
public:
Square();
Square(string, int, int, double);
double Perimeter();
void printMe();
double Area();
};
class Circle:
public Shape
{
int x, y, radius;
public:
Circle();
Circle(string, int, int, int);
double Perimeter();
void printMe();
double Area();
};
In main, I created the following objects:
Shape f1, f2("green");
Circle c1, c2("green", 2, 2, 2);
Square p1, p2("blue", 0, 0, 5);
Shape* f3 = &c1;
Shape* f4 = &c2;
Shape* f5 = new Square("blue", 1, 0, 2);
Shape* f6 = &p2;
And I want to build a function that takes any Shape objects and return the one that has the maximum area.
I tried like this:
template <typename T>
T maxim(initializer_list<T> list) {
T maxx;
for (auto i : list)
{
if (i.Area() > maxx.Area())
maxx = i;
}
return maxx;
}
In main, I tried to call the function:
maxim<Shape>({*f3, *f4, *f5, *f6}).printMe();
The program doesn't have any errors, only an empty string is displayed (due to the fact that maxx is a Shape that is initialized with an empty string).
The objects f3,f4,f5 and f6 are displayed right when I call the printMe() method, so I figured that when I call the maxim function, only the member color is assigned to the objects. There is no x,y,side or radius member assigned to them.
I think the problem is that the objects are just Shapes and they only have the color member.
Is there any way the objects in the list can be interpreted as Cricles and Squares so I can compare them using Area() method?
| You are trying to use polymorphism here. Unfortunately polymorphism in C++ works well with pointers or references but not with plain objects because of slicing (thank to @Jarod42 for that reference).
And as references cannot be assigned to (you instead assign to the ref-ed object) you cannot use them in containers nor in initializer lists.
That means that you will have to use good old pointers in maxim:
template <typename T>
T* maxim(initializer_list<T*> list) {
T* maxx = nullptr;
for (auto i : list)
{
if (nullptr == maxx || i->Area() > maxx->Area())
maxx = i;
}
return maxx;
}
From there on, you will be able to do:
maxim<Shape>({f3, f4, f5, f6})->printMe();
|
70,379,799 | 70,379,938 | How to make a notched matrix? | I have a little problem, I don't quite understand how to make a toothed (a notched?) matrix in C++.
The matrix should be like this (with 4 columns and 6 rows):
But I keep getting a matrix in the form of a triangle, i.e. no repeating rows are displayed. How can I fix it?
I'm attaching a piece of code, but I don't think it will help much.
(N are rows, M are columns)
for (int i = 0; i < N; i++) {
matrix[i] = new double[M];
for (int p = 0; p <= i; p++) {
matrix[i][p] = rand() % 101 - 50;
cout << setw(5) << matrix[i][p];
}
| I'm assuming that the first row has 1 column, second has 2 columns, etc., up to a maximum of M columns. In which case, the below will work.
size_t N = 6;
size_t M = 4;
double **matrix = new double*[N];
for (size_t i = 0; i < N; i++) {
size_t cols = std::min( i + 1, M ); // determine the correct number of cols for the row
matrix[i] = new double[cols];
for (size_t p = 0; p < cols; p++) {
matrix[i][p] = rand() % 101 - 50;
cout << setw(5) << matrix[i][p];
}
}
Btw, I'd suggest using something more modern than rand().
Would also generally recommend not using new, and instead preferring std::unique_ptr or std::shared_ptr, or in this case using std::vector.
Don't forget to delete as well.
|
70,380,645 | 70,380,944 | boost asio, post() to main thread? | I am using boost::asio as a general async backend.
I have multiple threads runing one io_context
But I encounter certain operations that are binded to specific thread. For example, imshow of opencv must be called from main thread.
What is the best way to post to main thread, or any specific thread in general? (without busy loop)
| You can't do it through asio.
You can use message queue you read in main thread (like Windows messages) or other specific thread.
|
70,381,179 | 70,381,331 | How to Add Element into a std::vector using std::any | I am working on a C++17 project and there i am using std::any. A minimal reproducible example is given below for reference explaining what i want to achieve.
#include <any>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> vec{1,2,3};
std::any anything = vec;
// anything.push_back(4);//i want to add an element into vector vec, using variable anything but this statement won't work
std::cout<<std::any_cast<std::vector<int>>(anything).size()<<std::endl;//prints 3
std::any_cast<std::vector<int>>(anything).push_back(4);//this adds(push_back) element into rvalue
std::cout<<std::any_cast<std::vector<int>>(anything).size()<<std::endl;//prints 3 but i want 4
}
As can be seen in the above example, i have a std::any object and i am using std::any_cast to add element into the vector. I want to add the element into the actual(lvalue) vector named vec but instead, the element is added into an rvalue. Is there a way to add element into the vector named vec using std::any. If not then is there any other way of doing this like using std::variant or something else that i may not be aware of. I am looking for a way of doing this in any version of C++ like C++11 or C++17 etc.
In my actual project, there is requirement for storing object of any type. So i got the same problem there. And then realized what is wrong(namely, we are using push_back on an rvalue) and then i reduced the problem to a minimal reproducible example and am asking here.
|
we are using push_back on an rvalue
No, that's not the problem. any stores a copy of what it is given. It doesn't reference some other object. It creates an object from what it is given. So even if you get a reference to the object in the any, it wouldn't be a reference to vec itself.
If you want to store a reference to an object in an any, you need to do so explicitly by storing either a pointer or a reference_wrapper to that object:
using ref_type = decltype(std::ref(vec));
std::any anything = std::ref(vec);
std::any_cast<ref_type>(anything).get().push_back(4);
Note that having an any which references an object is dangerous. If the any outlives the lifetime of the referenced object, you'll get bad things when you try to access the referenced object. This is part of why any stores copies by default.
|
70,381,528 | 70,381,728 | How To complete string from another string | #include<iostream>
#include<string>
using namespace std;
int main ()
{
string str;
string str2;
int count;
cin>>count;
while(count!=0)
{
cin>>str;
cin>>str2;
int l=str2.length()-1;
cout<<str[0];
if(str.length()==str2.length())
{
for(int x=1;x<str.length();x++)
cout<<str2[x-1]<<(str[x]);
cout<<str2[l];
cout<<endl;
}
count--;
}
return 0;
}
Given two strings S and T. Print a new string that contains the following:
The first letter of the string S followed by the first letter of the string T.
the second letter of the string S followed by the second letter of the string T.
and so on...
In other words, the new string should be ( S0 + T0 + S1 + T1 + .... ).
Note: If the length of S is greater than the length of T then you have to add the rest of S letters at the end of the new string and vice versa.
Input
The first line contains a number N (1 ≤ N ≤ 50) the number of test cases.
Each of the N following lines contains two string S, T (1 ≤ |S|, |T| ≤ 50) consists of lower and upper English letters.
Output
For each test case, print the required string.
Example
inputCopy
2
ipAsu ccsit
ey gpt
outputCopy
icpcAssiut
egypt
in my good i get errors in some cases can someone tell me how to solve this probelm
| A straightforward approach can look the following way
std::string::size_type i = 0;
for ( auto n = std::min( str.size(), str2.size() ); i < n; i++ )
{
std::cout << str[i] << str2[i];
}
while ( i < str.size() )
{
std::cout << str[i++];
}
while ( i < str2.size() )
{
std::cout << str2[i++];
}
Here is a demonstration program
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str( "ipAsu" );
std::string str2( "ccsit" );
std::string::size_type i = 0;
for (auto n = std::min( str.size(), str2.size() ); i < n; i++)
{
std::cout << str[i] << str2[i];
}
while (i < str.size())
{
std::cout << str[i++];
}
while (i < str2.size())
{
std::cout << str2[i++];
}
std::cout << '\n';
}
The program output is
icpcAssiut
You could move the basic code in a separate function.
|
70,382,001 | 70,384,139 | How to marshal through py::dict in C++ passing from pybind11 | I try to pass a dictionary (unordered_map) structure from python to C++ through pybind11. On the python side I am trying to do:
v1 = { 1:3.0, 2:4.0}
v2 = { 7:13.0, 8:14.0, 15:22.0}
data={'ab':v1, 'bz':v2}
cpp_run(data)
On the C++ side, I have
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
namespace py = pybind11;
void cpp_run(py::dict& results) {
for (auto it : results) {
const std::string& name = reinterpret_cast<const std::string&>(it.first);
const py::dict& values = reinterpret_cast<const py::dict&>(it.second);
for (auto iter : values) {
const int& id = reinterpret_cast<const int&>(iter.first);
const double& value = reinterpret_cast<const double&>(iter.second);
std::cout << "name:" << name << ", id:" << id << ", value:" << value << std::endl;
}
}
}
It prints garbage data. I used reinterpret_cast to satisfy the Visual Studio compiler.
| I sort of solve this by using py::cast on the C++ side:
void cpp_run(const py::dict& results) {
for (auto it : results) {
const std::string& name = py::cast<const std::string>(it.first);
std::unordered_map<int, double>& a_map = py::cast <std::unordered_map<int, double> >(it.second);
for (auto iter = a_map.begin(); iter != a_map.end(); ++iter) {
of << "name:" << name << ", id:" << iter->first << ", value:" << iter->second << std::endl;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.