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 |
|---|---|---|---|---|
71,548,000 | 71,548,039 | ostream << operator not getting invoked | I have created a class Animal with some basic properties and added a no data constructor.
I have overloaded the ostream operator as well to print the properties.
Animal.cpp
#include<bits/stdc++.h>
using namespace std;
class Animal {
string name;
int action;
public:
Animal() {
name = "dog";
action = 1;
}
ostream& write(ostream& os) {
os << name << "\n" << action << "\n";
return os;
}
friend ostream& operator<<(ostream& os, Animal &animal) {
return animal.write(os);
}
};
int main() {
cout << "Animal: " << Animal() << "\n";
}
However I am getting error in the main that invalid operands to binary expression ostream and Animal.
It works fine if I declare Animal and then call the cout. But how to make it work like this (initialize and cout at the same time) ?
| The 2nd parameter of operator<< is declared as Animal &; Animal() is a temporary and can't be bound to lvalue-reference to non-const.
You can change the type to const Animal &; temporary could be bound to lvalue-reference to const. (Then write needs to marked as const too.)
class Animal {
string name;
int action;
public:
Animal() {
name = "dog";
action = 1;
}
ostream& write(ostream& os) const {
os << name << "\n" << action << "\n";
return os;
}
friend ostream& operator<<(ostream& os, const Animal &animal) {
return animal.write(os);
}
};
|
71,548,291 | 71,548,379 | Forward CMake BOOL to C++ | I want to be able to set a bunch of boolean flags when calling CMake, that are later used in C++ code. Something like:
set(DEBUG_ENABLE false CACHE BOOL "enable debugging")
target_compile_definitions(target PRIVATE DEBUG_ENABLE=${DEBUG_ENABLE})
This actually works fine and produces something equivalent to:
#define DEBUG_ENABLE false
However, the the native CMake literals for BOOLs are ON/OFF and tools like the CMake GUI will use those values, resulting in a define that doesn't work well in C++:
#define DEBUG_ENABLE OFF
What is the best way to forward such a boolean variable from CMake to C++?
I can think of a few things:
Conversion function in CMake, resulting in three lines per boolean value
Use STRING instead of BOOL
Make it work in C++: #define ON true
None of these options seem particularly great to me.
| I'd use configure_file. It won't get you a C++ bool directly, but it's something that will actually scale over time.
You'll need to make a config file template for cmake to modify, in this example config.hpp.in.
#cmakedefine01 DEBUG_ENABLE
Next, add a configure_file line to your CMakeLists.txt.
configure_file(config.hpp.in "${CMAKE_BINARY_DIR}/config.hpp")
Any variable in the config template will be replaced with either 0/1 depending on the value in cmake.
Working output:
(after configuring)
$ cat config.hpp
#define DEBUG_ENABLE 0
$ cmake -DDEBUG_ENABLE=ON .
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/so/cmake-bool/build
$ cat config.hpp
#define DEBUG_ENABLE 1
This also completely removes the need for your target_compile_definitions line, provided you #include "config.hpp" in the appropriate places.
|
71,548,320 | 71,548,608 | How to add a value at some list[x][y] in C++? | I am trying to add some value at cost[x][y] and the list must be a pointer type.
I declared the list like this:
list<int>* cost = new list<int>[V]; // V being user input
And here I'm trying to add the value "c" at the place of cost[x][y]. How am I supposed to add that .When I try to use iterator as below it says
"Debug Assertion Failed"
"Unable to increment end point iterator"
The Code:
void addCost(int x, int y, int c) // adds cost in cost[x][y] and cost[y][x] indicies
{
auto it = cost[x].begin();
advance(it, y);
*it = c;
}
| The problem is that the lists will be initially empty. So, having 0 elements.
So, you can write cost[x] and can get an iterator. That is OK. But, as said, the list is empty. So, if you try to advance the iterator, it will fail.
Because, it will be equal to end() in the beginning. And this cannot be advanced.
Else, it would work . . .
Some demo example:
#include <iostream>
#include <list>
constexpr size_t SIZE = 10;
int main() {
size_t numberOfElementsX{ SIZE };
size_t numberOfElementsY{ SIZE };
std::list<int>* cost = new std::list<int>[numberOfElementsX];
for (size_t i = 0; i < numberOfElementsX; ++i)
cost[i].resize(numberOfElementsY);
auto it = cost[3].begin();
std::advance(it, 5);
*it = 42;
for (auto i : cost[3])
std::cout << i << ' ';
}
|
71,548,740 | 71,549,138 | Using Boost Beast to build Platform specific client-side authentication in SSL connection | I’m working on boost::beast based application on macOS platform, and I wonder how I can provide a client-side certificate to authenticate against the server ?
basically , in macOS the certificates are stored in keychain, and cannot be exported (backed by dedicated hardware called secured-enclave for better security)…
So I wonder if there’s any callback suitable to sign server’s challenge manually with native macOS native code that send the challenge to the keychain/secure-enclave for signing.
basically, I'm looking for a callback that have roughly the following signature :
bool validate_client_side_certificate(const std::string& challenge)
So basically What I've got right not is the ability to provide the certificate + private key from file
boost::asio::ssl::context ctx_;
std::string client_cert_ = read_pem_file(client_cert_path);
std::string client_cert_private_key_ = read_pem_file(private_key_path);
ctx_.use_certificate(
boost::asio::buffer(client_cert_.c_str(), client_cert_.length()),
boost::asio::ssl::context::pem);
ctx_.use_private_key(
boost::asio::buffer(client_cert_key_.c_str(), client_cert_key_.length()),
boost::asio::ssl::context::pem);
This flow works perfectly, but if I want to use the certificates that are inside the keychain (macOS storage for crypto data) I cannot get the private key but only a reference (because it's protected).
So in macOS we cannot just provide the private key to ctx_ do that the challenge will be signed automatically. instead, we need to get the callback that occur when client-side authentication is required, along with the challenge... and use macOS native code to sign the challenge inside the keychain hardware, using the key reference.
| See set_verify_callback
There are examples here:
asio/example/cpp11/ssl/client.cpp
asio/example/cpp03/ssl/client.cpp
You can see it integrated in Beast's ssl_stream: https://www.boost.org/doc/libs/1_78_0/libs/beast/doc/html/beast/ref/boost__beast__ssl_stream/set_verify_callback/overload2.html
|
71,548,837 | 71,548,999 | function to print min and max value of an array using c++ pointers | I'm trying to understand pointers in c++ so I made a function that takes an array and the length of that array and print out the min and max values of that array, however, it always just print the last element in that array for both min and max, I went through my code line by line but I still don't understand the reason for this behavior, can you please help understand and fix my code, thanks.
void getMinAndMax(int numbers[], int length)
{
int *min = &numbers[0];
int *max = &numbers[0];
cout << length << endl;
for (int i = 1; i < length; i++)
{
if (*min > numbers[i])
{
*min = numbers[i];
}
if (*max < numbers[i])
{
*max = numbers[i];
}
}
cout << "min: " << *min << endl;
cout << "max: " << *max << endl;
}
| Since, you are using the de-referencing operator in the if condition. You are basically changing the value at the memory location where the pointer is pointing (in this case the 0th index of the array). What you should do in the if condition is store the index where the minimum and maximum values are present.
Like so
if (*min > numbers[i])
{
min = &numbers[i];
}
This way, the pointer will hold the addresses of the maximum and minimum values and when you dereference them, you will get the right answer.
|
71,549,394 | 71,550,087 | C++ access callback data | I am attempting to create a wrapper around class functions. The purpose of my wrapper is to test input, output, and enforce order of operations with various calls throughout my program. I am trying to not make any changes to the callee class. Attached is an example of what I am trying to achieve, but unable to figure out.
Main.cpp
#include "func_warpper.h"
#include "func.h"
int main()
{
func_wrapper fw
fun func;
int origValue = 5;
fw.caller([&](int origValue) { func.f(origValue); }, origValue);
int output = func.getResult().number;
std::cout << " value outputed by function 2 : " << output << std::endl;
// output
// note that above line does give me the result I am looking for
// however, I want to be able to get this inside the function of caller
return 0;
}
func.h .... I want this to be unmodified
#ifndef FUN_H
#define FUN_H
class fun
{
public:
struct result
{
int number;
};
fun();
~fun();
void f(int value);
struct result getResult(){return this->testResult;};
private:
struct result testResult;
};
#endif
func.cpp .... I want this to be unmodified
#include "func.h"
fun::fun(){
this->testResult.number = 0;
return;
}
fun::~fun(){
return;
}
void fun::f(int value){
int updateValue = value * 5;
this->testResult.number = updateValue;
}
func_wrapper.h .... I can modify this until the cows come home, please go ham with recommended changes :)
class func_wrapper
{
public:
struct new_result
{
int new_number;
};
func_wrapper();
~func_wrapper();
void caller(std::function<void(int)> clb, int val);
struct new_result getNewResult() { return this->new_testResult; };
private:
struct new_result new_testResult;
};
#endif
func_wrapper.cpp .... same as above, I can modify this until the cows come home, please go ham with recommended changes :)
#include "func_wrapper.h"
func_wrapper::func_wrapper()
{
//ctor
this->new_testResult.new_number = 0;
return;
}
func_wrapper::~func_wrapper()
{
//dtor
}
void func_wrapper::caller(std::function<void(int)> clb, int val)
{
std::cout << " value entered into function: " << val << std::endl;
// clb(val); seems to call the function but does not store locally anything
clb(val);
clb;
// clb; seems to store all the information locally however I seem unable to
// to reach the infromation: clb -> [functor] -> func -> testResult -> number
// would like ...
int output = clb ??? // the result of what gets filled from number struct
// if I attempt to #include func.h
// func func;
// func.getResult().number; locally the answer is zero with or without delay
}
Through several days of searching, I have not found anything that can help with this problem, to include similar enough questions on stack overflow. Any help would be greatly appreciated, thank you.
| @JohnFilleau had mentioned to pass the class object instead of the function from within the class. The following is the solution based on example code that he provided, and I modified to work with the example. I realize the question is confusing but would like to thank both JohnFilleau and Taekahn for the discussion.
In main.cpp
int main()
{
func_wrapper fw;
fun func;
int origValue = 5;
fw.caller2(func, origValue);
return 0:
}
func_wrapper::caller2
void func_wrapper::caller2(fun& fun, int val)
{
std::cout << " value entered into function: " << val << std::endl;
fun.f(val);
int output = fun.getResult().number;
std::cout << " did this work: " << output << std::endl;
}
In the header I had to add
#include "func.h"
with the change to the header as follows
void caller2(fun& fun, int val);
|
71,549,789 | 71,549,848 | Inbuilt / pre-defined comparator in cpp | Recently I learnt about comparators in cpp from STL.
I came to know we can use greater<>() as third argument for sorting instead of writing own logic.
Just curious to know how many inbuilt comparators are there in cpp.
| The standard library defines pretty much what you would expect as analogues to the built-in operators:
std::equal_to // ==
std::not_equal_to // !=
std::less // <
std::less_equal // <=
std::greater // >
std::greater_equal // >=
Since C++20 also constrained versions of all these comparison function objects in the std::ranges namespace as well as std::compare_three_way, which is the analogue to the built-in three-way comparison operator <=>.
For a reference of these function objects see https://en.cppreference.com/w/cpp/utility/functional#Comparisons.
|
71,549,797 | 71,550,159 | How to use IDirect3D9 functions | I am trying to use the function GetAdapterIdentifier but for some reason I keep on getting an error
g++ main.cpp -ld3d9 -ld3dcompiler -lgdi32 -static -static-libstdc++ -o output
main.cpp: In function 'int main()':
main.cpp:22:59: error: cannot call member function 'virtual HRESULT IDirect3D9::GetAdapterIdentifier(UINT, DWORD, D3DADAPTER_IDENTIFIER9*)' without object
22 | HRESULT hResult = IDirect3D9::GetAdapterIdentifier(x ,xWord, &pIdentifier);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
make: *** [Makefile:7: build] Error 1
This is my main.cpp file very simple yet still got an error
#include <iostream>
#include <d3d9.h>
#include <D3D9Types.h>
#include <tchar.h>
int main(void)
{
UINT x;
DWORD xWord;
D3DADAPTER_IDENTIFIER9 pIdentifier;
HRESULT hResult = IDirect3D9::GetAdapterIdentifier(x ,xWord, &pIdentifier);
return 0;
}
I am using a Makefile to compile the main file
CC = g++
FILES = main.cpp
OUT_EXE = output
INCLUDES = -ld3d9 -ld3dcompiler -lgdi32 -static -static-libstdc++
build:$(FILES)
$(CC) $(FILES) $(INCLUDES) -o $(OUT_EXE)
| Found this blog that helped me get to this answer
#include <iostream>
#include <d3d9.h>
#include <D3D9Types.h>
#include <tchar.h>
#include <string.h>
LPDIRECT3D9 g_pDirect3D = NULL;
LPDIRECT3DDEVICE9 g_pDirect3D_Device = NULL;
int main(void)
{
UINT x = 0; // Ordinal number that denotes the display adapter.
DWORD xWord = 0 ;
D3DADAPTER_IDENTIFIER9 pIdentifier ;
g_pDirect3D = Direct3DCreate9(D3D_SDK_VERSION);
HRESULT hResult = g_pDirect3D->GetAdapterIdentifier(x, xWord, &pIdentifier);
if (hResult == D3D_OK)
std::cout << "Successfully created DirectX handle " << std::endl;
else
std::cout << "Failed to create DirectX handle" << std::endl;
return 0;
}
Direct3DCreate9 creates a handle to call the functions from
|
71,550,127 | 71,550,215 | What is the purpose of d-char-sequence in C++ raw strings? | On this reference: https://en.cppreference.com/w/cpp/language/string_literal, raw string is defined as:
prefix(optional) R"d-char-sequence(optional)(r-char-sequence(optional))d-char-sequence(optional)"
Example:
const char* s1 = R"foo(
Hello
World
)foo";
What is the purpose of the d-char-sequence ("foo" in the example above)?
| The optional d-char-sequence is used to define the end marker of the raw string.
For example, if the raw string contains the substring )", then the line:
const char* s = R"(string with )" inside)";
will raise a syntax error. This can be fixed by using the optional d-char-sequence that is not met inside the raw string:
const char* s = R"uniq(string with )" inside)uniq";
|
71,550,243 | 71,550,297 | My helper function is returning an empty string | I'm writing some code for a game, and I'm attempting to write a helper function to return a string inside an object:
const char* getGhostName(GhostAI* ghostAI)
{
if (ghostAI) {
GhostInfo* ghostInfo = getGhostInfo(ghostAI);
const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
const char* name = il2cppi_to_string(ghostName).c_str();
return name;
}
return "UNKNOWN";
}
And here is the il2cppi_to_string functions:
std::string il2cppi_to_string(Il2CppString* str) {
std::u16string u16(reinterpret_cast<const char16_t*>(str->chars));
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);
}
std::string il2cppi_to_string(app::String* str) {
return il2cppi_to_string(reinterpret_cast<Il2CppString*>(str));
}
When I call getGhostName, I end up with an empty string. Now I did get a warning from ReSharper which says:
Object backing the pointer will be destroyed at the end of the full-expression.
This is appearing on the following line inside getGhostName when calling il2cppi_to_string:
const char* name = il2cppi_to_string(ghostName).c_str();
I'm not entirely sure what this means or how I can modify the code to fix it. I absolutely hate working with strings in C++.
| il2cppi_to_string() returns a temporary std::string, which will be destroyed at the end of the expression that calls il2cppi_to_string(). You are obtaining a const char* pointer to the data of that temporary std::string, which is what ReSharper is warning you about. Since the temporary std::string is destroyed before the return, that means getGhostName() is returning a dangling pointer to invalid memory.
To fix this, change getGhostName() to return a std::string instead of a const char*:
std::string getGhostName(GhostAI* ghostAI)
{
if (ghostAI) {
GhostInfo* ghostInfo = getGhostInfo(ghostAI);
const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
return il2cppi_to_string(ghostName);
}
return "UNKNOWN";
}
|
71,550,602 | 71,550,671 | No matching function call error when the functions are actually being called | I am currently doing a project for school and for some reason, g++ won't compile my code properly, saying:
Rectangle.cpp: In constructor ‘Rectangle::Rectangle()’:
Rectangle.cpp:8:22: error: no matching function for call to ‘Line::Line()’
Rectangle::Rectangle(){
^
In file included from Rectangle.h:1:0,
from Rectangle.cpp:2:
Line.h:7:5: note: candidate: Line::Line(Point, Point)
Line(Point s, Point e);
^~~~
Line.h:7:5: note: candidate expects 2 arguments, 0 provided
Line.h:3:7: note: candidate: constexpr Line::Line(const Line&)
class Line{
^~~~
Line.h:3:7: note: candidate expects 1 argument, 0 provided
Line.h:3:7: note: candidate: constexpr Line::Line(Line&&)
Line.h:3:7: note: candidate expects 1 argument, 0 provided
Rectangle.cpp:8:22: error: no matching function for call to ‘Line::Line()’
Rectangle::Rectangle(){
^
In file included from Rectangle.h:1:0,
from Rectangle.cpp:2:
Line.h:7:5: note: candidate: Line::Line(Point, Point)
Line(Point s, Point e);
^~~~
Line.h:7:5: note: candidate expects 2 arguments, 0 provided
Line.h:3:7: note: candidate: constexpr Line::Line(const Line&)
class Line{
^~~~
Line.h:3:7: note: candidate expects 1 argument, 0 provided
Line.h:3:7: note: candidate: constexpr Line::Line(Line&&)
Line.h:3:7: note: candidate expects 1 argument, 0 provided
Rectangle.mak:11: recipe for target 'Rectangle.o' failed
make: *** [Rectangle.o] Error 1
Rectangle.cpp
#include <iostream>
#include "Rectangle.h"
using namespace std;
// Rectangle::Rectangle(Line w, Line l){
// width=w;
// length=l;
// };
Rectangle::Rectangle(){
Line w(Point(0,4),Point(0,0));
width=w;
Line l(Point(0,0),Point(8,0));
length=l;
}
// Rectangle::Rectangle(Point ws, Point we, Point ls, Point le) {
// width=Line(ws,we);
// length=Line(ls,le);
// }
Rectangle.h
#include "Line.h"
class Rectangle{
public:
void print();
double calcArea();
Rectangle();
// Rectangle(Line w, Line l);
// Rectangle(Point ws, Point we, Point ls, Point le);
private:
Line width;
Line length;
};
Line.h
#include "Point.h"
// struct Line;
class Line{
public:
void print();
double lineLength();
Line(Point s, Point e);
private:
Point start;
Point end;
};
Line.cpp
#include <iostream>
#include "Line.h"
using namespace std;
Line::Line(Point s, Point e){
start=s;
end=e;
}
void Line::print() {
cout << " Start";
start.print();
cout << " End";
end.print();
cout << endl;
}
double Line::lineLength(){
return start.calcDistance(end);
}
Point.h
class Point{
public:
Point();
Point(double xVal,double yVal);
// double getX();
// double getY();
// void setX(double xVal);
// void setY(double yVal);
void print();
double calcDistance(Point a);
private:
double x;
double y;
};
Point.cpp
#include "Point.h"
#include <math.h>
#include <iostream>
using namespace std;
Point::Point() {
x = 0.0;
y = 0.0;
}
Point::Point(double xVal, double yVal){
x=xVal;
y=yVal;
}
// double Point::getX() {
// return x;
// }
// double Point::getY() {
// return y;
// }
// void Point::setX(double xVal) {
// x = xVal;
// }
// void Point::setY(double yVal) {
// y = yVal;
// }
void Point::print(){
cout<<"x:\t"<<x<<"\ny:\t"<<y<<endl;
}
double Point::calcDistance(Point a){
return sqrt(pow(x-a.x,2)+pow(y-a.y,2));
}
and the build scripts:
Point: g++ -Wall -c Point.cpp -o Point.o
Line: g++ -Wall -c Line.cpp -o Line.o
Rectangle: g++ -Wall -Wextra -c Rectangle.cpp -o Rectangle.o
I did leave out a lot of other unnecessary information so if you need it, my project is here
Thank you in advance and hope you all have a very nice day (or night!)
| You are trying to default construct two Lines (width and length) in the Rectangle constructor. Since Line doesn't have a default constructor you need to use the member initializer list:
Rectangle::Rectangle() : // colon starts the member initializer list
width(Point(0,4), Point(0,0)),
length(Point(0,0), Point(8,0))
{}
|
71,550,695 | 71,552,097 | Undefined identifier and unresolved external errors C++ Visual Studio 2022 | This is basically two errors in one, that seem to come from the same thing. If I define my functions in my main.cpp file, and forward declare them at the top of the file, it doesn't give me any errors and everything runs smoothly.
When trying to declutter and move things into seperate .cpp files, it starts to give me linker errors and saying things are undefined even though I am using appropriate header files. The code is shown below:
main.cpp
#include "io.h"
#include <iostream>
#include <map>
class exchangeRates;
void menu();
int main()
{
menu();
return EXIT_SUCCESS;
}
// class storing exchange rates
class exchangeRates
{
public: // Access specifier
// Data Members
std::map<std::string, double> usd = {
{"GBP", 1.2},
{"EUR", 0.7},
};
std::map<std::string, double> gbp = {
{"USD", 0.9},
{"EUR", 1.4},
};
};
// menu function
void menu()
{
// get reference currency code from user
std::string refCurrency{ obtainCodeFromUser() };
// create 'rates' instance of 'exchangeRates' class
exchangeRates rates{};
// print the exchange values for that currency
if (refCurrency == "USD")
{
printExchangeValues(rates.usd, refCurrency);
}
else if (refCurrency == "GBP")
{
printExchangeValues(rates.gbp, refCurrency);
}
else
{
std::cout << "\nInvalid currency code. Example: USD, GBP, EUR etc.\n\n";
menu();
}
}
io.h
#ifndef IO_H
#define IO_H
#include <iostream>
#include <map>
std::string obtainCodeFromUser();
double obtainAmountFromUser();
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency);
#endif
io.cpp
#include "io.h"
#include <iostream>
#include <map>
// io functions for currency converter
std::string obtainCodeFromUser()
{
// obatin reference currency code from user
std::cout << "Enter currency code for reference currency (case-sensitive): ";
std::cin.clear();
std::string refCurrency{};
std::cin >> refCurrency;
std::cin.ignore(INT_MAX, '\n');
return refCurrency;
}
double obtainAmountFromUser()
{
// obtain amount of currency to be converted from user
std::cout << "Enter amount of currency to convert: ";
std::cin.clear();
double amount{};
std::cin >> amount;
std::cin.ignore(INT_MAX, '\n');
return amount;
}
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency)
{
// obtain amount of currency to be converted
double amount{ obtainAmountFromUser() };
std::cout << refCurrency << " " << amount << " is worth:\n";
for (auto& item : valuedCurrencies) {
std::cout << item.first << ": " << amount * item.second << '\n';
}
}
I am still a beginner with C++ so some parts have been copied from other open-source programs, and I know there are probably plenty of places to improve my code, but I'm mainly interested in why it just won't compile. The examples I followed when learning how to use header files worked fine and I don't believe I've done anything different here.
It says the identifiers "obtainCodeFromUser" and "printExchangeValues" are undefined.
The linker error it gives is LNK2019 'unresolved external symbol ...' and it seems to be relating to the printExchangeValues function.
Any help is massively appreciated!
| The issue mentioned by WhozCraig is very useful, I hope you will read it carefully. Regarding your question, after I modified some code, the program can run correctly. The error is caused by the template. Since you are a beginner and the program is not very complicated, the following code is more convenient for you to understand:
main.cpp
#include "io.h"
#include <iostream>
#include <map>
// class storing exchange rates
class exchangeRates
{
public: // Access specifier
// Data Members
std::map<std::string, double> usd = {
{"GBP", 1.2},
{"EUR", 0.7},
};
std::map<std::string, double> gbp = {
{"USD", 0.9},
{"EUR", 1.4},
};
};
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency)
{
// obtain amount of currency to be converted
double amount{ obtainAmountFromUser() };
std::cout << refCurrency << " " << amount << " is worth:\n";
for (auto& item : valuedCurrencies) {
std::cout << item.first << ": " << amount * item.second << '\n';
}
}
// menu function
void menu()
{
// get reference currency code from user
std::string refCurrency{ obtainCodeFromUser() };
// create 'rates' instance of 'exchangeRates' class
exchangeRates rates{};
// print the exchange values for that currency
if (refCurrency == "USD")
{
printExchangeValues(rates.usd, refCurrency);
}
else if (refCurrency == "GBP")
{
printExchangeValues(rates.gbp, refCurrency);
}
else
{
std::cout << "\nInvalid currency code. Example: USD, GBP, EUR etc.\n\n";
menu();
}
}
int main()
{
menu();
return EXIT_SUCCESS;
}
io.h
#ifndef IO_H
#define IO_H
#include <iostream>
#include <map>
std::string obtainCodeFromUser();
double obtainAmountFromUser();
#endif
io.cpp
#include "io.h"
#include <iostream>
#include <map>
// io functions for currency converter
std::string obtainCodeFromUser()
{
// obatin reference currency code from user
std::cout << "Enter currency code for reference currency (case-sensitive): ";
std::cin.clear();
std::string refCurrency{};
std::cin >> refCurrency;
std::cin.ignore(INT_MAX, '\n');
return refCurrency;
}
double obtainAmountFromUser()
{
// obtain amount of currency to be converted from user
std::cout << "Enter amount of currency to convert: ";
std::cin.clear();
double amount{};
std::cin >> amount;
std::cin.ignore(INT_MAX, '\n');
return amount;
}
|
71,550,798 | 71,551,013 | How to add the Github "BigFloat" library to my c++ project | (Sorry if this question is glaringly obvious or poorly written as I am fairly inexperienced to any form of coding and this website) I've been trying to include a library called "Big float" from github to my project as it needs to calculate very large numbers with high precision but my compiler doesn't recognise the library. I am using codeblocks version 20.03. I have tried: project ->
build options -> linker settings and then adding the files there but to no avail. I also tried: settings -> compiler -> linker settings and adding the files in there.
link:https://github.com/Mariotti94/BigFloat
Again, sorry for my lack of knowledge and thank you.
| The library you are referring to appears to consist of source code only. This means you need to compile it yourself. Just add the "BigFloat.cc" and "BigFloat.h" files to your project. Then, in your own code, write #include "BigFloat.h" to get access to the BigFloat class.
|
71,551,071 | 71,551,430 | Deduce complete type of parent from one of its template parameters | I want to get the typename of the parent that has a specific template parameter(key).
For example, if I have a parent MyParent<int, 1>, I want to be able to get that type(MyParent<int, 1>) from my child with just '1'. If I have MyParent<float,2> I want to be able to get that type(MyParent<float, 2>) with just '2'.
Basically, I want to get a typename (MyParent<float, 1>, MyParent<int, 2> etc.) from a "key" (1, 2, 3 etc.)
I'm using MSVC compiler, in C++20 mode.
Here's working code that does exactly that (but it has one downside):
#include <iostream>
template<std::size_t key>
class KeyClass {};
template<class Type, std::size_t key>
class parent
{
using keyclass = KeyClass<key>;
using self = parent<Type, key>;
public:
template<std::same_as<keyclass> T>
static self GetType() {}
};
class test :
public parent<int, 1>,
public parent<float, 2>
{
public:
using parent<int, 1>::GetType;
using parent<float, 2>::GetType;
};
int main()
{
std::cout << typeid(decltype(test::GetType<KeyClass<1>>())).name() << std::endl;
std::cout << typeid(decltype(test::GetType<KeyClass<2>>())).name() << std::endl;
}
This prints as expected: "class parent<int,1> class parent<float,2>". I can freely use those types, get their static members and do other stuff with them, and that's exactly what I want.
The downside is that I have to explicitly specify that I'm using the GetType method from every one of my parents. Which is quite lame, since I have to type everything twice (inheriting once, then specifying 'using'). Imagine having tens of keys ...
Are there any other ways to do this without repeating my code? For example, is there any way to specify 'using GetType` for all the parents in one line somehow? Or to make them automatically inherited or something, so that I don't have to specify 'using' at all?
Or maybe there's a different way to do what I want (to get a type at compile-time from some key (a template parameter), for example 1 should return Myparent<int, 1>, 2 should return MyParent<int, 2>)?
I don't want to use the preprocessor for this.
| To avoid having to write a using declaration for the members of each of the parent classes, you can write a variadic class template wrapper that exposes this member for all of the types (as in the Overloader pattern shown here)
template<typename... Ts>
struct Bases : Ts...
{
using Ts::GetType...;
};
And now your test class can just inherit from this wrapper as
class test : public Bases<parent<int, 1>,
parent<float, 2>>
{};
Here's a demo
|
71,551,116 | 71,551,979 | OpenSSL 3 Diffie-Hellman Key Exchange C++ | Before OpenSSL3 this was simple.
DH* dh = DH_new();
/* Parameters */
dh->p = BN_bin2bn(bin_p, bin_p_size, NULL);
dh->g = BN_bin2bn(bin_g, bin_g_size, NULL);
/* Private key generation */
BN_hex2bn(&dh->priv_key, hex_priv_key);
/* Public key generation */
DH_generate_key(dh);
/* Derive */
int shared_key_size = DH_compute_key(shared_key, peer_pub_key, dh);
I am trying to make keys in the new version of OpenSSL but it didnt work because EVP_PKEY_generate fails with
error:03000097:digital envelope routines::operation not initialized
OSSL_PARAM_BLD* param_build = OSSL_PARAM_BLD_new();
OSSL_PARAM_BLD_push_BN(param_build, OSSL_PKEY_PARAM_FFC_P, p);
OSSL_PARAM_BLD_push_BN(param_build, OSSL_PKEY_PARAM_FFC_G, g);
OSSL_PARAM* params = OSSL_PARAM_BLD_to_param(param_build};
/* DH_new() */
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "DH", nullptr);
EVP_PKEY_keygen_init(ctx);
/* DH_generate_key */
EVP_PKEY* dh_key_pair = NULL;
EVP_PKEY_generate(ctx, &dh_key_pair, EVP_PKEY_KEY_PARAMETERS, params);
There is lack of information on the Internet. I dont know what to do.
| You have to create an EVP_PKEY with domain parameters first if you use custom prime and generator.
// Create the OSSL_PARAM_BLD.
OSSL_PARAM_BLD* paramBuild = OSSL_PARAM_BLD_new();
if (!paramBuild) {
// report the error
}
// Set the prime and generator.
if (!OSSL_PARAM_BLD_push_BN(paramBuild, OSSL_PKEY_PARAM_FFC_P, prime) ||
!OSSL_PARAM_BLD_push_BN(paramBuild, OSSL_PKEY_PARAM_FFC_G, generator)) {
// report the error
}
// Convert to OSSL_PARAM.
OSSL_PARAM* param = OSSL_PARAM_BLD_to_param(paramBuild);
if (!param) {
// report the error
}
// Create the context. The name is DHX not DH!!!
EVP_PKEY_CTX* domainParamKeyCtx = EVP_PKEY_CTX_new_from_name(nullptr, "DHX", nullptr);
if (!domainParamKeyCtx) {
// report the error
}
// Initialize the context.
if (EVP_PKEY_fromdata_init(domainParamKeyCtx) <= 0) {
// report the error
}
// Create the domain parameter key.
EVP_PKEY* domainParamKey = nullptr;
if (EVP_PKEY_fromdata(domainParamKeyCtx, &domainParamKey,
EVP_PKEY_KEY_PARAMETERS, param) <= 0) {
// report the error
}
The domain parameter domainParamKey is ready! Now, use it to create a key pair.
EVP_PKEY_CTX* keyGenerationCtx = EVP_PKEY_CTX_new_from_pkey(nullptr, domainParamKey, nullptr);
if (!keyGenCtx) {
// report the error
}
if (EVP_PKEY_keygen_init(keyGenerationCtx) <= 0) {
// report the error
}
EVP_PKEY* keyPair = nullptr;
if (EVP_PKEY_generate(keyGenerationCtx, &keyPair) <= 0) {
// report the error
}
The key pair keyPair is ready!
See this project on GitHub: https://github.com/eugen15/diffie-hellman-cpp. It shows how to generate key pairs, set and get Diffie-Hellman parameters. Plus, it has some custom Diffie-Hellman implementations.
See the following files for an OpenSSL 3 example:
diffie-hellman-openssl.h
diffie-hellman-openssl.cpp
The following files is a LibreSSL example which is basically OpenSSL before version 3. This is to be sure you have backward compatibility.
diffie-hellman-libressl-dh.h
diffie-hellman-libressl-dh.cpp
More things to consider
FIRST
If you used a custom prime before OpenSSL 3, then it is better to move to a predefined safe prime. You can see an example here: https://www.openssl.org/docs/manmaster/man7/EVP_PKEY-DH.html
int priv_len = 2 * 112;
OSSL_PARAM params[3];
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
params[0] = OSSL_PARAM_construct_utf8_string("group", "ffdhe2048", 0);
/* "priv_len" is optional */
params[1] = OSSL_PARAM_construct_int("priv_len", &priv_len);
params[2] = OSSL_PARAM_construct_end();
EVP_PKEY_keygen_init(pctx);
EVP_PKEY_CTX_set_params(pctx, params);
EVP_PKEY_generate(pctx, &pkey);
...
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
Alice executes the above code (taken from the OpenSSL manual). Then you get the prime and generator:
EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_FFC_P, &prime);
EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_FFC_G, &generator);
Then send it to Bob and use my code above to create the key pair.
SECOND
Use Elliptic-Curve Diffie-Hellman (ECDH) key exchange for new projects. It is much faster. Leave your DH as a fallback. See examples here.
|
71,551,522 | 71,551,804 | Is every "complete" object a "most-derived" object? | Per [intro.object]/2:
[..] An object that is not a subobject of any other object is called a complete object [..].
So consider this snippet of code:
struct Base {};
struct Derived : Base {};
struct MostDerived : Derived {};
I can't understand the wording in this quote from the standard:
[object.intro]/6:
If a complete object, a member subobject, or an array element is of class type, its type is considered the most derived class [..] An object of a most derived class type or of a non-class type is called a most derived object.
From the quote what I understand is that a type of a complete object is of "most-derived" class type. I stopped here, I really do not understand the rest of the wording.
Per the question "What does the "most derived object" mean?" I think that (correct me if I am wrong), objects of type "most-derived" class only, like MostDerived, are called "most-derived" objects. Is this true?
If I have created an object of Base like this: Base b_obj = Base(), is the object b_obj a "most-derived" object?
If I have created an object of Derived like this: Derived d_obj = Derived(), is the object d_obj also a "most-derived" object?
Does the word "derived" in "most-derived" mean that the object is an object of a class like MostDerived, or mean that the object has no class subobject in it?
|
Per the question "What does the "most derived object" mean?" I think that (correct me if I am wrong), objects of type "most-derived" class only, like MostDerived, are called "most-derived" objects. Does this true?.
"Most derived class" is supposed to be dependent on the object under consideration. It is not a property of the class as such.
if I have created an object of Base like this: Base b_obj = Base(), Is the object b_obj is "most-derived" object?
Yes, b_obj is a variable and as such a complete object. A complete object is always a most-derived object.
if I have created an object of Derived like this: Derived d_obj = Derived(), Is the object d_obj is also a "most-derived" object?
Same as above applies.
Is the word "derived" in "most-derived" mean that the object is an object of a class like MostDerived, or mean that the object has no class subobject in it?
"most-derived" means that there is no other object of which the object under consideration is a base class subobject. This is again not a property of classes themselves, but depends on the concrete instance of the class. If for example a Derived object is created with new Derived, then it contains a Base base class subobject and this subobject is not a most-derived object. However the Derived object is the most-derived object, since there isn't e.g. any MostDerived object of which it is a base class subobject.
Is every "complete" object is "most-derived" object
Yes, every complete object is a most-derived object. But the reverse is not true. For example
struct A {
Base b;
};
A a;
a is an object of type A and itself a most-derived object and a complete object, but a.b is also a most-derived object, although not a complete object.
|
71,551,631 | 71,551,668 | Im having a code error, while doing a code for a circular link list | Im having a problem finding the solution on my code, it was running okay, but while I as editing the main to Run the code, something might have change. so now I'm having this error on my code that says: this' argument to member function 'isEmpty' has type 'const CircularLinkedList', but function is not marked const
This is the part of the code where the error is popping.
//Copy Constructor
template <typename T>
CircularLinkedList<T>::CircularLinkedList(const CircularLinkedList& c1)
{
if (!c1.isEmpty())
{
Node<T>* curr = c1.frst;
//Iterating through elements until we encounter home node again
while (curr->next != first)
{
insert(curr->data);
curr = curr->next;
}
}
}
The following code I didn't originally have it on my main-menu to run the code but once I put it on it the error pop up. I'm no sure if this has something to do with it. but as a reference here is the code that I added. I didn't have any error before this code.
int printMenu();
// InsertList inserts an item into the list parameter
void insertListItem ( CircularLinkedList<int> & );
// deletes the first occurrence from the list parameter
void deleteOne ( CircularLinkedList<int> & );
// deletes all the occurrence from list parameter
void deleteAll ( CircularLinkedList<int> & );
//return the length of the list
int totalCount( CircularLinkedList<int> & );
// searchItem searches for an item in the list parameter
void searchItem ( CircularLinkedList<int> );
// return the number of occurrences of a given item
int totalOccurence (CircularLinkedList<int> & );
| The error is self-explanatory: in your CircularLinkedList<T>::CircularLinkedList copy constructor, the parameter is marked const.
You can only use its method that are defined as const. So change your isEmpty definition to something like
bool isEmpty() const {...}
After all, checking if the list is empty should not modify that list.
|
71,552,052 | 71,552,118 | What is good approach to declare object being used globally? c++ | I know that global/extern variables are bad, still not sure why exactly though.
But some cases, I can't figure out how to deal with this problem without using extern.
For example, in the server application I'm developing, I need every class, every source file to access list of all client objects. So that I can sending packets to that client whenever I need to..
Also, I need to declare memory pool object to increase performance of allocating/deallocating overlapped struct.(I cannot use smart pointer in this case because I have to free memory frequently). But there has to be only one memory pool object obviously so I have to declare it as gloabl/extern.
How can I approach this problem?
Should I declare shared_ptr or raw pointer in every class, and pass the pointer of object when class is constructed?
| Singleton can help. There is a simple example:
static MemPool *MemPool::getMemPool()
{
static MemPool g_mempool = MemPool(/***...***/);
return &g_mempool;
}
Memory *MemPool::allocMemFromPool(const size_t &size)
{
//...
}
auto data = getMemPool()->allocMemFromPool(1024);
|
71,552,170 | 71,552,203 | C++ call functions internally | I'm working with following code which gives access to low level monitor configuration using Windows APIs
https://github.com/scottaxcell/winddcutil/blob/main/winddcutil/winddcutil.cpp
And I would like to create a new function that increases or decreases the brightness, I was able to do this using Powershell but since the C++ code looks somewhat easy to understand I want to have a crack at it and try my luck and hopefully integrate it with an ambient light sensor later.
The powershell code I have is as follows which works with above executable: (its very crude at this stage)
$cb = [int]([uint32]("0x" + ((C:\Users\Nick\WindowsScripts\winddcutil-main\x64\Release\winddcutil.exe getvcp 0 10) -join "`n").split(" ")[2]))
if ($args[0] -eq "increase") {
if ( $cb -ne 100) {
$nb = "{0:x}" -f ($cb + 10)
C:\Users\Nick\WindowsScripts\winddcutil-main\x64\Release\winddcutil.exe setvcp 0 10 $nb
}
} elseif ($args[0] -eq "decrease") {
if ( $cb -ne 10) {
$nb = "{0:x}" -f ($cb - 10)
C:\Users\Nick\WindowsScripts\winddcutil-main\x64\Release\winddcutil.exe setvcp 0 10 $nb
}
}
It gets current brightness and if argument given is "increase" and if brightness is not already 100 then adds 10, in case of "decrease" it subtracts 10. Values are coveted to and from hex to decimals.
I understand if I want to integrate this inside the C++ code directly I would have something like following:
int increaseBrightness(std::vector<std::string> args) {
size_t did = INT_MAX;
did = std::stoi(args[0]);
//0 is monitor ID and 10 is the feature code for brightness
//currentBrightness = getVcp("0 10")
//calculate new value
//setVcp("0 10 NewValue")
}
Ultimetaly I would like to call the executable like "winddcutil.exe increasebrightness 0" (0 being the display ID)
I can keep digging around on how to do the calculation in C++ but internally calling the functions and passing the arguments so far turned out to be very challenging for me and I would appreciate some help there.
| you need to add a needed option here
line 164
std::unordered_map<std::string,std::function<int(std::vector<std::string>)>> commands
{
{ "help", printUsage },
{ "detect", detect},
{ "capabilities", capabilities },
{ "getvcp", getVcp },
{ "setvcp", setVcp},
{"increasebrightness ", increaseBrightness } // update here
};
to get current brightness you can't use getVcp api due to its result will be printed to stdout , it isn't returned via returned value, follow getVcp to get brighness value , use this
DWORD currentValue;
bool success = GetVCPFeatureAndVCPFeatureReply(physicalMonitorHandle, vcpCode, NULL, ¤tValue, NULL);
if (!success) {
std::cerr << "Failed to get the vcp code value" << std::endl;
return success;
}
then
define your increaseBrightness like
int increaseBrightness(std::vector<std::string> args) {
size_t did = INT_MAX;
did = std::stoi(args[0]);
DWORD currentBrightness;
bool success = GetVCPFeatureAndVCPFeatureReply(
physicalMonitorHandle, vcpCode, NULL, ¤tBrightness, NULL);
if (!success) {
std::cerr << "Failed to get the vcp code value" << std::endl;
return success;
}
//example + 10
auto newValue = did + 10;
success = setVcp({"0", "10", std::to_string(newValue)});
if(success)
{
// your handler
}
// 0 is monitor ID and 10 is the feature code for brightness
// currentBrightness = getVcp("0 10")
// calculate new value
// setVcp("0 10 NewValue")
}
test for passing argument:
https://godbolt.org/z/5n5Gq3d7e
note: make sure your have increaseBrightness's declaration before std::unordered_map<std::string,std::function<int(std::vector<std::string>)>> commands to avoid compiler's complaint
|
71,552,258 | 71,552,295 | request for member ‘nickname’ in ‘a’, which is of non-class type ‘Author [1000]’ | #include <iostream>
using namespace std;
struct Author {
int id ;
string fullname;
string nickname;
int age ;
};
struct Book {
int id ;
string title;
int year;
float price ;
};
void menu (){
cout << "Add New Author (1) \n" ;
cout << "Display Author List (2)\n " ;
cout << "Add New Book (3) \n" ;
cout << "Display Book List (4) \n" ;
cout << "Edit Author nickname (5) \n" ;
cout << "Quit The Program (0) \n\n" ;
cout << "Please Enter The Number : " ;
}
Author addauthor(Author *v ){
cout << "Enter ID: ";
cin >> v->id;
cout << "Enter Full Name: ";
cin.ignore();
getline(cin ,v->fullname) ;
cout << "Enter nickname: ";
cin >> v->nickname;
cout << "Enter Age: ";
cin >> v->age;
cout << endl ;
return *v ;
}
void displayauthor(Author *v ){
cout << "ID: " << v->id << endl;
cout << "Full Name: " << v->fullname << endl;
cout << "Nickname: " << v->nickname << endl ;
cout << "Age: " << v->age << endl << endl;
}
Book addbook(Book *v ){
cout << "Enter ID: ";
cin >> v->id;
cout << "Enter Title: ";
cin.ignore();
getline(cin ,v->title);
cout << "Enter Year: ";
cin >> v->year;
cout << "Enter Price : RM";
cin >> v->price;
cout << endl ;
return *v ;
}
void displaybook(Book *v ){
cout << "ID: " << v->id << endl;
cout << "Title: " << v->title << endl;
cout << "Year: " << v->year << endl ;
cout << "Price: RM" << v->price << endl << endl;
}
int main()
{
int n ;
Author a[1000];
Book b[1000];
int i, j , num1 , num2 ,id ;
string sr, rp;
do {
menu();
cin >> n ;
{
if (n==1) {
cout << "Please Enter the number of Author (Max 100): ";
cin >> num1;
cout << endl ;
for(i = 0 ;i < num1 ; i++ )
{
a[i]= addauthor(&a[i]);
}
}
else if (n==2) {
cout << "\nAuthor Information." << endl << endl;
for(i = 0 ;i < num1 ; i++ )
{
displayauthor(&a[i]);
}
}
else if (n==3) {
cout << "Please Enter the number of Book (Max 100): ";
cin >> num2;
cout << endl ;
for( i = 0 ;i < num2 ; i++ )
{
b[i]= addbook(&b[i]);
}
}
else if (n==4) {
cout << "\nBook Information." << endl << endl;
for(i = 0 ;i < num2 ; i++ )
{
displaybook(&b[i]);
}
}
else if (n==5) {
cout << "Please Enter Old Nickname : " << endl ;
cin >> sr ;
cout << "Please Enter Author New Nickname : " << endl ;
cin >> rp ;
for (int j = 0 ; j < num1 ; j++){
if (a.nickname[j] == sr){
cout << " The nickname has been Found." ;
a.nickname[j]=rp;
}
else {
cout << " Nickname not found ." ;
}
}
}
else {
cout << "The number you've enter is not available"<< endl << endl ;
}
}
}while (n !=0);
cout << "Program end" ;
return 0;
}
I tried to replace a nickname for the selected author which happen on this part
else if (n==5) {
cout << "Please Enter Old Nickname : " << endl ;
cin >> sr ;
cout << "Please Enter Author New Nickname : " << endl ;
cin >> rp ;
for (int j = 0 ; j < num1 ; j++){
if (a.nickname[j] == sr){
cout << " The nickname has been Found." ;
a.nickname[j]=rp;
}
else {
cout << " Nickname not found ." ;
}
}
}
So basically, the user tried to enter a new nickname for the Author by having the user to enter an old one and the error is "error: request for member ‘nickname’ in ‘a’, which is of non-class type ‘Author [1000]’" which happened in this 2 lines :
if (a.nickname[j] == sr){
a.nickname[j]=rp;
| The problem you're facing is just the order of operations you're performing.
a is an array of Authors, nickname is the member variable you're trying to access.
you first need to decide which array entry you want to select by using a[j], then afterwards access the member variable 'nickname' by appending .nickname.
this results in the statement a[j].nickname instead of a.nickname[j]
|
71,552,539 | 71,552,577 | How to create a Discord bot in C++ 98 with platform toolset version v120? | I'm working on a C++ 98 project with platform toolset version v120 on VS 2013. I'm trying to implement Discord bot API in my project. I've tried several unofficial Discord libraries for C++, like Sleepy-Discord, DPP, and Discord.CPP. But it seems like none of them are compatible with my project's C++/platform toolset version. Unfortunately, I cannot update my project as it's too big. I want to know if there's any solution for this.
What I'm expecting:
A Discord lib for CPP compatible with my project's PTV v120.
Or a way to downgrade one of the Discord libraries to make it compatible with my project.
Or a way to interact with the Discord API through my project.
Any other way.
Thank you.
| As stated on the Discord Developer Portal, their API can be accessed entirely through web requests. You don't need any additional libraries, except if you want to use a prebuilt REST or WebSocket library for easier use, which - if available to you - i would highly recommend.
|
71,553,105 | 71,553,142 | Seg fault with default allocation std::set<void*> | I am trying to learn STL allocators for void*. Here is my code
#include <set>
#include <memory>
class Test {
public:
std::set<void*> GetAllInformation() { return info_set_; }
private:
std::set<void*> info_set_;
};
int main() {
std::unique_ptr<Test> test_obj_;
const auto info = test_obj_->GetAllInformation();
if (info.empty())
std::cout << "info empty";
return 0;
}
But I am getting Segmentation fault at
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00402a18 in std::_Rb_tree<void*, void*, std::_Identity<void*>, std::less<void*>, std::allocator<void*> >::_M_root (this=0x0) at C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/stl_tree.h:733
The stl_tree.h
_Const_Base_ptr
_M_root() const _GLIBCXX_NOEXCEPT
{ return this->_M_impl._M_header._M_parent; }
could anyone help to explain?
Thanks
| The problem is that currently test_obj_ is not pointing to any Test object. Thus the expression test_obj_->GetAllInformation() leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash(which is what happens in your case).
For example, here the program doesn't crash but here it crashes.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
71,553,445 | 71,553,636 | Concatenation of multiple absolute std::filesystem::path instances | Why is the result of concatenating the following paths /c/d?
std::filesystem::path{"/a"} / std::filesystem::path{"b"} / std::filesystem::path{"/c/d"}
My mental model so far had the resulting path set to /a/b/c/d. To my surprise, it was simply /c/d. Curious to know where I went wrong here. (And what the right mental model is)
| /a is an absolute path, and b is a relative path, so concatenating them will produce /a/b.
But /c/d is also an absolute path, so concatenating it with anything in front of it is basically a no-op, the absolute path will take priority, so the final result is just /c/d.
This is discussed in more detail on cppreference.com:
std::filesystem::operator/(std::filesystem::path)
Concatenates two path components using the preferred directory separator if appropriate (see operator/= for details).
Effectively returns path(lhs) /= rhs.
std::filesystem::path::operator/=
path& operator/=( const path& p );
If p.is_absolute() || (p.has_root_name() && p.root_name() != root_name()), then replaces the current path with p as if by operator=(p) and finishes.
To get the result you want, drop the leading / from /c/d to make it a relative path:
std::filesystem::path{"/a"} / std::filesystem::path{"b"} / std::filesystem::path{"c/d"}
|
71,553,666 | 71,554,186 | How to insert pointer in QGraphicsItem so when they get selected pointer will be accessed? | I want to select rectangle/polyline through scene with mouse click and should be able to print it's name and other property. It's name and other properties are in the graph node. But I dont want to interact graph again.
So when I was drawing rectangle/polyline through graph co-ordinates, I should be able to store some pointer of graph node on rectangle/polyline so when I will click on rectangle/polyline, then through that pointer I can access it's name and other properties.
Question is `Is this possible ?
Among all above parameters, I want to store only _Ptr ( it is basically a pointer, but store as long, while using it will be type cast )
rect = new myRect();
while(true)
{
for(auto iter = verts.begin();iter != verts.end();++iter)
{
// getting co-ordinates of rectangle
QGraphicsRectItem* rectItem = rect->createRect(co-ordinates of rectangle);
rect->_Ptr = iter->_Ptr; // trying to store _crossRefPtr
}
}
myRect.h
class myRect : public QGraphicsRectItem
{
........
QGraphicsRectItem* createRect(QRectF& rect);
}
And when I will click on rectangle on scene through mouse I am doing like this:
if(_scene->selectedItems().count() != 0)
{
foreach(QGraphicsItem* currentItem, _scene->selectedItems())
{
QGraphicsRectItem* rItem = qgraphicsitem_cast<QGraphicsRectItem*>(currentItem);
if(rItem)
{
myRect* r = reinterpret_cast<myRect*>(rItem);
if(r)
{
Instance (rectangle)
Instance* i = reinterpret_cast<Instance*>(r->_boostRefPtr);
qDebug()<< i->Name();
}
}
But aobve way is wrong. Getting run time errors ( Showing Verbose stack trace)
So the question is :
How to store pointer on QGraphicsItem so that, once they get selected,
that pointer will be accessed ?
| Use Qt's dynamic properties, check QObject::setProperty. It should do the trick.
But AFAIC, I would have used a double QMap to associate directly <graph_node, QGraphicsItem> AND <QGraphicsItem, graph_node> - so you can search quickly for both associations, and both in O(log2(n)) complexity. You can store this either as a static part of your graph (better) or standalone (not the best idea). Obviously, if your graph is already in O(log2(n)), you don't need this map and you need only the <QGraphicsItem, graph_node> one.
|
71,555,055 | 71,555,120 | Explanation of the C++ template function argument deduction when matching `T const &&t` against `int const *` | I don't understand how the argument deduction rule works in this case. I have the following simple code snippet:
template<typename T>
void fn(T const &&t) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
std::cout << typeid(decltype(t)).name() << std::endl;
}
int main() {
int const *ar = nullptr;
std::cout << typeid(ar).name() << std::endl;
fn(std::move(ar));
}
The result I get is as follows:
PKi
void fn(const T &&) [T = const int *]
PKi
What I don't understand is why T is inferred as const int *. Why the const did not get pattern matched?
| In the parameter declaration T const &&t, const is qualified on T, i.e. t is declared as an rvalue-reference to const T.
When ar with type const int * is passed, T is deduced as const int *, then the type of t would be const int * const &&, i.e. an rvalue-reference to const pointer to const int. Note that the consts are qualified on different things (on different levels), one for the pointer, one for the pointee.
|
71,555,500 | 71,555,616 | Separate declaration and definition in .h and .cpp but NON-class functions? | I have the practice of writing functions that do not have to be in a class in namespaces, so I would like to know if can separate them in source and headers files:
utilities.hpp:
namespace nms {
static void process();
};
utilities.cpp
void nms::process(){/*...*/}
But like this I only get an error: main.cpp:(.text+0x5): undefined reference to 'nms::process()'. So i would like to know if this is possible in anyway.
| In the header file utilities.hpp:
namespace nms {
static void process();
};
static means the function has internal linkage, meaning it declares a unique function for each translation unit in which the header is included.
The only translation unit (TU) for which the corresponding unique (internal linkage) process() function has a definition is, however, in the TU associated with utilities.cpp, whereas for any other source file which includes utilities.hpp, no definition exists for the TU-local process() function.
This explains why you get undefined reference errors in locations other than utilities.cpp, as soon as that use site requires a definition for the TU-local function. Remove static and the publically-intended process() function will not have internal linkage.
... but NON-class functions?
The static keyword is unfortunately quite overloaded in meaning in C++, and static for class member function does not mean the same thing as for a namespace scope function as process() above. For class member function, using the static keyword makes the static members ([class.static].
|
71,556,162 | 71,556,586 | Provide different functionality with subclasses | I don't know if this title is descriptive enough... but I have no idea what else to call it. What I'm trying to do is the following:
There is a class (lets call it the AgentClass) that consumes the functionality of some other class (in this example the Initializer). I have different versions of Initializer (like ZeroInit, RandomInit, OptimisticInit) that inherit from a common base class.
How would I best implement this system, so that when the 'AgentClass' gets instantiated, I will be able to specify which type of Initializer I get? I was thinking of templates... but does this work on the level of classes as typenames? Additionally I think the methods provided by the Initializer can be static. How does that affect the implementation?
Here is some code:
//base_init.h
class BaseInit
{
public:
virtual init(double** data) = 0;
}
//zero_init.h
#include "base_init.h"
class ZeroInit : BaseInint
{
init(double** data) override;
}
//random_init.h
#include "base_init.h"
class RandomInit : BaseInint
{
init(double** data) override;
}
//agent_class.cpp
#include "base_init.h"
#include "zero_init.h"
#include "random_init.h"
class AgentClass
{
private:
double** data;
public:
AgentClass()
{
BaseInit* init = new ZeroInit(); // Problem here: ZeroInit is "hard coded". I would like this to be specified as constructor argument or template for AgentClass
init.init(data);
}
}
| Roughly speaking you have two options: Choose at runtime which derived class to use, then you can pass the instance as parameter to the constructor:
AgentClass(BaseInit& init)
{
init.init(data);
}
Or select at compile time which derived class to use. When it is ok that eg AgentClass<RandomInit> is a different type than AgentClass<ZeroInit> then you can make AgentClass a class template:
template <typename Init>
class AgentClass {
private:
double** data;
public:
AgentClass() {
Init{}.init(data);
}
}
In this case there is no need for BaseInit. The different parameters for Init can be completely unrelated types, as long as they provide an init method. Also in this case init can be a static function, so you need not create an instance of Init. With inheritance that isnt an option because you cannot override static methods in derived classes.
As mentioned in a comment by molbdnilo, if the xInit classes have no state and consist of a single method, then you do not need the classes in the first place. All you need is a function void(double**). You could pass a function pointer to a free function to the constructor for example.
|
71,556,814 | 71,557,402 | C++ Is data race big problem in producer/consumer pattern? | I still learning multithread programming with network involved.
My question is that when I designed threads as consumer/producer pattern, and producer modify variable randomly, consumer checks variable and do something based on it, would it be still bad(big problem)?
Like the code below.
int flag = 0;
void producer()
{
while(true)
{
// waits until packet arrives.
recv(socket, data);
if(data == 1)
flag = 1;
}
}
void consumer()
{
while(true)
{
if(flag == 1)
doSomething();
}
}
I guess doSomething() function will be called eventually. I don't need to sync these two thread perfectly. So I think it would be fine even if I don't use like std::atomic_int instead of int. (I would use std::atomic_int in this example, but in my real implementation, the variable is too complex to use std::atomic.)
So is it bad practice to just ignore data race problem? or is it rather good choice for performance?
| A data race results in undefined behavior.
C++ draft N4860
6.9.2.1 Data races (21.2)
The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.
and
3.30 undefined behavior
Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, [...]
So, if you can live with undefined behavior, e.g. a formatted hard disk or nasal demons, that's your choice.
If it's a Hello world program, you may get away with it. If it is a bank transaction over 2000€ which gets lost, I consider it as a problem. In my business, if I accidentally miss a network package with measurement points, a plane may crash. I consider it as a big problem.
In the comments you wrote:
Actually what I'm doing is game development, which sometimes I need to choose performance over correctness.
Granted, in game development, you make a compromise between performance and correctness. But typically it means that the amount of correctness is measurable or estimatable. E.g. a physics engine updating only 50 times per second instead of 100 times per second. But still, the result is correct to the extent possible.
With undefined behavior, it's hard to tell how incorrect "unpredictable results" actually are. You don't want the result to change with every new compiler for example.
I suggest you implement it in a thread-safe way and then check whether or not you actually have a performance problem. I bet: there will be a solution which does not require undefined behavior and is still fast enough. It has been done before.
Premature optimization is the root of all evil.
as Donald Knuth said.
|
71,556,861 | 71,557,659 | Cast a variable to void pointer in Julia | In C/C++ we are able to do this:
double my_var = 4.32;
void* my_var_ptr = &my_var;
which results in the my_var_ptr being a void pointer pointing to the memory which stores the value 4.32.
I am trying to do the same in Julia, but I face several errors. Naively, I tried this:
my_var=Cdouble(4.32)
my_var_ptr=Ptr{Cvoid}(pointer(my_var))
which failed with the error:
ERROR: MethodError: no method matching pointer(::Float64)
The failure (I assume) is because I am trying to create a Cvoid pointer from Cdouble object.
Any solution on that?
Thanks in advance!
| TL; DR
julia> my_var = Cdouble(4.32)
julia> my_var_ptr = Ptr{Cvoid}(pointer_from_objref(Ref(my_var)))
Ptr{Nothing} @0x00007f2a9148c6c0
pointer only works for array-like elements
julia> methods(pointer)
# 18 methods for generic function "pointer":
[1] pointer(a::Random.UnsafeView) in Random at /usr/share/julia/stdlib/v1.7/Random/src/RNGs.jl:516
[2] pointer(x::SuiteSparse.CHOLMOD.Sparse{Tv}) where Tv in SuiteSparse.CHOLMOD at /usr/share/julia/stdlib/v1.7/SuiteSparse/src/cholmod.jl:359
[3] pointer(x::SuiteSparse.CHOLMOD.Dense{Tv}) where Tv in SuiteSparse.CHOLMOD at /usr/share/julia/stdlib/v1.7/SuiteSparse/src/cholmod.jl:358
[4] pointer(x::SuiteSparse.CHOLMOD.Factor{Tv}) where Tv in SuiteSparse.CHOLMOD at /usr/share/julia/stdlib/v1.7/SuiteSparse/src/cholmod.jl:360
[5] pointer(V::SubArray{T, N, P, I, true} where {T, N, P, I<:Union{Tuple{Vararg{Real}}, Tuple{AbstractUnitRange, Vararg{Any}}}}, i::Int64) in Base at subarray.jl:431
[6] pointer(V::SubArray{T, N, P, I, true} where {T, N, P, I}, i::Int64) in Base at subarray.jl:430
[7] pointer(V::SubArray{<:Any, <:Any, <:Array, <:Tuple{Vararg{Union{Int64, AbstractRange{Int64}}}}}, is::Base.AbstractCartesianIndex{N}) where N in Base at subarray.jl:433
[8] pointer(V::SubArray{<:Any, <:Any, <:Array, <:Tuple{Vararg{Union{Int64, AbstractRange{Int64}}}}}, is::Tuple) in Base at deprecated.jl:212
[9] pointer(A::PermutedDimsArray, i::Integer) in Base.PermutedDimsArrays at permuteddimsarray.jl:61
[10] pointer(x::AbstractArray{T}) where T in Base at abstractarray.jl:1164
[11] pointer(x::AbstractArray{T}, i::Integer) where T in Base at abstractarray.jl:1165
[12] pointer(p::Cstring) in Base at c.jl:186
[13] pointer(buffer::Base64.Buffer) in Base64 at /usr/share/julia/stdlib/v1.7/Base64/src/buffer.jl:20
[14] pointer(x::SubString{String}) in Base at strings/substring.jl:122
[15] pointer(x::SubString{String}, i::Integer) in Base at strings/substring.jl:123
[16] pointer(p::Cwstring) in Base at c.jl:187
[17] pointer(s::String) in Base at strings/string.jl:95
[18] pointer(s::String, i::Integer) in Base at strings/string.jl:96
However, you should check pointer_from_objref, for example:
julia> pointer_from_objref(Ref(1))
Ptr{Nothing} @0x00007f2a914feb60
But from the wiki...
Get the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr will be used.
This function may not be called on immutable objects, since they do not have stable memory addresses.
See also unsafe_pointer_from_objref.
|
71,557,313 | 71,557,625 | for loop not executing on zero parameters | I am a self-taught python & C programmer and Iam now trying to learn C++
As a small exercise, I tried to port a function I had created in a Python minigame of mine, that generates a random matrix, then averages it, to create a map with terrain elevation.
I tried implementing it in C++ using a trick with size_t and the maximum size of an array, which I have already used successfully in C before.
However, the for-loop in my AverageSurroundings seems not to run when it is ran on row or column 0. This is confirmed by the output on stderr (I don't know how to put it in the question, sorry) and causes a division by zero error, which should not happen. I have done a small fix, but I can't find the origin of the problem
Here is a minimal snippet showing the problem.
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/assignment.hpp> //for <<=
#include <cstdint>
#include <iostream>
static const std::size_t n_rows = 3;
static unsigned int
AverageSurroundings(const boost::numeric::ublas::matrix<unsigned int> mat,
const std::size_t row, const std::size_t col) {
std::uint_fast16_t sum = 0; // <= 9*255= 2295 => 12 bits
std::uint_fast8_t count = 0;
std::cerr << "AverageSurroundings(" << row << ',' << col << ") called." << '\n';
for ( std::size_t r = row - 1; r <= row + 1; r++) {
for (std::size_t c = col - 1; c <= col + 1; c++) { // these values should remain positive, so we just
// need to check if we are smaller than n_rows,
//thanks to the wraparound of size_t.
std::cerr<<"r:"<<r<<" c:"<<c<<'\n'; // FIXME : loop not executing on first row/column
if (r < n_rows && c < n_rows) {
sum += mat(r, c);
count++;
std::cerr << "AverageSurroundings(" << row << ',' << col << "): Neighbour found at (" << r<< ',' << c << ")." <<'\n';
}
}
}
std::cerr << std::endl; // flushing and adding a blank line.
return count ? static_cast<unsigned int>(sum / count):0; // count is 8bits long so no overflow is possible, casting to silence warning.
//added ? to avoid floating point error for debug. FIXME : This should NOT BE 0
}
static const boost::numeric::ublas::matrix<unsigned int>
Average(const boost::numeric::ublas::matrix<unsigned int> mat,
const std::size_t rows) {
using boost::numeric::ublas::matrix;
matrix<unsigned int> m(n_rows, n_rows);
for (std::size_t row = 0; row < rows; row++) {
for (std::size_t col = 0; col < rows; col++) {
m(row, col) = AverageSurroundings(mat, row, col);
std::cout << m(row, col) << '\t';
}
std::cout << '\n';
}
std::cout << std::endl;
return m;
}
int main() {
using boost::numeric::ublas::matrix;
matrix<unsigned int> m(n_rows,n_rows); m <<= 0, 1, 2,
3, 4, 5,
6, 7, 8;
std::cout<< "---- RESULT ----" << '\n';
const matrix<unsigned int> m2 = Average(m, n_rows);
}
and the corresponding output.
---- RESULT ----
0 0 0
0 4 4
0 5 6
Any help on the issue and remarks or code formatting are welcome.
| You make a call to AverageSurroundings with row==0 and/or col==0 (see your loop variables in Average).
But std::size_t is an UNSIGNED type... So when it's zero, minus 1, it underflows in AverageSurroundings's loops and returns 0xFFFF FFFF FFFF FFFF... Which is obviously greater than row+1 (or col+1). So the loop isn't executed not a single time.
Even without the underflow, you would still be outside your matrix, even with a proper "-1" as index...
|
71,557,908 | 71,558,201 | sprintf into char* var[1] fails with Segmentation fault | consider code:
using std::cout; using std::cerr;
using std::endl; using std::string;
using std::vector;
// . . .
char* envp[10];
vector<string> lines;
char* c_line = nullptr;
size_t len = 0;
while ((getline(&c_line, &len, input_file)) != -1) {
string line;
lines.push_back(line.assign(c_line));
}
fclose(input_file);
free(c_line);
sprintf(envp[0], "SERVER=%s", lines[0].data());
// printing envp[0] here OK
sprintf(envp[1], "DOMAIN=%s", lines[1].data());
// printing envp[1] never happened - Segmentation fault prints in output instead
I am C# dev I havent used C for couple decades. Something obvious is missing. Mem allocation?
P.S. I am mixing "old" char * for strings with std strings as the app uses 3rd party dll with chars*
EDIT declaring char envp[10][512]; fails down the line when I try to assing to the 3rd party property somedllObj.envps = envp; with cannot convert char[10][512] to char**
| I do not recommend mixing std::string and old C-strings in such a wild manner. Instead I'd rely on C++ classes as long as possible:
std::ifstream inputFile("path to file");
if(!inputFile)
{
// error handling
}
std::vector<std::string> lines;
std::string tmp;
while(std::getline(inputFile, tmp))
{
lines.emplace_back(std::move(tmp)); // since C++11, not copying the strings...
}
if(!inputFile.eof())
{
// not the entire file read
// -> error handling!
}
// TODO: size check; what, if not sufficient lines in file?
lines[0] = std::string("SERVER=") + lines[0];
lines[1] = std::string("DOMAIN=") + lines[1];
std::vector<char*> envp;
envp.reserve(lines.size());
for(auto& l : lines) // C++11: range based for loop...
{
// note that this ABSOLUTELY requires the library not
// modifying the strings, otherwise undefined behaviour!
envp.emplace_back(const_cast<char*>(l.c_str()));
// UPDATE: this works as well:
envp.emplace_back(l.data());
// the string is allowed to be modified, too – apart from
// the terminating null character (undefined behaviour!)
}
// so far, pure C++...
// now we just get the pointers out of the vector:
libraryFunction(envp.size(), envp.data());
Bonus: No manual memory management at all...
(Note: Assuming the strings are not modified in the library!)
|
71,558,090 | 71,558,091 | What language rules governs that `T&&` in a templated array-by-&& function argument is *not* a forwarding reference? | A static analysis tool I'm using prompts me that I need to std::forward the argument of the following function down the call chain:
template<typename T, std::size_t size>
constexpr void f(T (&& arr)[size]) { /* linter: use std::forward on 'arr' here */ }
as it identifies the function parameter type as a forwarding reference.
A simple test on several compilers show, however, that this is not a forwarding reference. The following example
void g() {
int a[3]{1, 2, 3};
f(a); // #1
}
is rejected at #1 (DEMO), explicitly pointing our that the function parameter is an rvalue reference:
error: cannot bind rvalue reference of type 'int (&&)[3]' to lvalue of type 'int [3]'
Question
What language rules governs that T&& in a templated array-by-&& function argument as in f above is not a forwarding reference?
| The relevant section is [temp.deduct.call]/1 [emphasis mine]:
Template argument deduction is done by comparing each function
template parameter type (call it P) that contains
template-parameters that participate in template argument deduction
with the type of the corresponding argument of the call (call it A)
as described below. If removing references and cv-qualifiers from
P gives std::initializer_list<P′> or P′[N] for some P′
and N and the argument is a non-empty initializer list
([dcl.init.list]), then deduction is performed instead for each
element of the initializer list independently, taking P′ as
separate function template parameter types P′i and the i:th
initializer element as the corresponding argument. [...]
Meaning [temp.deduct.call]/3 does not apply for a P that was originally an array reference type (once it reaches /3, /3 applies per element).
However, if we return to the section above we may note that it comes with the restriction
[...] and the argument is a non-empty initializer list [...]
meaning a call, for OP's example function f, like
f({1, 2, 3}); // [temp.deduct.call]/1 applies
But what about the case where the argument is not an initializer list, but an array?
int arr[3]{1, 2, 3};
f(arr);
[temp.deduct.call]/2 have special rules for arrays, but it does not apply as P is a reference type, meaning we do end up at [temp.deduct.call]/3:
If P is a cv-qualified type, the top-level cv-qualifiers of P's type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction.
A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])). If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction.
The function parameter in f, however, is an rvalue reference to T[size], which is not a template parameter. This governs the case for when the argument is not an initializer list (and arguably also that case).
|
71,558,263 | 71,559,966 | Proper way to perform unsigned<->signed conversion | Context
I have a char variable on which I need to apply a transformation (for example, add an offset). The result of the transformation may or may not overflow.
I don't really care of the actual value of the variable after the transformation is performed.
The only guarantee I want to have is that I must be able to retrieve the original value if I perform the transformation again but in the opposite way (for example, substract the offset).
Basically:
char a = 42;
a += 140; // overflows (undefined behaviour)
a -= 140; // must be equal to 42
Problem
I know that signed types overflow is undefined behaviour but it's not the case for unsigned types overflows. I have then chosen to add an intermediate step in the process to perform the conversion.
It would then become:
char -> unsigned char conversion
Apply the tranformation (resp. the reversed transformation)
unsigned char -> char conversion
This way, I have the garantee that the potential overflow will only occur for an unsigned type.
Question
My question is, what is the proper way to perform such a conversion ?
Three possibilities come in my mind. I can either:
implicit conversion
static_cast
reinterpret_cast
Which one is valid (not undefined behaviour) ? Which one should I use (correct behaviour) ?
My guess is that I need to use reinterpret_cast since I don't care of actual value, the only guarantee I want is that the value in memory remains the same (i.e. the bits don't change) so that it can be reversible.
On the other hand, I'm not sure if the implicit conversion or the static_cast won't trigger undefined behaviour in the case where the value is not representable in the destination type (out of range).
I couldn't find anything explicitly stating it is or is not undefined behaviour, I just found this Microsoft documentation where they did it with implicit conversions without any mention of undefined behaviour.
Here is an example, to illustrate:
char a = -4; // out of unsigned char range
unsigned char b1 = a; // (A)
unsigned char b2 = static_cast<unsigned char>(a); // (B)
unsigned char b3 = reinterpret_cast<unsigned char&>(a); // (C)
std::cout << (b1 == b2 && b2 == b3) << '\n';
unsigned char c = 252; // out of (signed) char range
char d1 = c; // (A')
char d2 = static_cast<char>(c); // (B')
char d3 = reinterpret_cast<char&>(c); // (C')
std::cout << (d1 == d2 && d2 == d3) << '\n';
The output is:
true
true
Unless undefined behaviour is triggered, the three methods seem to work.
Are (A) and (B) (resp. (A') and (B')) undefined behaviour if the value is not representable in the destination type ?
Is (C) (resp. (C')) well defined ?
|
I know that signed types overflow is undefined behaviour,
True, but does not apply here.
a += 140; is not signed integer overflow, not UB. That is like a = a + 140; a + 140 does not overflow when a is 8-bit signed char or unsigned char.
The issue is what happens when the sum a + 140 is out of char range and assigned to a char.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. C17dr § 6.3.1.3 3
It is implementation defined behavior, when char is signed and 8-bit - to assign a value outside the char range.
Usually the implementation defined behavior is a wrap and fully defined so a += 140; is fine as is.
Alternatively the implementation defined behavior might have been to cap the value to the char range when char is signed.
char a = 42;
a += 140;
// Might act as if
a = max(min(a + 140, CHAR_MAX), CHAR_MIN);
a = 127;
To avoid implementation defined behavior, perform the + or - on a accessed as a unsigned char
*((unsigned char *)&a) += small_offset;
Or just use unsigned char a and avoid all this. unsigned char is defined to wrap.
|
71,558,576 | 71,559,078 | Why hasn't cppreference got any knowledge points about _Base_bitset when introducing bitsets? | I noticed that in cppreference/bitset, bitset is not mentioned to be inherited from _ Base_bitset , including the following header file.
Does the cppreference estimate omit this inheritance relationship?
namespace std {
template<size_t N> class bitset {
public:
// bit reference
class reference {
friend class bitset;
reference() noexcept;
public:
reference(const reference&) = default;
~reference();
reference& operator=(bool x) noexcept; // for b[i] = x;
reference& operator=(const reference&) noexcept; // for b[i] = b[j];
bool operator~() const noexcept; // flips the bit
operator bool() const noexcept; // for x = b[i];
reference& flip() noexcept; // for b[i].flip();
};
// constructors
constexpr bitset() noexcept;
constexpr bitset(unsigned long long val) noexcept;
template<class CharT, class Traits, class Allocator>
explicit bitset(
const basic_string<CharT, Traits, Allocator>& str,
typename basic_string<CharT, Traits, Allocator>::size_type pos = 0,
typename basic_string<CharT, Traits, Allocator>::size_type n
= basic_string<CharT, Traits, Allocator>::npos,
CharT zero = CharT('0'),
CharT one = CharT('1'));
template<class CharT>
explicit bitset(
const charT* str,
typename basic_string<CharT>::size_type n = basic_string<CharT>::npos,
CharT zero = CharT('0'),
CharT one = CharT('1'));
// bitset operations
bitset& operator&=(const bitset& rhs) noexcept;
bitset& operator|=(const bitset& rhs) noexcept;
bitset& operator^=(const bitset& rhs) noexcept;
bitset& operator<<=(size_t pos) noexcept;
bitset& operator>>=(size_t pos) noexcept;
bitset& set() noexcept;
bitset& set(size_t pos, bool val = true);
bitset& reset() noexcept;
bitset& reset(size_t pos);
bitset operator~() const noexcept;
bitset& flip() noexcept;
bitset& flip(size_t pos);
// element access
constexpr bool operator[](size_t pos) const; // for b[i];
reference operator[](size_t pos); // for b[i];
unsigned long to_ulong() const;
unsigned long long to_ullong() const;
template<class CharT = char,
class Traits = char_Traits<CharT>,
class Allocator = allocator<CharT>>
basic_string<CharT, Traits, Allocator>
to_string(CharT zero = CharT('0'), CharT one = CharT('1')) const;
size_t count() const noexcept;
constexpr size_t size() const noexcept;
bool operator==(const bitset& rhs) const noexcept;
bool test(size_t pos) const;
bool all() const noexcept;
bool any() const noexcept;
bool none() const noexcept;
bitset operator<<(size_t pos) const noexcept;
bitset operator>>(size_t pos) const noexcept;
};
// hash support
template<class T> struct hash;
template<size_t N> struct hash<bitset<N>>;
}
| The description of std::bitset can be found in the C++ Standard at 22.9 Utilities.bitset.
It doesn't mention _Base_bitset or other details, because those are left to the library implementors.
|
71,558,717 | 71,558,790 | Proper use of template classes | I have an exercise wherein I must use a template class "Garage" that takes as parameters either a "car" or a "bike". Easy enough but I keep getting errors since I obviously don't understand the templates well enough. Is this :
template<class Car>
class Garage{
Car array[10];
public:
void addCar(int counter1);
void removeCar(int counter1);
void displayContents(int counter1);
};
template<class Motorbike>
class Garage{
Motorbike array[10];
public:
void addMotorbike(int counter2);
void removeMotorbike(int counter2);
void displayContents(int counter2);
};
proper ? Do I have to insert the template infront of every function of the class ?
The program of course contains more classes and functions but its the template thing I need to get sorted out in my head.
Thanks for taking the time.
| If you had to write out specifically every implementation for each instantiation then there would be no need for templates in the first place. You could name your classes CarGarage and MotorbikeGarage and call it a day. You probably want something along the line of this:
template<class VehicleType>
class Garage{
VehicleType array[10];
public:
void addVehicle(int counter1);
void removeVehicle(int counter1);
void displayContents(int counter1);
};
From this class template (it is not a template class, there are no template classes. Garage is a template, not a class) you can instantiate the types Garage<Car> which has an array of Cars as member and a Garage<Motorbike> which has an array of Motorbikes as member.
Implementations of the member functions need to be in the header (see Why can templates only be implemented in the header file?). And it is easiest to define them inline within the template.
|
71,558,802 | 71,559,812 | Vector out of boundaries access: why such behavior? | I am aware that out of boundary access of an std::vector in C++ with the operator[] results in undefined behavior. So, I should not expect anything meaningful doing that. However, I'm curious about what is actually happening there under the hood.
Consider the following piece of code:
#include <iostream>
#include <vector>
int main() {
{
std::cerr << "Started\n";
std::vector<int> v(2);
std::cerr << "Successfully initialized vector\n";
v[-1] = 10000; // Note: if accessing v[3], nothing bad seems to happen
std::cerr << "Successfully accessed element -1\n";
}
std::cerr << "Successfully destructed the vector\n";
}
When compiled on GNU/Linux with g++ (GCC) 11.2.0, running this code produces the following output:
Started
Successfully initialized vector
Successfully accessed element -1
double free or corruption (out)
Aborted (core dumped)
Why could have that happened? Why does it cause the destructor to fail? Why does it produce such an error message?
I would understand it if I was using some structure that stored the array together with it on the stack: I would then accidentally access some of its internal data that lies right before v[0] and could have broken something. But as far as I know, the underlying array of std::vector is stored on heap, so the data that I access should not even belong to it, should it? Also, because my last output attempt is taken right after exiting the block with only vector declared in it, I don't see what else except for its destructor could have been called, so the vector seems to be somehow affected by my action...
| A hypothetical answer that could have happened: The UB caused arbitrary piece of memory to be overwritten. This is called memory corruption.
That overwritten arbitrary piece of memory happened to be right before the dynamic memory that the vector allocated. The arbitrary piece of memory right before the allocation happened to contain an "information header" that describes the allocation. When the destructor was called, there was an attempt to deallocate the memory. The global allocator detected that the corrupted information was inconsistent, produced the diagnostic message and terminated the program.
This is what the source code of the global memory allocator on your system may look like: https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#4326 The link leads specifically to the line that produces the error message.
|
71,560,000 | 71,562,119 | Is there an issue with "cache coherence" on C++ multi-threading on a *Single CPU* (Multi-Core) on Windows? | (EDIT: Just to make it clear: The question of "cache coherence" is in the case that there is no use of atomic variables.)
Is it possible (A single CPU case: Windows can run on top of Intel / AMD / Arm CPU), that thread-1 runs on core-1 stores a bool variable (for example) and it stays in L1 cache, and thread-2 runs on core-n uses that variable, and it looks on another copy of it that is in the memory?
Code example (To demonstrate the issue, lets say that the std::atomic_bool is just a plain bool):
#include <thread>
#include <atomic>
#include <chrono>
std::atomic_bool g_exit{ false }, g_exited{ false };
using namespace std::chrono_literals;
void fn()
{
while (!g_exit.load(std::memory_order_relaxed))
{
// do something (lets say it takes 1-4s, repeatedly)
std::this_thread::sleep_for(1s);
}
g_exited.store(true, std::memory_order_relaxed);
}
int main()
{
std::thread wt(fn);
wt.detach();
// do something (lets say it took 2s)
std::this_thread::sleep_for(2s);
// Exit
g_exit.store(true, std::memory_order_relaxed);
for (int i = 0; i < 5; i++) { // Timeout: 5 seconds.
std::this_thread::sleep_for(1s);
if (g_exited.load(std::memory_order_relaxed)) {
break;
}
}
}
| CPU cache is always coherent across cores that we run C++ threads across1, whether they're in the same package (a multi-core CPU) and/or spread across sockets with an interconnect. That makes it impossible to load a stale value once the writing thread's store has executed and committed to cache. As part of doing that, it will send an invalidate request to all other caches in the system.
Other threads can always eventually see your updates to std::atomic vars, even with mo_relaxed. That's the entire point; std::atomic would be useless if it didn't work for this.
But without std::atomic, you code would be super broken, and a classic example of https://electronics.stackexchange.com/questions/387181/mcu-programming-c-o2-optimization-breaks-while-loop/387478#387478 / Multithreading program stuck in optimized mode but runs normally in -O0 - the compiler can assume that no other thread is writing a non-atomic var it's reading, so it can hoist the actual load out of the loop and keep it in a thread-private CPU register. So it's not re-reading from coherent cache at all. i.e. while(!exit_now){} becomes if(!exit_now) while(1){} for a plain bool exit_now global.
(Except that your sleep_for call would probably prevent that optimization. It's probably not declared pure, because you don't want compilers to optimize out multiple calls to it; time is the side-effect. So the compiler has to assume that calls to it could modify global vars, and thus would re-read the global var from memory (with normal load instructions that go through coherent cache)).
Footnote 1: C++ implementations that support std::thread only run it across cores in the same coherency domain. In almost all systems, there is only one coherency domain that includes all cores in all sockets, but huge clusters with non-coherent shared memory between nodes are possible.
So are embedded boards with an ARM microcontroller core sharing memory but not coherent with an ARM DSP core. You wouldn't be running a single OS across both those cores, and you wouldn't consider code running on those different cores part of the same C++ program.
For more details about cache coherency, see When to use volatile with multi threading?
|
71,560,016 | 71,560,236 | Template specialization not taking place | #include<bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
inline T1 max (T1 const& a, T2 const& b)
{
return a < b ? b : a;
}
template <>
inline int max<int,int> (const int& a, const int& b)
{
return 10;
}
int main() {
cout << max(4,4.2) << endl;
cout << max(5,5) << endl;
return 0;
}
The output for the above code is 4 5 and not 4 10, please explain why.
| using namespace std; will make all names from the standard library namespace std visible to unqualified name lookup as if they were defined in the global namespace.
This includes the function std::max which has an overload of the form
template<typename T>
const T& max(const T&, const T&);
This overload is chosen for your call max(5,5) with T=int since it is more specialized than your function template with two different template parameters.
This is exactly the reason that using namespace std; is not recommended. Instead write only using declarations for the names you want imported, e.g.
using std::cout;
using std::endl;
or always qualify all standard library names with std:: when used.
|
71,560,565 | 71,560,796 | Moving unique_ptr inside a lambda function gives me a compiler error on C++17 | Given the following hierarchy:
class IJobInterface
{
};
class JobAbstract : public IJobInterface
{
public:
JobAbstract(std::string n) : name(n) {};
protected:
std::string name;
};
class JobConcrete: public JobAbstract
{
public:
JobConcrete(std::string n, int i) : JobAbstract(n), index(i) {};
void doIt();
private:
int index;
};
When I need to pass JobConcrete as unique_ptr param inside a lambda function:
void doSomenthigHeavy(std::unique_ptr<JobConcrete> j)
{
j->doIt();
}
void main()
{
auto job = std::make_unique<JobConcrete>("name", 0);
doSomenthigHeavy(std::move(job)); //it works
auto t = std::thread([j = std::move(job)]
{
doSomenthigHeavy(std::move(j)); //it doesn't work
});
}
Then I get a compiler error:
The question is: what am I missing here?
Calling doSomenthigHeavy from inside a lambda produces a compiler error while from outside it doesn't.
| The issue is that lambda's operator () is declared const and with the move you try to modify the unique pointer j.
Declare it mutable via auto t = std::thread([j = std::move(job)]() mutable ...) or pass the unique_ptr as an argument to the lambda.
|
71,560,793 | 71,561,534 | How to use enum from another class and file withouot repetitive scoping? c++ | I feel like this is an easy question but I don't seem to find the answer myself. I was wondering if there is a way of using the enum in another file, without having to use scoping?
e.g. Head.h
namespace h{
class Eye{
enum class State{
closed = 0, blinking, open, staring, rolling // etc.
};
void print(const State &eye);
};
class Body{
Eye::State eye;
Eye::State eyesOpen();
};
}
Head.cpp
namespace h{
void Eye::print(const State &eye){
switch(eye){
case Eye::State::closed: cout << "Closed" << endl;
case Eye::State::blinking: cout << "Blinking" << endl;
case Eye::State::open: cout << "Open" << endl;
}
bool Body::eyesOpen(){
return eye == Eye::open;
}
}
I am using Eye::State about 80+ times in my Body class, so I was wondering if there's a way for me to just state that State is Eye::State rather than having to write it 80 times?
Edit: Eye and Body are two separate classes. It's just that Body uses the Eye object
| Don't put a type alias at the top of the namespace unless that's really the logical scope you want.
If you just want to save typing in the Body methods you haven't shown, simply
namespace h{
class Body{
using State = Eye::State;
State eye;
State eyesOpen();
};
}
will work. It seems odd that the eyes are the only organ of this body whose state is important, though. If you really want more organ states later, you can remove the class-level alias and just write
bool Body::eyesOpen() {
using State = Eye::State;
return eye == State::open;
}
(which is no improvement at all, but imagine it's applied to the other 80 instances you haven't shown us).
|
71,560,852 | 71,561,469 | How to transform int parameter pack | Given a template
template <int... Ints>
struct FixedArray;
How to implement a meta function that multiplies each integer value by a given number?
template <int A, typename F>
struct Mul;
Mul<2, FixedArray<5, 7, 8>>::type
is the same as
FixedArray<10, 14, 16>
| To do this, you can first define an empty Mul class:
template<int A, typename T>
struct Mul;
Then create a specialization for FixedArray:
template<int A, int ... Ints>
struct Mul<A, FixedArray<Ints...>>
{
using type = FixedArray<(Ints * A)...>;
};
However, I'd rather have a typedef inside FixedArray, so the resulting syntax looks more natural to me:
template <int ... Ints>
struct FixedArray
{
template<int A>
using Mul = FixedArray<(Ints * A)...>;
};
static_assert(std::same_as<FixedArray<1,2,3>::Mul<2>, FixedArray<2,4,6>>);
|
71,561,883 | 71,562,135 | Virtual functions that act like dynamic casts | In JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS Bjarne states, that:
Down casting (casting from base to derived class) shall only be
allowed through one of the following mechanism:
Virtual functions that act like dynamic casts (most likely useful in
relatively simple cases)
Use of the visitor (or similar) pattern (most likely useful in
complicated cases)
I can't wrap my head around first proposition. Googling it presented no examples, nor explanation.
How can virtual function act like a dynamic cast?
| It's referring to a technique that was kind of common in the early days of C++, before dynamic_cast, RTTI, etc., were added to the language.
The basic idea looks something like this:
class Derived1;
class Derived2;
class Base {
public:
virtual Derived1 *toDerived1() const { return nullptr; }
virtual Derived2 *toDerivde2() const { return nullptr; }
};
class Derived1 : public Base {
public:
Derived1 *toDerived1() const override { return this; }
Derived2 *toDerived2() const override { return nullptr; }
};
class Derived2 : public Base {
public:
Derived1 *toDerived1() const override { return nullptr; }
Derived2 *toDerived2() const overrode { return this; }
};
This lets you do something just about like a dynamic_cast on a pointer, yielding a pointer to the expected type if the pointee object is actually of that type, and otherwise a nullptr.
This has obvious disadvantages though. Every class involved has to be aware of every other class. Adding a new class means adding a new function to every class. Unless the entire class structure is quite static (and a small number of classes altogether), this can quickly turn into a maintenance nightmare.
Reference
This technique was covered in Effective C++, 1st Edition, Item 39. I haven't checked to be sure, but it was probably dropped from the newer editions, as (at least in the minds of most programmers) the addition of dynamic_cast rendered it obsolescent (at best).
|
71,562,522 | 71,564,515 | Constructing a constexpr lambda with member function pointer | I am attempting to build a constexpr lambda that uses a member function pointer as part some type of registration process.
The problem is the outermost function that is part of that process is not constexpr which makes the argument (the function pointer) not valid in a constexpr context.
Can that createLambda call and variable storage (invokable) be made constexpr within that function (maybe pass the whole function point as a template argument?) and would I even save anything by making the lambda constexpr inside of "passthrough"?
A basic example is below. In the real code, the lambda is part of abstraction converting to an "any" type.
#include <iostream>
#include <map>
#include <functional>
std::map<uint64_t, std::function<int(void*)>> g_map;
class Data
{
public:
int returnData()
{
return m_data;
}
int m_data = 5;
};
template<
typename ReturnType,
typename ClassType
>
constexpr auto createLambda(ReturnType(ClassType::* method)(void))
{
return [=](void* object) -> int
{
return (reinterpret_cast<ClassType*>(object)->*method)();
};
}
template<
typename ReturnType,
typename ClassType
>
auto passthrough(ReturnType(ClassType::* method)(void)) // Function cannot be constexpr
{
auto invokable = createLambda(method); // This is not valid, what are my alternatives to make this possible?
constexpr uint64_t someOtherTask = 1 + 2;
g_map[someOtherTask] = invokable;
return invokable;
}
int main()
{
Data testData;
constexpr auto invoke = createLambda(&Data::returnData); // Works Fine
auto invoke2 = passthrough(&Data::returnData); // Does Not Work
testData.m_data = 7;
std::cout << invoke(&testData) << std::endl;
testData.m_data = 8;
std::cout << invoke2(&testData) << std::endl;
testData.m_data = 9;
std::cout << g_map[1 + 2](&testData) << std::endl;
return 0;
}
A concern I have is binary size bloat when used with literally thousands of member methods.
Assume a ceiling of C++17 standard and that the user should only have to make a single call to passthrough per member method (arguments can change if needed).
| If you want to make next statement constexpr
auto invokable = createLambda(method);
Pass method as non-type template argument
template<auto method>
auto passthrough() // Function cannot be constexpr
{
constexpr auto invokable = createLambda(method); // This is not valid, what are my alternatives to make this possible?
constexpr uint64_t someOtherTask = 1 + 2;
g_map[someOtherTask] = invokable;
return invokable;
}
And the call it like this
auto invoke2 = passthrough<&Data::returnData>();
The reason why you can not do auto invokable = createLambda(method); when method is function argument, because function arguments are not constexpr. Since, function is not scope of creating argument object.
If method was created inside passthrough it would work. Template argument is guaranteed to be evaluted at compile-time that's the reason why it can be used in function in constepxr context even, if was created outside of function
Code snippet in godbolt compiler https://godbolt.org/z/c6aqWW9j6
|
71,563,520 | 71,563,621 | literal type in constexpr expression and template parameter | Why do I can use non constexpr literal types in constexpr functions(such as reflection) and it can be returned as constexpr, but I can't use such types in template non-type parameters?
class Point {
public:
constexpr Point(double xVal = 0, double yVal = 0) noexcept
: x(xVal), y(yVal)
{}
constexpr double xValue() const noexcept { return x; }
constexpr double yValue() const noexcept { return y; }
constexpr void setX(double newX) noexcept { x = newX; }
constexpr void setY(double newY) noexcept { y = newY; }
private:
double x, y;
};
template <long long N>
void F()
{
std::cout << N << std::endl;
}
constexpr Point reflection(const Point& p) noexcept
{
Point result;
result.setX(p.xValue());
result.setY(p.yValue());
return result; // returning literal non consexpr type
}
int main()
{
constexpr Point p;
F<static_cast<long long>(reflection(p).xValue())>(); //result returned from reflection can be used here
Point p1;
p1.setX(123);
F<static_cast<long long>(p1.xValue())>(); //error: the value of ‘p1’ is not usable in a constant expression
}
| constexpr is not a property of a type. It is a specifier on a variable/function declaration.
Objects whose lifetime begins within the evaluation of the constant expression are usable in that constant expression and don't need to be declared constexpr.
The expression that needs to be a constant expression here is in the first case
static_cast<long long>(reflection(p).xValue())
The variable result inside reflection lives only during the evaluation of that expression and p is declared constexpr. Therefore both are usable in the constant expression.
In the second case the expression
static_cast<long long>(p1.xValue())
is required to be a constant expression. This uses p1, but p1 is not declared constexpr and its lifetime started before the evaluation of the expression, so it is not usable in the constant expression. More precisely the lvalue-to-rvalue conversion required in xValue() violates the requirements for a constant expression.
|
71,563,779 | 71,564,088 | What are dependent names in C++? | When is a C++ name "dependent"? Apparently it is not dependent when it uses a type-definition in the same scope. It is however dependent, when it uses a type definition in a nested scope of this scope. Consider the following examples:
Example A:
template <typename T>
struct some_struct
{
struct B
{
int b_;
};
T some_member_func();
T a_;
};
template <typename T>
T some_struct<T>::some_member_func()
{
using hello = B;
return a_;
}
.. compiles fine.
Example B (Nested):
template <typename T>
struct some_struct
{
struct B
{
struct C {
int c_;
};
};
T some_member_func();
T a_;
};
template <typename T>
T some_struct<T>::some_member_func()
{
using hello = B::C;
return a_;
}
..issues the following error:
<source>: In member function 'T some_struct<T>::some_member_func()':
<source>:365:19: error: need 'typename' before 'some_struct<T>::B::C' because 'some_struct<T>::B' is a dependent scope
365 | using hello = B::C;
| ^
| typename
Why is some_struct::B a dependent scope but not some_struct (example A)?
| If I'm reading https://en.cppreference.com/w/cpp/language/dependent_name correctly, both B and B::C are dependent.
But B also "refers to the current instantiation", which allows it to be used without typename. It seems to be a fancy way of saying that "whether it's a type can't be affected by specializations".
You can specialize B to make B::C not a type:
template <>
struct some_struct<int>::B
{
static void C() {}
};
(interestingly, a partial specialization didn't compile)
But you can't prevent B from being a type via specializations.
|
71,563,781 | 71,564,009 | How to input commands c++ | Hi I'm trying implement commands in a c++ console app
The app has a command prompt , basically does nothing until you type a specific command , now the problem is I can't find an efficient way to do this, the only solution I can think of is implementing thousands of if else statements which are not exactly efficient, also switch statements don't work on strings,
The commands are separate functions with different arguments and all commands are preprocessor definitions,
I tried implementing if else statements but they were silly
one other way i also could think of was using a scripting language and implementing my own functions, for example i could use chaiscript and implement my own function called 'new' which takes two parameters (first what type of file and second the name of the file) and i could give it the command line inputs instead of a script file, this approach could save me from creating my own scripting language or command line interface(whatever it is called)
| Have a std::map of string => std::function
Like this
#include <iostream>
#include <map>
#include <functional>
#include <string>
typedef std::function<void(const std::string &)> CmdFunc;
void cmda(const std::string &line) {
std::cout << "cmda " << line << "\n";
}
void cmdb(const std::string& line) {
std::cout << "cmdb " << line << "\n";
}
int main() {
std::map<std::string, CmdFunc > cmds;
cmds["a"] = cmda;
cmds["b"] = cmdb;
//...
while (true) {
std::string cmdLine;
std::getline(std::cin, cmdLine);
std::string token = cmdLine.substr(0, cmdLine.find(" "));
auto find = cmds.find(token);
if (find != cmds.end())
(find->second)(cmdLine);
else
std::cout << "unknown command\n";
}
}
output
a froot
cmda a froot
b wang
cmdb b wang
c
unknown command
|
71,563,790 | 71,563,886 | Need to store result of cURL http request as a map in C++ | I've been using cURL library in C++ to make HTTP requests. When storing the result in a string it works perfectly fine however the result is like this:
and this is all one continuous string. I want to access each exchange rate and save them into different variables so I can make calculations with them. I have tried saving it into a map instead of a string, and it compiles, but when running it aborts and it's not clear why.
The code giving me problems is here:
#define CURL_STATICLIB
#include "curl/curl.h"
#include <iostream>
#include <string>
#include <map>
// change cURL library depending on debug or release config
#ifdef _DEBUG
#pragma comment(lib, "curl/libcurl_a_debug.lib")
#else
#pragma comment (lib, "curl/libcurl_a.lib")
#endif
// extra required libraries
#pragma comment (lib, "Normaliz.lib")
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Wldap32.lib")
#pragma comment (lib, "Crypt32.lib")
#pragma comment (lib, "advapi32.lib")
static size_t my_write(void* buffer, size_t size, size_t nmemb, void* param)
{
std::string& text = *static_cast<std::string*>(param);
size_t totalsize = size * nmemb;
text.append(static_cast<char*>(buffer), totalsize);
return totalsize;
}
int main()
{
// create var to store result from request
std::map<std::string, double> result;
CURL* curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
// determine the setup options for the request
curl_easy_setopt(curl, CURLOPT_URL, "http://api.exchangeratesapi.io/v1/latest?access_key=9c6c5fc6ca81e2411e4058311eafdf3b&symbols=USD,GBP,AUD&format=1");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
// perform the http request
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (CURLE_OK != res) {
std::cerr << "CURL error: " << res << '\n';
}
}
curl_global_cleanup();
std::map <std::string, double> ::const_iterator i;
for (i = result.begin(); i != result.end(); i++)
{
std::cout << i->first << ": " << i->second;
}
}
To save it into a string, I replace:
std::map<std::string, double> result;
with std::string result; and also replace:
std::map <std::string, double> ::const_iterator i;
for (i = result.begin(); i != result.end(); i++)
{
std::cout << i->first << ": " << i->second;
}
with std::cout << result << "\n\n";.
With these replacements, it runs fine, but it's just not in the format I need it in, unless it's possible to extract the particular values from the string format?
I get the feeling that what I'm trying to do is very specific and I've struggled to find anything online that can help me.
| You are grabbing a JSON (JavaScript Object Notation) file. To make your life much easier you should look into using a library for processing JSON in C++ like jsoncpp. This site here provides a quick tutorial.
|
71,563,845 | 71,563,909 | Why do I get "forbids converting a string constant to ‘char*’" in C++? | I'm trying to invert the case manually, and I tried this:
char* invertirCase(char* str){
int size = 0;
char* iterador = str;
char* retorno = str;
while (*iterador != '\0') {
if (retorno[size] < 96) {
retorno[size] = *iterador + 32;
}
else {
retorno[size] = *iterador - 32;
}
iterador++;
size++;
}
return retorno;
}
I'm trying to figure out where's the error, but I don't get it since I'm pretty new at C++ language.
|
Why do I get "forbids converting a string constant to ‘char*’" in C++?
The error message means that you are trying to pass a string literal to the function.
String literals in C++ have types of constant character arrays that passed by value to functions are implicitly converted to the type const char *. And any attempt to change a string literal results in undefined behavior.
You could pass to the function a character array initialized by a string literal as for example
char s[] = "Hello";
std::cout << invertirCase( s ) << '\n';
In turn the function can be defined the following way
#include <cctype>
char * invertirCase( char *str )
{
for ( char *p = str; *p; ++p )
{
unsigned char c = *p;
if ( std::isalpha( c ) )
{
if ( std::islower( c ) )
{
*p = std::toupper( c );
}
else
{
*p = std::tolower( c );
}
}
}
return str;
}
or
char * invertirCase( char *str )
{
for ( char *p = str; *p; ++p )
{
unsigned char c = *p;
if ( std::islower( c ) )
{
*p = std::toupper( c );
}
else if ( std::isupper( c ) )
{
*p = std::tolower( c );
}
}
return str;
}
|
71,564,234 | 71,564,806 | How can I make this work and is there a way to optimize this? | I wanted to do a calculator with c++, and I did not wish my calculator to do only 2 number calculations, so I "made" 2 operator calculator. Also, I want to learn if there is a way to make this without two switch statements to make it easier for machines and programmers to read.
#include <iostream>
int top1 ;
int main()
{
char operatr1, operatr2;
float num1, num2, num3, num4 ;
std::cout << "Please choose the first operator ( +, -, *, /):";
std::cin >> operatr1 ;
std::cout << "Please choose the second operator ( +, -, *, /):";
std::cin >> operatr2;
std::cout << "Please enter three numbers: " << std::endl;
std::cin >> num1 >> num2 >> num3;
switch (operatr1) {
case '+':
int top1{ num1 + num2 };
break;
case '-':
int top1{ num1 - num2 };
break;
case '*':
int top1{ num1 * num2 };
break;
case '/':
int top1{ num1 / num2 };
break;
default:
std::cout << "Error! The operator is not correct" << std::endl << "The operators are ( +, -, *, / ).";
break;
}
switch (operatr2) {
case '+':
int top2{ top1 + num3 };
std::cout << "The answer is:" << " " << top2;
break;
case '-':
int top2{ top1 - num3 };
std::cout << "The answer is:" << " " << top2;
break;
case '*':
int top2{ top1 * num3 };
std::cout << "The answer is:" << " " << top2;
break;
case '/':
int top2{ top1 / num3 };
std::cout << "The answer is:" << " " << top2;
break;
default:
std::cout << "Error! The operator is not correct" << std::endl << "The operators are ( +, -, *, / ).";
break;
}
}
| You could make use of a function:
int Evaluate(const char operator,
const int num1,
const int num2)
{
bool is_valid_operator = true;
int result = 0;
switch (operator)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '/':
// Note: integer division.
result = num1 / num2;
break;
case '*':
result = num1 * num2;
break;
default:
result = 0;
is_valid_operator = false;
break;
}
if (is_valid_operator)
{
std::cout << "Result of " << num1 << " " << operator << " " << num2 << "\n";
std::cout << result << "\n";
}
return result;
}
Your main would be simplified to:
//...
int top1 = Evaluate(operatr1, num1, num2);
int top2 = Evaluate(operatr2, top1, num3);
|
71,564,476 | 71,564,911 | How to iterate over a range-v3 action? | I'm new to range-v3. I started by write a program that generates a range of integers, modifies it, and prints out the resulting range. I used a modifier from the actions library, which rendered my code non-iterable.
Could someone help me understand how to convert a ranges::action::action_closure into an iterable?
Here's the example I started with - a function that generates and prints out a range of numbers. This code works fine and compiles.
void generate_and_print_numbers_using_streams_and_iterators() {
auto v = views::iota(1, 5); // <-- this code works fine with streams and iterators.
// this works
cout << v << endl;
//this works too
for (auto s: v) {
cout << s << ", ";
}
cout << endl;
// and this works too
for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it << ", ";
}
cout << endl;
}
Then I tried introducing the action I mentioned. This code no longer compiles - v is no longer a view, but an action_closure which does not define begin() and end() functions.
void generate_and_print_numbers_using_streams_and_iterators() {
// I REPLACED THIS:
// auto v = views::iota(1, 5);
// WITH THIS:
auto v = action::push_back(views::iota(1, 5)) | actions::unique; // Wrapped iota in push_back
// .. the remainder of the function is unchanged
I tried searching through the documentation of ranges-v3, as well as googling this conversion. The only thing I found was the following article that shows how to convert a view to a concrete container (a vector).
I will appreciate any help on this topic.
| Actions do not return a light-weight ephemeral object that can be lazily iterated over like view operations do. Actions are applied eagerly to actual containers and return actual containers, but still can be composed together.
In the following std::vector<int>() is an r-value that gets filled via push_back which returns an r-value that is then passed to the reverse action. All of this processing happens eagerly, akin to normal nested function calls but using the pipeline syntax:
void do_something_with_a_push_back_action() {
std::vector<int> vec = std::vector<int>() |
ranges::actions::push_back(ranges::views::iota(1, 5)) |
ranges::actions::reverse;
for (int val : vec) {
std::cout << val << "\n";
}
}
|
71,564,678 | 71,564,794 | OpenGL how to create a sphere from half-sphere in c++ | So, from a material I have, I managed to somehow complete it to half-sphere, the original destination. But now I have to make a sphere from the said half-sphere and I'm lost. I haven't met an answer online that has a fourth parameter (raze). Can someone tell me what I'm missing?
The code:
void drawSphere(double r, int lats, int longs, double raze) {
double alpha = acos((r - raze)/r);
bool ind = true;
int i, j;
for(i = 0; i <= lats; i++) {
double lat0 = M_PI * (-0.5 + (double) (i - 1) / lats);
double z0 = sin(lat0);
double zr0 = cos(lat0);
double lat1 = M_PI * (-0.5 + (double) i / lats);
double z1 = sin(lat1);
double zr1 = cos(lat1);
if (lat0>alpha && lat1>alpha){
if (ind){
ind = false;
double z0 = sin(alpha);
double zr0 = cos(alpha);
double lat1 = M_PI * (-0.5 + (double) (i-1) / lats);
double z1 = sin(lat1);
double zr1 = cos(lat1);
glBegin(GL_QUAD_STRIP);
for(j = 0; j <= longs; j++) {
double lng = 2 * M_PI * (double) (j - 1) / longs;
double x = cos(lng);
double y = sin(lng);
glColor3f(1, 0, 0);
//glNormal3f(x * zr0, y * zr0, z0);
glVertex3f(r * x * zr0, r * y * zr0, r * z0);
//glNormal3f(x * zr1, y * zr1, z1);
glVertex3f(r * x * zr1, r * y * zr1, r * z1);
}
glEnd();
}
glBegin(GL_QUAD_STRIP);
for(j = 0; j <= longs; j++) {
double lng = 2 * M_PI * (double) (j - 1) / longs;
double x = cos(lng);
double y = sin(lng);
glColor3f(1, 0, 0);
//glNormal3f(x * zr0, y * zr0, z0);
glVertex3f(r * x * zr0, r * y * zr0, r * z0);
//glNormal3f(x * zr1, y * zr1, z1);
glVertex3f(r * x * zr1, r * y * zr1, r * z1);
}
glEnd();};
}
}
| For a full sphere raze must be equal r. However, the condition if (lat0>alpha && lat1>alpha) is wrong. It has to be:
if (lat0 >= -alpha && lat1 <= alpha)
Note that for a full sphere you need to draw slices from -M_PI/2 to M_PI/2. That means if (lat0 >= -M_PI/2 && lat1 < -M_PI/2).
|
71,565,613 | 71,565,773 | Passing message in std::exception from managed code to unmanaged | I am trying to throw a std::exception from managed code so that it is caught in unmanaged code. Where I'm struggling is passing a string (describing the exception) so that the (re-)caught exception can be examined using the what() method ...
#pragma managed
static std::string InvokeMethod() {
try {
//...
}
catch (Exception^ ex) {
std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->ToString());
throw std::exception(myExMsg);
}
}
#pragma unmanaged
void Execute() {
try {
myMethod = InvokeMethod();
}
catch (std::exception ex) {
SetError(ex.what());
}
}
This doesn't compile with "no instance of constructor "stdext:exceptipon::exception" matches the argument list argument types are (std::string)" BUT if I 'hard code' a string into std::exception like this ...
throw std::exception("An error has occurred");
... then that string gets passed along and returned by ex.what(). I also tried ...
throw std::runtime_error(myExMsg);
... but ex.what() just returns a string ending with '\x7F' (in case that's a clue).
It looks to me that std::exception is expecting some other type. But what type? What does 'myExMsg' need to be so that ex.what() returns the same string (that can be used in the SetError method)?
| Following suggestion made by @Joe, I inherit from std::exception ...
class InvokeException : public std::exception {
public:
InvokeException(std::string const& message) : msg_(message) { }
virtual char const* what() const noexcept { return msg_.c_str(); }
private:
std::string msg_;
};
... and then ...
const std::string myExMsg = msclr::interop::marshal_as<std::string>(ex->Message);
throw InvokeException(myExMsg);
|
71,565,682 | 71,565,805 | Returning a rapidjson::GenericValue from a function | I want to make a function that returns a constructed rapidjson::Value from it. Like this:
using JsonValue = rapidjson::GenericValue< rapidjson::UTF16LE<> >;
JsonValue MakeInt(int val)
{
return JsonValue().SetInt(val); //copy-by-reference is forbidden
//return JsonValue().SetInt(val).Move(); //same, Move() returns a reference
//return std::move(JsonValue().SetInt(val)); //gcc complains about RVO failure
//JsonValue json_val;
//json_val.SetInt(val);
//return json_val; //copy constructor is forbidden
}
However, each attempt fails due to various reasons listed in comments.
Obviously I could pass a destination value by reference:
void WriteInt(JsonValue &dst_val, int val)
{
dst_val.SetInt(val);
}
But I want to find how I'm expected to make it a return value.
PS I noticed there are a couple similarly spirited questions like this one RapidJSON: Return GenericValue from Function but none of them are answered.
UPDATE:
The actual solution is supposed to be just returning a value like this on any compiler that supports c++11:
JsonValue MakeInt(int val)
{
JsonValue json_val;
json_val.SetInt(val);
return json_val;
}
But this code failed to compile for us on clang build. Turns out the reason for that is not the compiler difference, but because the move constructor inside rapidjson.h is declared like this:
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
//! Move constructor in C++11
GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) {
rhs.data_.f.flags = kNullFlag; // give up contents
}
#endif
and as it turns out the macro RAPIDJSON_HAS_CXX11_RVALUE_REFS was set to 0 due to its declaration in rapidjson.h:
#if __has_feature(cxx_rvalue_references) && \
(defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306)
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
#else
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0
#endif
which is in turn because neither _LIBCPP_VERSION nor GLIBCXX are declared in our configuration. This is our build system bug on clang that somehow ended up not having its compiler macros defined.
| What compiler and C++ version are you using?
This compiles OK in MS Visual Studio 2019:
using JsonValue = rapidjson::GenericValue< rapidjson::UTF16LE<> >;
JsonValue MakeInt(int val)
{
JsonValue json_val;
json_val.SetInt(val);
return json_val;
}
I compile with C++11. Please see this (from document.h)
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
//! Move constructor in C++11
GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) {
rhs.data_.f.flags = kNullFlag; // give up contents
}
#endif
|
71,566,083 | 71,566,111 | C++) why const int*& parameter can't take int* argument? | before writing, I'm not good at english. So maybe there are many awkward sentence.
void Func1(const int* _i) { };
void Func2(const int& _j) { };
void Func3(const int* (&_k)) { };
int main()
{
int iNum = 1;
int* pInt = new int(1);
Func1(pInt); // works;
Func2(iNum); //works
Func3(pInt); // error
}
I use Visual Studio and error message said
"Cannot convert argument 1 from 'int *' to 'const int *&'"
I know it cant convert because of '&'. _i equals pInt so it may change dereference.
But i used const. so i think it will work but const keyword doesnt work.
why const keyword doesnt work unlike other cases? ex)Func1,Func2
| Func1(pInt); // works; int* could convert to const int* implicitly
Func2(iNum); //works; int could be bound to const int&
Func3(pInt); // error;
pInt is a int*, when being passed to Func3 which expects a reference to const int*, then it would be converted to const int*, which is a temporary and can't be bound to lvalue-reference to non-const like const int* & (lvalue-reference to non-const pointer to const int).
If you change the parameter type of Func3 to int* &, then no conversion is required, pInt could be bound directly. Or change to const int* const & (lvalue-reference to const pointer to const int) or const int* && (rvalue-reference) which could bind to temporary.
|
71,566,232 | 71,566,322 | How to split a string and record each split as a distinct variable C++ | I was looking at a popular StackOverflow post about how to split strings. I have found this very useful, but I'd like to take each split and store it in array or a distinct string variable. Such that I can access: scott, tiger, mushroom, or fail. Below is my attempt to do this, but I cannot complile this due to an error:
cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'char' in assignment
Does anyone know an efficient way of doing this?
#include <bits/stdc++.h>
using namespace std;
#include <stdio.h>
#include <string.h>
char str[10];
void setup(){
std::string s = "scott>=tiger>=mushroom>=fail";
std::string delimiter = ">=";
int arrayIndex = 0;
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
str[arrayIndex++] = token;
}
std::cout << s << std::endl;
}
void loop(){
}
| str[] is an array of individual chars, but you are trying to store std::string objects in it, hence the error. Change the array to hold std::string instead of char. And then consider using std::vector instead of a fixed array.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> str;
void setup(){
std::string s = "scott>=tiger>=mushroom>=fail";
std::string delimiter = ">=";
size_t start = 0, pos;
std::string token;
while ((pos = s.find(delimiter, start)) != std::string::npos) {
token = s.substr(start, pos-start);
str.push_back(token);
start = pos + delimiter.size();
}
if (start < s.size())
str.push_back(s.substr(start));
for(auto &elem : str)
std::cout << elem << std::endl;
}
Online Demo
|
71,568,141 | 71,568,180 | Fastest way to insert a character at the beginning of the string in C++? | So while solving problems on Leetcode I came across this problem. To generate a string normally, I could just use str.push_back('a'). But if I want to generate the string backwards I would use this same method and reverse the string at the end. Using str.insert() resulted in Time Limit Exceeded and str='a'+str; would as expected result in Memory Limit Exceeded. Wanted to know if there was an easy way to insert a character at the beginning of the string in C++
| You already answered your own question by saying reversing. Just use += operator to append and then reverse.
As another way, first push elements into a stack then pop them to fill string.
If it is still slow, then divide the output into small segments and pipeline the reversing + appending parts to hide latency using multiple threads. While one thread is reversing a segment, another thread can create another segment. Then you join all threads and join their output segments to make single array of chars to be converted to string. If each segment is size of L1 cache, then the reversing should be fast.
If you can't use threads, then you can still do the reversing inside sse/avx registers, they have shuffle commands that can help you use the instruction level parallelism to hide the latency, unless they are slower than L1 access.
|
71,568,155 | 71,568,178 | What is the syntax to require a template variable to be void? | Is there a way to write a requires requires expression to apprehend that a template parameter is void?
I believe it is legal to make the value of std::is_void_v<ParmThree> a parameter of the template. However, I cannot formulate a syntax to check this in a requirement - for being either true or false.
Is it possible? How would it be done?
| requires requires works because the nested (second) requires returns a bool.
Since you already have a bool, you can just do requires std::is_void_v<T>:
template <typename T>
requires std::is_void_v<T>
struct A {};
|
71,568,361 | 71,570,945 | Boost Asio Serial port How to find out the size of the buffer in the queue for reading C++ | In Arduino data can be read as follows:
void setup() {
Serial.begin(9600);
}
String Comand = "";
void loop() {
if (Serial.available() > 0) //If there is data read
{
char c = Serial.read(); //get byte
if(c!='\n')
{
Comand+=c;
}
else
{
if(Comand == "MyComand")
{
Serial.println("Comand 1");
}
//else
//...
Comand = "";
}
}
}
С++ boost asio
Here is an example of c ++ playback of data from the port, but what function to check if there is anything to read?
#include <boost/asio.hpp>
#include <windows.h>
//....
int main(int, char**)
{
{
boost::asio::io_service io;
boost::asio::serial_port serial(io,"COM5");
serial.set_option(boost::asio::serial_port_base::baud_rate(9600));
std::string s = "MyComand\n";
boost::asio::write(serial,boost::asio::buffer(s.c_str(),s.size()));
std::string result;
//while serial data > 0 ??? How to check
{
using namespace boost;
char c;
asio::read(serial,asio::buffer(&c,1));
result+=c;
}
std::cout<<result.c_str();
}
return 0;
}
If I read in a cycle, and there is no data, the program will stop and wait for the data, it does not suit me. How to check if there is data before trying to read.
| The idea of asynchronous IO is that you donot check whether data is available. Instead, you defer the completion of the read until that is the case.
Now, you're using Asio to still do synchronous IO. And your requirement is:
If I read in a cycle, and there is no data, the program will stop and wait for the data, it does not suit me.
Synchronous IO implies blocking reads. You can make it return whatever is available:
while (auto n = serial.read_some(asio::buffer(buf))) {
result.append(buf.data(), n);
std::cout << "Received " << n
<< " bytes, total length: " << result.length() << "\n";
}
But read_some is still blocking:
This function is used to read data from the serial port. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.
So, the only real alternative for serial ports is to use the async interface:
std::string result;
std::array<char, 32> buf;
std::function<void(error_code, size_t)> read_loop;
read_loop = [&](error_code ec, size_t n) {
if (ec.failed())
return;
std::cout << "Received " << n
<< " bytes, total length: " << result.length() << "\n";
result.append(buf.data(), n);
serial.async_read_some(asio::buffer(buf), read_loop);
};
read_loop(error_code{}, 0);
Now you have a new "problem": how to integrate your application logic into this. The fact that you're printing the request suggests to me that you're not receiving an unbounded stream of binary data.
Instead, consider simplifying for your application logic to read just what you need, perhaps with a timeout. See e.g. asio_read_some countinue reading to get all data
|
71,568,830 | 71,569,572 | How to print following pattern in C++ :1st row->10101010...;2nd row->11001100..;3rd row ->11100011 etc | How to print following pattern in C++ :1st row->10101010...;2nd row->11001100..;3rd row ->11100011 and so on.
Number of alternate 0 and 1s depends on the row number.
Pattern should look like:
1010101010
1100110011
1110001110
Code:
#include<iostream>
using namespace std;
int main()
{
int row,col,cond;
cout <<"Enter the number of rows: ";
cin >> row;
cout <<"Enter the number of cols: ";
cin >> col;
int a[row][col]={0};
for(int i=0; i<row; i++)
{
for(int j=0;j<col;j++)
{
cond = (((j+1)/(i+1))+i+1);
// cout << "i=" << i <<"j="<<j<<"cond="<<cond <<endl;
if( (j <= i) )
{
a[i][j]=1;
if(cond+j<col)
{
a[i][cond+j]=1;
}
}
else if (a[i][j] !=1)
{
a[i][j]=0;
}
}
}
for(int i=0; i<row; i++)
{
for(int j=0;j<col;j++)
{
cout << a[i][j];
}
cout<<endl;
}
return 0;
}
Ouput:
Enter the number of rows: 4
Enter the number of cols: 9
101000000
111010000
111110100
111111101
| You are overcomplicating this - you don't need any arrays or tricky indexing.
Print one row at a time, starting with 1.
Switch back and forth between 0 and 1 at the appropriate columns.
for (int r = 1; r <= row; r++)
{
int symbol = 1;
for (int c = 1; c <= col; c++)
{
std::cout << symbol;
if (c % r == 0)
{
symbol = 1 - symbol;
}
}
std::cout << std::endl;
}
|
71,569,611 | 71,569,895 | Does popen load whole output into memory or save in a tmp file(in disk)? | I want to read part of a very very large compressed file(119.2 GiB if decompressed) with this piece of code.
FILE* trace_file;
char gunzip_command[1000];
sprintf(gunzip_command, "gunzip -c %s", argv[i]); // argv[i]: file path
trace_file = popen(gunzip_command, "r");
fread(¤t_cloudsuite_instr, instr_size, 1, trace_file)
Does popen in c load whole output of the command into memory? If it does not, does popen save the the whole output of the command in a tmp file(in disk)? As you can see, the output of decompressing will be too large. Neither memory nor disk can hold it.
I only know that popen creates a pipe.
$ xz -l 649.fotonik3d_s-1B.champsimtrace.xz
Strms Blocks Compressed Uncompressed Ratio Check Filename
1 1 24.1 MiB 119.2 GiB 0.000 CRC64 649.fotonik3d_s-1B.champsimtrace.xz
|
I only know that popen creates a pipe.
There are two implementations of pipes that I know:
On MS-DOS, the whole output was written to disk; reading was then done by reading the file.
It might be that there are still (less-known) modern operating systems that work this way.
However, in most cases, a certain amount of memory is reserved for the pipe.
The xz command can write data until that amount of memory is full. If the memory is full, xz is stopped until memory becomes available (because the program that called popen() reads data).
If the program that called popen() reads data from the pipe, data is removed from the memory so xz can write more data.
When the program that called popen() closes the file handle, writing to the pipe has no more effect; an error message is reported to xz ...
|
71,570,764 | 71,571,344 | Slow compilation speed for "const unordered_map" as global variable | I am experiencing really slow compilation time, probably due to the existence of a global variable of the kind std::unordered_map. Below you can find the lines of code, which are located in a file called correspondance.h
using Entry_t = std::tuple<Cfptr_t, short int, short int>;
...
#include "map_content.h"
inline const std::unordered_map<std::string, Entry_t> squaredampl{MAP_CONTENT};
#undef MAP_CONTENT
and, in map_content.h there is the content of the map:
#define MAP_CONTENT \
{ {EMPTYCHAR+corr::su_R,ANTICHAR,EMPTYCHAR+corr::sd_L,EMPTYCHAR+corr::A,EMPTYCHAR+corr::W},{ &mssm2to2::sumSqAmpl_su_R_anti_sd_L_to_A_W, 9,2}},\
{ {EMPTYCHAR+corr::su_L,ANTICHAR,EMPTYCHAR+corr::sd_R,EMPTYCHAR+corr::A,EMPTYCHAR+corr::W},{ &mssm2to2::sumSqAmpl_su_L_anti_sd_R_to_A_W, 9,2}},\
...
it goes on like this for about 3500 lines.
Note that
Cfptr_t is a function pointer
EMPTYCHAR and all the variables of the type corr::something are integers, so they define the key value string
The problem I encounter is that the makefile takes 10 minutes for each file that includes correspondace.h, since indeed there are so many lines of code to process.
As you may have understood, this map is needed to allow the user to access functions without knowing their names, but just with a string. For this reason I cannot at the moment eliminate this feature, since it's fundamental.
As far as I could do, I tried to include this file in as few files as possible. Anyways, it is inevitable to include it in every file that will generate the executable, so, overall, this forces me to wait a long time each time I have to debug something.
If you have any suggestion on how to speed up compilation keeping this feature, it would be really helpful for me :)
| Change
#include "map_content.h"
inline const std::unordered_map<std::string, Entry_t> squaredampl{MAP_CONTENT};
#undef MAP_CONTENT
to
extern const std::unordered_map<std::string, Entry_t> squaredampl;
and in a new .cpp file:
#include "correspondance.h"
#include "map_content.h"
const std::unordered_map<std::string, Entry_t> squaredampl{MAP_CONTENT};
#undef MAP_CONTENT
This will cause only one definition of the map to be emitted (in contrast to inline which will emit it in every translation unit odr-using it).
It is safe as long as the map isn't used during the construction of another static storage duration object before main is entered. If that is required, it would be preferable to make the map a local static variable in a function returning it by-reference to be used by callers. This would avoid the "static initialization order fiasco".
It might also help to make a function to initialize the map with an insert statement for each entry instead of doing it all in the initializer, i.e. have a function initSquaredampl returning a std::unordered_map<std::string, Entry_t> by-value and then:
auto initSquaredampl() {
std::unordered_map<std::string, Entry_t> squaredampl;
// Insert items one-by-one
return squaredampl;
}
const std::unordered_map<std::string, Entry_t> squaredampl = initSquaredampl();
This may help, because a compiler might not be optimized for compilation of very long expressions or initializers. However, they may also have trouble with very long functions.
|
71,571,034 | 71,572,183 | How to get an instance of class in const expressions (decltype, templates ...) | How to get an instance of a class?
Everyone would answer: call its constructor
like
class_name()
Then what if the class has no default constructor?
I have a function accepting a byte buffer as argument:
template<typename BUFFER>
void fun(BUFFER& buf) {
I need to have some restrains on BUFFER, and I choose the newest ranges
template<std::ranges::range BUFFER>
void fun(BUFFER& buf) {
And this is a byte buffer, so the return type of std::ranges::begin(buf) should be byte
Then I added some requirments
template<std::ranges::range BUFFER>
requires std::same_as<byte, decltype(*std::ranges::begin(BUFFER()))>
void fun(BUFFER& buf) {
This is no good because we don't know whether BUFFER has a default constructor
So, is there any solution better than the following code?
template<typename T>
struct instanceof_t {
T value;
};
template<typename T>
using instanceof = instanceof_t<T>::value;
template<std::ranges::range BUFFER>
requires std::same_as<byte, decltype(std::ranges::begin(instanceof<BUFFER>))>
void fun(BUFFER& buf) {
| There is already range_value_t which is used to obtain the value type of the iterator type of range type R, so in your case it should be
#include <ranges>
template<std::ranges::range BUFFER>
requires std::same_as<std::byte, std::ranges::range_value_t<BUFFER>>
void fun(BUFFER& buf);
|
71,571,315 | 71,571,342 | Using "typedef" or "using" to define a structure - which is best? | Sample structure:
typedef struct tagExportSettings
{
COLORREF crHeading{};
COLORREF crEvenBack{};
COLORREF crOddBack{};
COLORREF crHighlight{};
COLORREF crDate{};
COLORREF crEvent{};
COLORREF crEmpty{};
COLORREF crNotes{};
} EXPORT_SETTINGS_S;
Visual Assist says:
typedef can be converted to using declaration.
Is there any real benefit of making this code change?
All my code in the software uses EXPORT_SETTINGS_S so I don't want to break that syntax.
| Even better is to use neither. One type name should be enough. Pick either tagExportSettings or EXPORT_SETTINGS_S and stick with it. Example:
struct tagExportSettings
{
// ...
};
But, 1. All my code in the software uses EXPORT_SETTINGS_S
As I said, pick either name. If you use EXPORT_SETTINGS_S, then name the class as EXPORT_SETTINGS_S:
struct EXPORT_SETTINGS_S
{
// ...
};
If something still refers to tagExportSettings, then refactor the code to use the canonical name.
But more generally, using is preferred to typedef because it's more readable. There are at least two reasons for it:
With typedef syntax it isn't intuitive which is the old name and which is the new alias:
typedef new_or_old old_or_new; // old_or_new is the new alias
using is intuitive through familiar pattern of initialisation:
using intuitively_alias = intuitively_old_name;
typedef syntax is difficult for a programmer to parse in case of compound names because the alias is "interleaved":
// alias for void()
typedef void function();
using function = void();
|
71,571,363 | 71,571,418 | What happens when we return with a Sum in C++? | int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
It's a C++ code
I don't understand, when you return in the 3rd like (return k + sum(k-1);
aren't we returning
10 + 9 together?
Not like 10+9+8+7+6+5+4+3+2+1=55 (Original Output)
shouldn't this be the output?
by this I mean like the return is something like 10+9 then again 9+8 again 8+7
So the output might be like
10+9+9+8+8+7+7+6+6+5+5+4+4+3+3+2+2+1+1+0+0? (ac to me the sum would be like this)
The output would be one hundred?
I know I am wrong but please clear this for me.
| This summation function is using recursion (basically when a function contains a callback of itself inside).
When you call sum(10), the value you will get is 10 + sum(9), not just 10 + 9. Then sum(9) == 9 + sum(8) and so on until sum(10) == 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0) which will break the recursion and will just return a constant 0, and the function will finally return 55.
There won't be any repeating results as sum(k - 1) does not contain k in its sum.
|
71,572,011 | 71,595,536 | How to update a progress Bar in QML by calculating the countdown on the C++ side in the QTWidget? | I basically want to send the progress from the c++ side to update the value of the ProgressBar on the QML size.
I am trying to integrate QML into a widget application. The thing is I have my mainwindwo.cpp file like this:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QQmlContext *context = ui->quickWidget->rootContext();
QString title = "Progress Bar App";
int progress = 0;
context->setContextProperty("_myString",title); //Set Text in QML that says Hello World
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(myFunction()));
timer->start(1000);
progress = myFunction();
context->setContextProperty("_myProgress", progress);
if(progress == 100.0){
timer->stop();
}
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
ui->quickWidget->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
int MainWindow::myFunction(){
//Calculate progress
static uint16_t total_time = 50000;
static uint16_t progress = 0;
static uint16_t i = 0;
// for(double i=0; i<=total_time; i=i+1000){
// progress = ((i)*100)/total_time;
// qDebug()<<"Progress: "<<progress<<endl;
// }
if(i < total_time){
i = i + 1000;
progress = ((i)*100)/total_time;
qDebug()<<"Progress: "<<progress<<endl;
}else{
qDebug()<<"Finished: "<<progress<<endl;
}
return progress;
}
I want to send the progress to calculated here to the ProgressBar in QML side but I can't seem to get it to work.
My question is if you typically create a C++ class with a header and cpp files, how do you do the samething but instead use things in a QTWidget or the Mainwindow.cpp file and send data continuously from it to the QML file to update a ProgressBar?
| You have to create a class that inherits from QObject and is a bridge between C++ and QML:
#ifndef PROGRESSBRIDGE_H
#define PROGRESSBRIDGE_H
#include <QObject>
class ProgressBridge : public QObject
{
Q_OBJECT
Q_PROPERTY(int progress READ progress WRITE setProgress NOTIFY progressChanged)
public:
explicit ProgressBridge(QObject *parent = nullptr)
: QObject{parent}, m_progress{0}
{}
int progress() const{
return m_progress;
}
void setProgress(int newProgress){
if (m_progress == newProgress)
return;
m_progress = newProgress;
emit progressChanged();
}
signals:
void progressChanged();
private:
int m_progress;
};
#endif // PROGRESSBRIDGE_H
mainwindow.h
ProgressBridge progress_bridge;
mainwindow.cpp
context->setContextProperty("progressBridge", &progress_bridge);
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
int MainWindow::myFunction(){
// TODO
progress_bridge.setProgress(progress);
}
And in QML you do use Connections
ProgressBar{
id: progressbar
from: 0.0
to: 100.0
}
Connections{
target: progressBridge
function onProgressChanged(){
progressbar.value = progressBridge.progress
}
}
|
71,572,186 | 71,575,543 | Question on converting boost shared pointer to standard shared pointer | This is more of a follow up question on the second answer posted here. The code from this answer is shown below:
template<typename T>
void do_release(typename boost::shared_ptr<T> const&, T*)
{
}
template<typename T>
typename std::shared_ptr<T> to_std(typename boost::shared_ptr<T> const& p)
{
return
std::shared_ptr<T>(
p.get(),
boost::bind(&do_release<T>, p, _1));
}
My understanding on above code is, a functor is created from do_release binded with the boost shared_ptr we are trying to convert and is passed in as a custom deleter.
My current thought is (likely wrong): the new standard shared_ptr doesnt hold any existing ref count held by boost shared_ptr but only one ref count for itself after this "conversion". When the standard shared_ptr destructor gets called, it would call the custom deleter which would then trigger the destructor on the boost shared_ptr? So the ref count and life time of the heap resource is still effectively maintained by the boost shared_ptr. What I mean is if the ref count on the boost shared_ptr > 0 (after de-ref by 1) when the custom deleter is called, it would still not destroy the heap memory.
But what if the standard shared_ptr gets copied? Would this conversion still work? I think it would because when the standard share_ptr is copied, it would then increase the ref count, but its the ref count maintained by the standard shared_ptr, so that the overall ref count on the heap resource is still correct. But now the ref count is maintained by both standard + boost shared_ptr?
Am I correct?
| The shared pointer created has a destroy function object (deleter) that has state. In particular it has a copy of the boost shared ptr.
The destruction action does nothing, it is the destruction of deleter that cleans up the boost shared ptr.
There is a problem though:
Does the C++ standard fully specify cleanup of the deleter itself? E.g. it might stay around when only weak references remain?
The standard does guarantee a minimum lifetime for the deleter, leaving the possibility that lives longer than that.
Destroying the destruction object is not specified to occur in either the constructor of std::shared_ptr nor the destructor of std::shared_ptr. It would be reasonable to destroy it either after it is called, or when the reference counting block is destroyed - in the second case, we end up with it lasting until the last weak ptr goes away.
From the draft standard:
[Note: It is unspecified whether the pointer remains valid longer than that. This can happen if the implementation doesn’t destroy the deleter until all weak_ptr instances that share ownership with p have been destroyed. — end note]
The possibility to defer destruction of the deleter is clear. So in that case we end up with shared_ptrs that doesn't destruct their element instance when we want it to be called depending on unspecified details of the C++ implementation you run it on. That is a bad idea.
Better Alternative
I would personally go with a similar trick based on the aliasing constructor instead. It is just as simple, has no additional overhead, and the semantics are actually correct:
template<class T>
std::shared_ptr<T>
as_std_shared_ptr(boost::shared_ptr<T> bp)
{
if (!bp) return nullptr;
// a std shared pointer to boost shared ptr. Yes.
auto pq = std::make_shared<boost::shared_ptr<T>>(std::move(bp));
// aliasing ctor. Hide the double shared ptr. Sneaky.
return std::shared_ptr<T>(pq, pq.get()->get());
}
This is much less of a hack than the code from the question, because lifetime
of the boost shared ptr is no longer tied to the (unspecified) lifetime of the deleter instance.
|
71,572,605 | 71,572,769 | Why same values inside string even after swapping the underlying integer? | I have a 64 bit unsigned integer and for some reason I have to store it inside a string. What I am wondering is that the value inside the string is same even after using the swapped integer?
For example:
#include <iostream>
#include <byteswap.h>
using namespace std;
int main()
{
uint64_t foo = 98;
uint64_t foo_reversed = bswap_64(foo);
std::string out = "";
out.append(reinterpret_cast<const char*>(&foo), sizeof(foo));
std::string out_reversed = "";
out_reversed.append(reinterpret_cast<const char*>(&foo_reversed), sizeof(foo_reversed));
std::cout << "out: " << out << std::endl;
std::cout << "out_reversed: " << out_reversed << std::endl;
return 0;
}
The string out and out_reversed have the exact same value, but I expect it to be different as the underlying integer foo and foo_reversed are swapped value of each other.
What am I missing here? Pardon me if it is a trivial mistake, but putting it out here on the chance that I'm missing some concept.
The output I see:
out: b
out_reversed: b
I was not expecting the above value for out_reversed
| You can see the same thing with arrays of char:
int main()
{
char foo[8] = { 98, 0, 0, 0, 0, 0, 0, 0 };
char foo_reversed[8] = { 0, 0, 0, 0, 0, 0, 0, 98 };
std::string out(foo, 8);
std::string out_reversed(foo_reversed, 8);
std::cout << "out: " << out << std::endl;
std::cout << "out_reversed: " << out_reversed << std::endl;
return 0;
}
The chars with value 0 aren't printable, so the terminal doesn't display them
Here's an alternative printing.
|
71,572,995 | 71,573,866 | What is the correct way to initialise pointers to structs in C++? | I am trying to learn the best practices while improving my C++ skills and I've got a question.
If I have, for example this, struct:
struct Vector {
int x;
int y;
};
typedef struct {
Vector position;
Vector velocity;
} Ball;
Which one would be the correct way to initialise it?
Ball* _ball1 = new Ball();
Ball* _ball2 = new Ball;
I know it would be better to create a class in this case, but I am trying to use all kinds of structures etc.
Also, regarding the struct definition - instead of typedef struct {} Ball;, would it be better just: struct Ball{}; ?
Any insight would be much appreciated.
Thanks!
Edit: Thank you everyone for the answers!
| First, you can do this:
Ball ball;
You now have a local Ball object. It will last until the enclosing code is closed. That is:
cout << "Foo\n";
if (true) {
Ball ball;
}
cout << "Bar\n";
The ball exists only inside those {}. If you try to use it outside (where the cout of Bar is found), it won't be there. So in many cases, your variables will be alive for the scope of a function call.
void foo() {
Ball ball;
...
}
This is the easiest thing to do, and it probably works for most of your use cases. You probably don't need to worry about pointers for your first pieces of code.
However, if there's a reason you want to really use pointers, you can do this:
void foo() {
Ball * ball = new Ball;
... make use of it
delete ball;
}
If you don't do the delete, you have a memory leak. Unlike Java, C++ doesn't have any sort of garbage collector. You're on your own.
But you can also do this:
void foo() {
std::shared_ptr<Ball> ball = std::make_shared<Ball>();
... use it
... no delete required
}
These are referred to as smart pointers, and the trend in C++ is to use either unique_ptr or shared_ptr instead of raw pointers. (Raw pointers are what I did in the previous example.) These work more like C++ objects, where when you lose all the pointers, it knows and deletes the memory for you. This is referred to as RAII (Resource Acquisition Is Initialization), and you're strongly, strongly encouraged to learn it.
|
71,573,073 | 71,583,397 | Cygwin 3.3.4 random end of program | I'm looking for tips to find a direction where I have to investigate.
I have a little c++ project that works well both on my old cygwin (3.0.4(0.338/5/3)) and on a debian distrib (thanks to Posix)
In this project I use some libraries like log4cplus (cxxTest, rapidJson, ...)
Now I had to upgrade my cygwin. So I install a new version of cygwin (3.3.4(0.341/5/3)) totally separated from the previous one. With this new cygwin, I have 2 problems:
The real problem : my program sometimes (2 of 10 times) work well without problem. And very often the program did nothing and end without any information
The second problem is that gdb (GNU gdb (GDB) (Cygwin 10.2-1) 10.2) : won't debug my program. Each time I try I have :
gdb: unknown target exception 0x80000001 at 0x7ffc741dd147
Thread 9 received signal ?, Unknown signal.
In order to find the problem I make a very simple code to reproduce the problem. And finally it was very simple, I do this :
#include <iostream>
#include <log4cplus/initializer.h>
#include <log4cplus/configurator.h>
using namespace std;
/// ***************************************************************************
/// Initialisation of log4cplus library
/// ***************************************************************************
void log4cplusInit() {
try {
log4cplus::initialize();
//log4cplus::PropertyConfigurator::doConfigure("config/log4cplus.ini");
}
catch(std::exception& e)
{
cout << e.what() << endl;
}
catch(...) {
cout << "Unexpected exception" << std::endl;
}
}
int main() {
//log4cplusInit();
cout << "Hello World " << endl;
}
Things that I already find/try :
If I comment the line log4cplus::initialize(); The program works.
The 2 Lines log4cplus::XXXX have the same impact : if one of this line is present, I have the bug, If both are commented then everything is fine
The try catch never catch anything
I try to catch every signal, for gdb problem, before finding this trhead : cygwin gdb Program received signal ?, Unknown signal (but didn't help me)
I don't understand why an unused code could have this impact (log4cplusInit() is commented and never called)
So I'm looking for an idea where I can start. I want to investigate this bug, but I have no clue.
PS: I already have open an issue in log4cplus github. Don't know if I have to open one in cygwin
Any help will be appreciated :)
| For every people who read this thread in future :
I don't really find a solution in Cygwin, but like @Alan Birtles mention : Use WSL (or another updated solution).
It work like a charm. thanks to microsoft ;)
|
71,573,199 | 71,573,351 | The deduction guide for std::array | In the C++ 17 and C++ 20 Working Drafts of the C++ Standard the deduction guide for the class template std::array is defined the following way
template<class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;
As a result for example this declaration
std::array a = { 1ll, 2llu };
should be compiled and the deduced type of the variable a is std::array<long long, 2>.
However compilers use another deduction guide that checks that all initializers have the same type.
Is it a bug of compilers or was the deduction guide indeed changed in C++ 17 and C++20 Standards?
| C++17 has that requirement in the deduction guide.
template<class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;
Requires: (is_same_v<T, U> && ...) is true. Otherwise the program is ill-formed.
[array.cons#2]
|
71,573,741 | 71,573,807 | How to install a Chrome extension with C/C++? | I have to install a Chrome extension using C/C++.
I tried to copy the whole folder of a extension in C:\Users[login_name]\AppData\Local\Google\Chrome\User Data\Default\Extensions. After copying it I deleted the extension from Chrome and then pasted the extension folder back to its own place but it doesn't get installed. How can I install a Chrome extension without using the Chrome browser? I want to install the extension using C/C++.
| Google Chrome supports the following alternative extension installation methods:
Using a preferences JSON file (for macOS X and Linux only)
Using the Windows registry (for Windows only)
source:
https://developer.chrome.com/docs/extensions/mv3/external_extensions/
|
71,574,407 | 71,575,059 | Problem parsing date/time with timezone name using Howard Hinnant's library | I'm writing a method to parse date/time strings in a variety of formats.
std::chrono::system_clock::time_point toTimePoint(const std::string str) {
... a bunch of code that determines the format of the input string
std::string formatStr = string{"%Y-%m-%d"}
+ " " // Delimeter between date and time.
+ "%H:%M:%S"
+ "%t%Z"
;
// The %t should be 0 or 1 whitespace
// The %Z should be a timezone name
std::chrono::system_clock::time_point retVal;
std::istringstream in{str};
in >> date::parse(formatStr, retVal);
return retVal;
}
I then test it with a variety of inputs. The other formats work. I can do these:
2022-04-01 12:17:00.1234
2022-04-01 12:17:00.1234-0600
2022-04-01 12:17:00.1234-06:00
The latter two are for US Mountain Daylight Time. It does all the right things. The first one shows as 12:17:00 UST. The other two are 18:17:00 UST. Working great. I've omitted all that code for brevity. What does not work is this:
2022-04-01 12:17:00.1234 US/Central
I've tried a variety of timezone names after writing a different program to dump the ones known by Howard's library. None of them matter. I get a UST-time value with no time zone offset.
Luckily, what I need right now is the -06:00 format, so I can move forward. But I'd like to fix the code, as we have other places that use timezone names, and I'd like to get this working properly.
I'm not sure what I'm doing wrong.
| When reading an offset with %z (e.g. -0600), combined with a sys_time type such as system_clock::time_point, the parse time point is interpreted as a local time, and the offset is applied to get the sys_time, as desired in your first two examples.
However this is not the case when reading a time zone name or abbreviation with %Z (note the change from lower case z to upper case Z).
%Z parses a time zone abbreviation or name, which is just a string. The common case is for this to just parse an abbreviation, e.g. CST. And in general, there is no unique mapping from an abbreviation to an offset. And so the offset can not be internally applied. Thus the parsed value should always be interpreted as a local time.
However all is not lost. You can parse the time zone name with %Z into a string, and then look up the time_zone with that name and use it to convert the parse local_time into a sys_time. This could look like:
#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
istringstream in{"2022-04-01 12:17:00.1234 US/Central"};
string tz_name;
local_time<microseconds> local_tp;
in >> parse("%F %T%t%Z", local_tp, tz_name);
system_clock::time_point tp = locate_zone(tz_name)->to_sys(local_tp);
cout << tp << '\n';
}
Just add a string as the third argument in your parse call, and make sure the first argument is a local_time instead of a sys_time. Then use locate_zone to get a time_zone const* and call to_sys with that, passing in the parsed local_time.
The above program outputs:
2022-04-01 17:17:00.123400
This is an hour off from the -6h offset because US/Central goes to daylight saving on 2022-03-13 (-5h offset).
|
71,574,663 | 71,574,954 | CPython extension using omp freezes Qt UI | I am working on a scientific algorithm (image processing), which is written in C++, and uses lots of parallelization, handled by OpenMP. I need it to be callable from Python, so I created a CPython package, which handles the wrapping of the algorithm.
Now I need some UI, as user interaction is essential for initializing some stuff. My problem is that the UI freezes when I run the algorithm. I start the algorithm in a separate thread, so this shouldn't be a problem (I even proved it by replacing the function call with time.sleep, and it works fine, not causing any freeze). For testing I reduced the UI to two buttons: one for starting the algorithm, and another just to print some random string to console (to check UI interactions).
I also experienced something really weird. If I started moving the mouse, then pressed the button to start the computation, and after that kept moving the mouse continuously, the UI did not freeze, so hovering over the buttons gave them the usual blueish Windows-style tint. But if I stopped moving my mouse for a several seconds over the application window, clicked a button, or swapped to another window, the UI froze again. It's even more strange that the UI stayed active if I rested my mouse outside of the application window.Here's my code (unfortunately I cannot share the algorithm for several reasons, but I hope I manage to get some help even like this):
if __name__ == "__main__":
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QThread, QObject, pyqtSignal
import time
from CustomAlgorithm import Estimator # my custom Python package implemented in C++
class Worker(QObject):
finished = pyqtSignal()
def run(self):
estimator = Estimator()
estimator.calculate()
# if the above two lines are commented, and the next line is uncommented,
# everything's fine
# time.sleep(5)
print("done")
app = QApplication([])
thread = QThread()
window = QWidget()
layout = QVBoxLayout()
# button to start the calculation
btn = QPushButton("start")
layout.addWidget(btn)
btn.clicked.connect(thread.start)
# button to print some text to console
btn2 = QPushButton("other button")
layout.addWidget(btn2)
btn2.clicked.connect(lambda: print("other button clicked"))
window.setLayout(layout)
# handling events
worker = Worker(app)
worker.moveToThread(thread)
thread.started.connect(worker.run)
worker.finished.connect(thread.quit)
worker.finished.connect(worker.deleteLater)
thread.finished.connect(thread.deleteLater)
window.show()
app.exec_()
I tried multiple variants of using threads, like threading.Thread, multiprocessing.Process, PyQt5.QtCore.QThread (as seen above), even napari's worker implementation, but the result was the same. I even tried removing omp from the code, just in case it interferes somehow with python threads, but it didn't help.
As for the reason I use python, is that the final goal is to make my implementation available in napari.
Any help would be highly appreciated!
| Because of Python's "Global Interpreter Lock", only one thread can run Python code at a time. However, other threads can do I/O at the same time.
If you want to allow other threads to run (just like I/O does) you can surround your code with these macros:
Py_BEGIN_ALLOW_THREADS
// computation goes here
Py_END_ALLOW_THREADS
Other Python threads will be allowed to run while the computation is happening. You can't access anything from Python between these two lines - so get that data in order before Py_BEGIN_ALLOW_THREADS.
Reference
|
71,574,914 | 71,575,147 | Do I have to overload functions for every different parameter? | I want to create a function to simplify a list/vector. I can do it in python:
i = [1, 2, 3, 4, 5]
f = [1.1, 2.2, 3.3, 4.4, 5.5]
s = ["one", "two", "three", "four", "five"]
def simplify(lst):
if len(lst) == 0:
return 0
tmp = lst[0]
for x in range(1, len(lst)):
tmp += lst[x]
print(tmp)
return tmp
simplify(i)
simplify(f)
simplify(s)
but for c++ I would have to write the same function for many variable types (long long, double, int, string, char).
My question is, can I do in c++ like I did in python? (creating a single function for multiple types)
|
My question is, can I do in c++ like I did in python? (creating a single function for multiple types)
Almost. A C++ function template is not a function, but using one can look indistinguishable from it.
You will also struggle with your choice of -1 as the result if the sequence is empty, as -1 is not a string.
template <typename Range>
std::ranges::range_value_t<Range> simplify(Range && range) {
auto it = std::ranges::begin(range);
if (it == std::ranges::end(range)) return -1; // this will fail for strings
auto result = *it++;
for (; it != std::ranges::end(range); ++it) {
result += *it;
}
std::cout << result; // I assume this is for testing the function?
return result;
}
If you make a different choice about what to do with an empty input, there is a function very similar to yours in the standard library:
template <typename Range>
std::ranges::range_value_t<Range> simplify(Range && range) {
std::ranges::range_value_t<Range> zero {}; // 0 for numbers, empty string for strings, etc.
return std::accumulate(std::ranges::begin(range), std::ranges::end(range), zero);
}
int main() {
std::vector<int> i {1, 2, 3, 4, 5};
std::vector<double> f {1.1, 2.2, 3.3, 4.4, 5.5};
std::vector<std::string> s {"one", "two", "three", "four", "five"};
std::cout << simplify(i);
std::cout << simplify(f);
std::cout << simplify(s);
}
See it on coliru
|
71,575,173 | 71,660,184 | Building GStreamer with CMake causes SDP & WebRTC unresolved external symbol errors | I'm building a C++ GStreamer project with CMake which depends on GStreamer, GLIB, Libsoup and json-glib. I'm new to CMake and having trouble setting up my project. I've managed to include many of the dependencies but some seem to remain unresolved even though they are part of GStreamer. All GStreamer methods and types are resolved with the exception of SDP and WebRTC. They are, to my understanding, part of GStreamer and are also located inside of the directory which GMake correctly "finds".
These are the errors that are occurring when trying to build the project.
[build] error LNK2019: unresolved external symbol __imp_gst_sdp_message_new referenced in function "void __cdecl soup_websocket_message_cb(struct _SoupWebsocketConnection *,enum SoupWebsocketDataType,struct _GBytes *,void *)" (?soup_websocket_message_cb@@YAXPEAU_SoupWebsocketConnection@@W4SoupWebsocketDataType@@PEAU_GBytes@@PEAX@Z)
[build] error LNK2019: unresolved external symbol __imp_gst_sdp_message_parse_buffer referenced in function "void __cdecl soup_websocket_message_cb(struct _SoupWebsocketConnection *,enum SoupWebsocketDataType,struct _GBytes *,void *)" (?soup_websocket_message_cb@@YAXPEAU_SoupWebsocketConnection@@W4SoupWebsocketDataType@@PEAU_GBytes@@PEAX@Z)
[build] error LNK2019: unresolved external symbol __imp_gst_sdp_message_as_text referenced in function "void __cdecl on_offer_created_cb(struct _GstPromise *,void *)" (?on_offer_created_cb@@YAXPEAU_GstPromise@@PEAX@Z)
[build] error LNK2019: unresolved external symbol __imp_gst_webrtc_session_description_get_type referenced in function "void __cdecl on_offer_created_cb(struct _GstPromise *,void *)" (?on_offer_created_cb@@YAXPEAU_GstPromise@@PEAX@Z)
[build] error LNK2019: unresolved external symbol __imp_gst_webrtc_session_description_new referenced in function "void __cdecl soup_websocket_message_cb(struct _SoupWebsocketConnection *,enum SoupWebsocketDataType,struct _GBytes *,void *)" (?soup_websocket_message_cb@@YAXPEAU_SoupWebsocketConnection@@W4SoupWebsocketDataType@@PEAU_GBytes@@PEAX@Z)
[build] error LNK2019: unresolved external symbol __imp_gst_webrtc_session_description_free referenced in function "void __cdecl on_offer_created_cb(struct _GstPromise *,void *)" (?on_offer_created_cb@@YAXPEAU_GstPromise@@PEAX@Z)
This is my CMakeLists.txt
# CMakeList.txt : CMake project for stream-project, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)
project (stream-project LANGUAGES CXX)
# Packages
find_package(PkgConfig REQUIRED)
# Add source to this project's executable.
add_executable (${PROJECT_NAME} "main.cpp" "main.h")
# Search all modules that we so desire to use and "include_directories"
pkg_search_module(GST REQUIRED gstreamer-1.0 gstreamer-sdp-1.0 gstreamer-video-1.0 gstreamer-app-1.0 gstreamer-webrtc-1.0)
pkg_search_module(GLIB REQUIRED glib-2.0)
pkg_search_module(LIBSOUP REQUIRED libsoup-2.4)
pkg_search_module(JSONGLIB REQUIRED json-glib-1.0)
include_directories(
${GST_INCLUDE_DIRS}
${GLIB_INCLUDE_DIRS}
${LIBSOUP_INCLUDE_DIRS}
${JSONGLIB_INCLUDE_DIRS}
)
# Link target directories and libraries
target_link_directories(${PROJECT_NAME} PRIVATE
${GST_LIBRARY_DIRS}
${GLIB_LIBRARY_DIRS}
${LIBSOUP_LIBRARY_DIRS}
${JSONGLIB_LIBRARY_DIRS}
)
target_link_libraries(${PROJECT_NAME} PRIVATE
${GST_LIBRARIES}
${GLIB_LIBRARIES}
${LIBSOUP_LIBRARIES}
${JSONGLIB_LIBRARIES}
)
message(STATUS ${GST_INCLUDE_DIRS})
| I've managed to solve it by using a premade find script I found online.
https://chromium.googlesource.com/external/Webkit/+/master/Source/cmake/FindGStreamer.cmake
It creates all necessary defines which I then include and link.
These are the defaults as specified in the FindGStreamer.cmake file
FIND_GSTREAMER_COMPONENT(GSTREAMER_APP gstreamer-app-1.0 gst/app/gstappsink.h gstapp-1.0)
FIND_GSTREAMER_COMPONENT(GSTREAMER_AUDIO gstreamer-audio-1.0 gst/audio/audio.h gstaudio-1.0)
FIND_GSTREAMER_COMPONENT(GSTREAMER_FFT gstreamer-fft-1.0 gst/fft/gstfft.h gstfft-1.0)
FIND_GSTREAMER_COMPONENT(GSTREAMER_PBUTILS gstreamer-pbutils-1.0 gst/pbutils/pbutils.h gstpbutils-1.0)
FIND_GSTREAMER_COMPONENT(GSTREAMER_VIDEO gstreamer-video-1.0 gst/video/video.h gstvideo-1.0)
I extended those above with:
FIND_GSTREAMER_COMPONENT(GSTREAMER_SDP gstreamer-sdp-1.0 gst/sdp/sdp.h gstsdp-1.0)
FIND_GSTREAMER_COMPONENT(GSTREAMER_WEBRTC gstreamer-webrtc-1.0 gst/webrtc/webrtc.h gstwebrtc-1.0)
|
71,575,246 | 71,576,145 | Is it possible to create "parent" class' method that accepts "child" class object as a parameter? | What I'm trying to do is something like this:
class Parent{
.....
....
public:
Child* func();
};
Child* Parent::func()
{
Child C[] = {.....,....,...};
return C;
}
class Child : Parent{....};
Excuse my total disregard for <array here.
| You can forward-declare Child before using it in the declaration of func(). This only works for pointers and references. You would then need to fully define what Child looks like before you can make Child instances in the definition of func(), and then you can return Child* pointers as needed.
Note that returning a pointer to a local variable will lead to undefined behavior, since the variable gets destroyed when the function exits, leaving the returned pointer dangling, pointing to now-invalid memory. You should instead return a std::vector of Child* pointers, eg:
#include <vector>
class Child;
class Parent{
...
public:
std::vector<Child*> func();
};
class Child : public Parent{ ... };
std::vector<Child*> Parent::func()
{
std::vector<Child*> C;
C.push_back(new Child(...));
C.push_back(new Child(...));
C.push_back(new Child(...));
return C;
}
Parent p;
std::vector<Child*> vec = p.func();
// use vec as needed...
for(size_t i = 0; i < vec.size(); ++i) {
delete vec[i]; // destroy each Child when done using it
}
Or better, use smart pointers instead, let the compiler handle the cleanup for you:
#include <vector>
class Child;
class Parent{
...
public:
std::vector<std::unique_ptr<Child>> func();
};
class Child : public Parent{ ... };
std::vector<std::unique_ptr<Child>> Parent::func()
{
std::vector<std::unique_ptr<Child>> C;
C.push_back(std::make_unique<Child>(...));
C.push_back(std::make_unique<Child>(...));
C.push_back(std::make_unique<Child>(...));
return C;
}
Parent p;
auto vec = p.func();
// use vec as needed...
Online Demo
|
71,575,691 | 71,575,756 | std::vector does not release memory in a thread | If I create a thread with _beginthreadex, and in the thread I used std::vector<WCHAR> that consumes 200MB of memory - when the thread ends, the memory is not released. Even after CloseHandle, the memory is not released.
Here is a working example:
#include <windows.h>
#include <process.h>
#include <vector>
using namespace std;
unsigned __stdcall Thread_RestartComputer(void* pComputerName)
{
std::vector<WCHAR> asdf(100000000);
_endthreadex(0);
return 0;
}
int main()
{
UINT threadID = 0;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_RestartComputer, 0, CREATE_SUSPENDED, &threadID);
ResumeThread(hThread);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
I thought that std::vector<WCHAR> released the memory when it went out of scope?
| C++ doesn't know that calling _endthreadex makes the thread go away. So it doesn't call the destructors of local variables like asdf before it calls _endthreadex.
Solution: Don't do that. return 0; ends the thread and calls the destructor.
|
71,576,273 | 71,576,466 | Fast byte copy C++11 | I need to convert C# app which uses extensively bytes manipulation.
An example:
public abstract class BinRecord
{
public static int version => 1;
public virtual int LENGTH => 1 + 7 + 8 + 2 + 1; // 19
public char type;
public ulong timestamp; // 7 byte
public double p;
public ushort size;
public char callbackType;
public virtual void FillBytes(byte[] bytes)
{
bytes[0] = (byte)type;
var t = BitConverter.GetBytes(timestamp);
Buffer.BlockCopy(t, 0, bytes, 1, 7);
Buffer.BlockCopy(BitConverter.GetBytes(p), 0, bytes, 8, 8);
Buffer.BlockCopy(BitConverter.GetBytes(size), 0, bytes, 16, 2);
bytes[18] = (byte)callbackType;
}
}
Basically BitConverter and Buffer.BlockCopy called 100s times per sec.
There are several classes that inherit from the base class above doing more specific tasks. For example:
public class SpecRecord : BinRecord
{
public override int LENGTH => base.LENGTH + 2;
public ushort num;
public SpecRecord() { }
public SpecRecord(ushort num)
{
this.num = num;
}
public override void FillBytes(byte[] bytes)
{
var idx = base.LENGTH;
base.FillBytes(bytes);
Buffer.BlockCopy(BitConverter.GetBytes(num), 0, bytes, idx + 0, 2);
}
}
What approach in C++ should I look into?
| Best option, in my opinion, is to actually go to C - use memcpy to copy over the bytes of any object.
Your above code would then be re-written as follows:
void FillBytes(uint8_t* bytes)
{
bytes[0] = (uint8_t)type;
memcpy((bytes + 1), &t, sizeof(uint64_t) - 1);
memcpy((bytes + 8), &p, sizeof(double));
memcpy((bytes + 16), &size, sizeof(uint16_t));
bytes[18] = (uint8_t)callbackType;
}
Here, I use uint8_t, uint16_t, and uint64_t as replacements for the byte, ushort, and ulong types.
Keep in mind, your timestamp copy is not portable to a big-endian CPU - it will cut off the lowest byte rather than the highest. Solving that would require copying in each byte manually, like so:
//Copy a 7 byte timestamp into the buffer.
bytes[1] = (t >> 0) & 0xFF;
bytes[2] = (t >> 8) & 0xFF;
bytes[3] = (t >> 16) & 0xFF;
bytes[4] = (t >> 24) & 0xFF;
bytes[5] = (t >> 32) & 0xFF;
bytes[6] = (t >> 40) & 0xFF;
bytes[7] = (t >> 48) & 0xFF;
|
71,576,623 | 71,579,381 | Constexpr expand constructor parameter pack into member array (C++11) | I want to expand a pack of variadic parameters into a struct member in C++11. My approach is the following:
template <typename... Ts>
struct cxpr_struct
{
constexpr cxpr_struct(Ts... Args) : t_(Args...) {}
std::array<int, sizeof...(Ts)> t_;
};
int main()
{
cxpr_struct(10, 20, 30);
}
However, this yields the following error:
<source>:208:16: error: missing template arguments before '(' token
208 | cxpr_struct(10, 20, 30);
|
I know that my code has flaws. E.g. the type of array is not determined from Ts (how can I do that?). But how would I do this the proper way? Is template argument deduction really not possible for the compiler?
EDIT: I have to use C++11
| due to c++11, you have to use something like that:
template <typename... Ts>
struct cxpr_struct
{
constexpr cxpr_struct(Ts... args) : t_{args...} {}
std::array<int, sizeof...(Ts)> t_;
};
template<typename... Ts>
cxpr_struct<Ts...> build(Ts...args){
return cxpr_struct<Ts...>(args...);
}
int main()
{
auto obj = build(10, 20, 30);
}
or better:
template <unsigned Size>
struct cxpr_struct
{
template<typename... Ts>
constexpr cxpr_struct(Ts... args) : t_{args...} {}
std::array<int, Size> t_;
};
template<typename... Ts>
cxpr_struct<sizeof...(Ts)> build(Ts...args){
return cxpr_struct<sizeof...(Ts)>(args...);
}
int main()
{
auto obj = build(10, 20, 30);
}
|
71,576,948 | 71,577,334 | How cppwinrt.exe tool know which C++ version to use to generate the headers from .winmd files? | I don't see any switch to specify the "C++ version" in the cppwinrt.exe tool !
(my fundamental assumption is cppwinrt.exe tool binds the C++ 17 syntax to the ABI, I can't figure out how it can bind C++ 20 or future newer versions syntax )
Similarly, the cswinrt.exe tool from C#/WinRT projection generates .cs files from .winmd files. The same question applies , How does the cswinrt.exe tool know which "C# version" to use to generate the .cs files ?
I don't see any switch to specify the "C# version" in the cswinrt.exe tool either !
end goal : is to understand how "language versions" fit in the WinRT language projections
| The cppwinrt.exe tool doesn't allow you to specify a C++ language standard. It simply defaults to C++17, with the ability to opt-in to newer language features by way of feature test macros.
The result is that the generated header files can be compiled with any C++17 compiler, or a compiler that supports a later language version.
At this time (C++/WinRT version 2.0.210922.5) there are four C++20 features in use:
C++20 coroutines, guarded by an #ifdef __cpp_lib_coroutine directive (though that is really just deciding on whether to include the coroutine header file from the experimental/ directory or not; coroutines have been supported since VS 2015).
C++20 modules. This isn't guarded as clients need to explicitly opt-in to using winrt.ixx through an import declaration.
Support for C++20 ranges (introduced in 2.0.210329.4). This is an interesting one in that none of the code changes require a C++20 compiler. The feature simply lights up for clients using a C++20 compiler when they use the <ranges> standard library header.
C++20 std::format (introduced in 2.0.210922.5), guarded by an #ifdef __cpp_lib_format directive.
At a fundamental level, C++/WinRT is just a C++ library. As such it can employ any technique that's suitable to providing language-adaptive implementations.
I don't know how C#/WinRT operates internally, nor C# for that matter, so I cannot comment on that.
|
71,577,055 | 71,578,034 | How can I add a path to a Makefile? | In C++, I have a library path I know how include when building with a CMakeLists.txt file but I don't know how to include it when building with a Makefile.
I tried applying the solution asked and answered here but it didn't work. The contents of the Makefile is below. The library's name is "NumCpp". The full path to this library on my computer is C:\Users\ooo\tor\Robot\rainbow\NumCpp\include\.
In the .cc file I am including the library as #include "NumCpp.hpp"
This is the CMakeLists.txt file. This would include and compile the NumCpp library if you ran this in the directory containing NumCpp. I don't know if it is helpful to show this, but I know I can include the library this way.
cmake_minimum_required(VERSION 3.14)
project("HelloWorld" CXX)
add_executable(${PROJECT_NAME} main.cpp)
find_package(NumCpp 2.6.2 REQUIRED)
target_link_libraries(${PROJECT_NAME}
NumCpp::NumCpp
)
The Makefile. I tried using INC_DIR, CFLAGS, and DEPS to link the path to the library but I'm getting an error.
COMMON=/O2 /MT /EHsc /arch:AVX /I../include /Fe../bin/
cl_vars = 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\Hostx86\x86\cl.exe'
cl_var = 'cl'
INC_DIR = C:/Users/ooo/tor/Robot/rainbow/NumCpp/include/
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = NumCpp.hpp
all:
$(cl_var) $(COMMON) testxml.cc ../bin/mujoco210nogl.lib
$(cl_var) $(COMMON) testspeed.cc ../bin/mujoco210nogl.lib
$(cl_var) $(COMMON) compile.cc ../bin/mujoco210nogl.lib
$(cl_var) $(COMMON) derivative.cc /openmp ../bin/mujoco210nogl.lib
$(cl_var) $(COMMON) basic.cc ../bin/glfw3.lib ../bin/mujoco210.lib
$(cl_var) $(COMMON) record.cc ../bin/glfw3.lib ../bin/mujoco210.lib
$(cl_var) $(COMMON) simulate.cc ../include/uitools.c ../bin/glfw3.lib ../bin/mujoco210.lib
del *.obj
The error...
simulate.cc(14): fatal error C1083: Cannot open include file: 'NumCpp.hpp': No such file or directory
Generating Code...
Compiling...
uitools.c
Generating Code...
make: *** [Makefile:16: all] Error 2
| This line assigns a value to a makefile variable named COMMON:
COMMON=/O2 /MT /EHsc /arch:AVX /I../include /Fe../bin/
this line assigns a value to a makefile variable name cl_var:
cl_var = 'cl'
These lines in the recipe use (or "expand") the variables cl_var and COMMON:
$(cl_var) $(COMMON) testxml.cc ../bin/mujoco210nogl.lib
(etc.)
Note that nowhere in your makefile do you ever use the variables cl_vars, CFLAGS, INC_DIR, or DEPS, so those variable assignments are basically no-ops: useless. They might as well not be there at all, they have no effect on your makefile.
If you want to add a new directory to the include path, then you have to add it to the COMMON variable, because that's the variable that will be used. Since you're using Visual C++, not a POSIX compiler like GCC or Clang, the syntax is /I<path>, not -I<path>.
So, you should try something like this:
INC_DIR = C:/Users/ooo/tor/Robot/rainbow/NumCpp/include/
COMMON = /O2 /MT /EHsc /arch:AVX /I../include /I$(INC_DIR) /Fe../bin/
If you need more orientation, you probably need to read at least the introduction to something like the GNU make user's manual to get yourself a basic understanding of what a makefile is and how it works. SO is not equipped to provide full-fledged tutorials.
|
71,577,371 | 74,487,602 | Will ObjC setter automatically copy a C++ object passed as a parameter when get called? | I recently read about a std::unique_ptr as a @property in objective c and the suggestion to store a unique_ptr in ObjC as a property is as following:
-(void) setPtr:(std::unique_ptr<MyClass>)ptr {
_ptr = std::move(ptr);
}
My question is in ObjC, does the parameter get copied in this case? Because if that happens, unique_ptr shall never be declared as a property right?
|
My question is in ObjC, does the parameter get copied in this case?
That depends. Let me introduce a custom class where all copy operations are removed to better demonstrate possible outcomes under different circumstances:
struct MyClass {
MyClass() {
std::cout << "Default constructor" << std::endl;
}
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;
MyClass(MyClass&&) {
std::cout << "Move Constructor" << std::endl;
}
MyClass& operator=(MyClass&&) {
std::cout << "Move Assignment" << std::endl;
return *this;
}
};
And change the parameter signature of your method accordingly:
- (void)setInst:(MyClass)inst {
_inst = std::move(inst);
}
Initialise the parameter with a temporary
Assuming the method in the sample belongs to a class named TDWObject the following code will compile just fine:
[[TDWObject new] setInst:MyClass{}];
Under C++17, you will find the default constructor and the move assignment called:
Default constructor
Move Assignment
The default constructor is called for the temporary, and thanks to guaranteed copy elision, neither copy nor move constructor is needed to initialise the parameter inst of the method with the temporary. The move assignemnt is straightforward - it happen when assigning result of std::move(inst) operation. If you use C++11 or C++14, standard doesn't guarantee copy elision, but clang will do it anyway. Some compilers use move-semantic instead, but overall for a temporary this code should work just fine.
Initialise the parameter with a moved named variable
Another option is to cast any named variable to an rvalue, and it will still allow to initialise the parameter without any issues:
MyClass inst;
[[TDWObject new] setInst:std::move(inst)];
The difference in this case, is that the function parameter will actually call the move constructor without elision optimisation:
Default constructor
Move Constructor
Move Assignment
Initialise the parameter with a named variable
And here is the broken scenario:
TDW::MyClass inst;
[self setInst:inst];
This will not work of course, because the parameter needs to call the copy constructor, which is marked deleted. The good thing about it, this code will never compile, and you will spot the problem straight away.
Considering alternatives
First of all I don't really think that Objective-C properties are compatible with non-copyable C++ classes and decided to give my own answer to the question linked, which you can review here.
|
71,577,835 | 71,577,897 | Should I qualify pointer parameters with volatile if they may be changed during the execution of a function? | Say I have the function
int foo(int * const bar){
while(!*bar){
printf("qwertyuiop\n");
}
}
where I intend to change the value at bar to something other than 0 to stop this loop. Would it be appropriate to instead write it as below?
int foo(int volatile * const bar){
while(!*bar){
printf("qwertyuiop\n");
}
}
| volatile was intended for things like memory-mapped device registers, where the pointed-to value could "magically" change "behind the compiler's back" due to the nature of the hardware involved. Assuming you're not writing code that deals with special hardware that might "spontaneously" change the value that bar points to, then you needn't (and shouldn't) use the volatile keyword. Simply omitting the const keyword is sufficient to let the compiler (and any programmer that might call the function) know that the pointed-to value is subject to change.
Note that if you are intending to set *bar from another thread, then the volatile keyword isn't good enough; even if you tag the pointer volatile, the compiler still won't guarantee correct handling. For that use-case to work correctly, you need to either synchronize all reads and writes to *bar with a mutex, or alternatively use a std::atomic<int> instead of a plain int.
|
71,578,589 | 71,579,169 | C++ vector push_back async object in for loop | I was coding a for loop in C++11, where I needed to push back an async object onto a vector. I wanted to split the object initialization into two steps:
std::vector<std::future<bool>> asyncThreads;
for (int i = 0; i < processorCount; i++) {
auto boundFunc = std::bind(&Foo::foo, this);
auto asyncThread = std::async(std::launch::async, boundFunc)
asyncThreads.push_back(asyncThread);
}
Now I do realize that both boundFunc and asyncThread objects go out of scope at the end of the for loop (the push_back function should copy/move the values though), but then why does directly declaring the objects in the push_back call work? Like so:
std::vector<std::future<bool>> asyncThreads;
for (int i = 0; i < processorCount; i++) {
asyncThreads.push_back(std::async(std::launch::async, std::bind(&Foo::foo, this)));
}
| A std::future object is not copyable, but moveable. So therefore, you must call move on the object to push it onto the vector.
|
71,578,607 | 71,580,760 | zlib error -3 while decompressing archive: Incorrect data check | I am writing a C++ library that also decompresses zlib files. For all of the files, the last call to gzread() (or at least one of the last calls) gives error -3 (Z_DATA_ERROR) with message "incorrect data check". As I have not created the files myself I am not entirely sure what is wrong.
I found this answer and if I do
gzip -dc < myfile.gz > myfile.decomp
gzip: invalid compressed data--crc error
on the command line the contents of myfile.decomp seems to be correct. There is still the crc error printed in this case, however, which may or may not be the same problem. My code, pasted below, should be straightforward, but I am not sure how to get the same behavior in code as on the command line above.
How can I achieve the same behavior in code as on the command line?
std::vector<char> decompress(const std::string &path)
{
gzFile inFileZ = gzopen(path.c_str(), "rb");
if (inFileZ == NULL)
{
printf("Error: gzopen() failed for file %s.\n", path.c_str());
return {};
}
constexpr size_t bufSize = 8192;
char unzipBuffer[bufSize];
int unzippedBytes = bufSize;
std::vector<char> unzippedData;
unzippedData.reserve(1048576); // 1 MiB is enough in most cases.
while (unzippedBytes == bufSize)
{
unzippedBytes = gzread(inFileZ, unzipBuffer, bufSize);
if (unzippedBytes == -1)
{
// Here the error is -3 / "incorrect data check" for (one of) the last block(s)
// in the file. The bytes can be correctly decompressed, as demonstrated on the
// command line, but how can this be achieved in code?
int errnum;
const char *err = gzerror(inFileZ, &errnum);
printf(err, "%s\n");
break;
}
if (unzippedBytes > 0)
{
unzippedData.insert(unzippedData.end(), unzipBuffer, unzipBuffer + unzippedBytes);
}
}
gzclose(inFileZ);
return unzippedData;
}
| First off, the whole point of the CRC is to detect corrupted data. If the CRC is bad, then you should be going back to where this file came from and getting the data not corrupted. If the CRC is bad, discard the input and report an error.
You are not clear on the "behavior" you are trying to reproduce, but if you're trying to recover as much data as possible from a corrupted gzip file, then you will need to use zlib's inflate functions to decompress the file. int ret = inflateInit2(&strm, 31); will initialize the zlib stream to process a gzip file.
|
71,578,686 | 71,578,723 | Why does "for(std::size_t i=2; i >= 0; --i)" fail | I was surprised when this for loop failed to run properly:
for (std::size_t i=2; i >= 0; --i)
I figured, okay, probably the final check is if -1 >= 0, and since i is not allowed to be negative, we have a problem. Presumably i is looping around to (264 - 1).
However, this for loop does execute:
for (std::size_t i=2; i+1 > 0; --i)
Ignoring std::size_t for a moment; this doesn't make sense to me from a logical perspective. Both (i+1 > 0) and (i >= 0) will be either true or false for the exact same values of i.
Both will be true if i = {0, 1, 2, ...} and false if i = {-1, -2, -3, ...}.
What is going on here?
Is it something to do with the implementation of std::size_t, or the compiler, or am I just missing something very obvious?
|
What is going on here?
std::size_t is an unsigned integer type.
i >= 0
All unsigned integers are greater than or equal to 0. There exists no value for which this relation would be false and hence the loop cannot end.
i+1 > 0
An unsigned integer can be 0. Hence this relation can be false and the loop can end. Example:
std::size_t i = 0;
i -= 1;
assert(i+1 == 0);
The value of i that ends the loop is congruent with -1 modulo M, where M is the number of representable values which is 2b where b is the width of the integer type in bits. That number is the greatest representable value i.e. 2b-1.
Your deduction works with whole numbers, but it doesn't work with modular arithmetic.
This is to some degree a matter of taste, but I recommend following code to loop over numbers (n..0]. It works correctly with both signed and unsigned types:
for (std::size_t i=n; i-- > 0;)
|
71,578,699 | 74,013,278 | setGeometry obstructed by setText | I created a Qt Widget in Qt Creator which consists of a QSlider and a QProgressBar whose length I want to adjust to the position of the slider like this:
To do so, I use setGeometry(). In order to maintain the length relative to the window width, I call my resizeProgressBar() in my overridden resizeEvent(). The slider's value is also shown in the label below the progress bar. However, the setText() call in on_horizontalSlider_valueChanged() seems to interfere with the setGeometry(), as only when I resize the window, the progress bar assumes the desired length, but each time I move the slider, the progress bar reverts to spanning the full width of the window. It does not matter whether the setText() comes before or after the setGeometry().
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeProgressBar()
{
ui->progressBar->setGeometry(ui->progressBar->x(), ui->progressBar->y(),
ui->horizontalSlider->width()
* ui->horizontalSlider->value()
/ ui->horizontalSlider->maximum(),
ui->progressBar->height());
}
void MainWindow::on_horizontalSlider_valueChanged(int value)
{
ui->label->setText(QString::number(ui->horizontalSlider->value()));
resizeProgressBar();
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
resizeProgressBar();
ui->label->setText(QString::number(ui->horizontalSlider->value()));
QWidget::resizeEvent(event);
}
| Since the originally intended way did not work, I've now solved the problem by using a horizontal layout containing the QProgressBar as well as a horizontal Spacer on the right of the bar. The stretch factors are set to 1 and 0, respectively. Now, when I move the slider, I change the stretch factors accordingly, so the progress bar is aligned with the slider's value.
void MainWindow::on_horizontalSlider_valueChanged(int value)
{
ui->horizontalLayout->setStretch(0, value);
ui->horizontalLayout->setStretch(1, ui->horizontalSlider->maximum() - value);
}
|
71,578,740 | 71,586,797 | constexpr result from non-constexpr call | Recently I was surprised that the following code compiles in clang, gcc and msvc too (at least with their current versions).
struct A {
static const int value = 42;
};
constexpr int f(A a) { return a.value; }
void g() {
A a; // Intentionally non-constexpr.
constexpr int kInt = f(a);
}
My understanding was that the call to f is not constexpr because the argument i isn't, but it seems I am wrong. Is this a proper standard-supported code or some kind of compiler extension?
| As mentioned in the comments, the rules for constant expressions do not generally require that every variable mentioned in the expression and whose lifetime began outside the expression evaluation is constexpr.
There is a (long) list of requirements that when not satisfied prevent an expression from being a constant expression. As long as none of them is violated, the expression is a constant expression.
The requirement that a used variable/object be constexpr is formally known as the object being usable in constant expressions (although the exact definition contains more detailed requirements and exceptions, see also linked cppreference page).
Looking at the list you can see that this property is required only in certain situations, namely only for variables/objects whose lifetime began outside the expression and if either a virtual function call is performed on it, a lvalue-to-rvalue conversion is performed on it or it is a reference variable named in the expression.
Neither of these cases apply here. There are no virtual functions involved and a is not a reference variable. Typically the lvalue-to-rvalue conversion causes the requirement to become important. An lvalue-to-rvalue conversions happens whenever you try to use the value stored in the object or one of its subobjects. However A is an empty class without any state and therefore there is no value to read. When passing a to the function, the implicit copy constructor is called to construct the parameter of f, but because the class is empty, it doesn't actually do anything. It doesn't access any state of a.
Note that, as mentioned above, the rules are stricter if you use references, e.g.
A a;
A& ar = a;
constexpr int kInt = f(ar);
will fail, because ar names a reference variable which is not usable in constant expressions. This will hopefully be fixed soon to be more consistent. (see https://github.com/cplusplus/papers/issues/973)
|
71,578,748 | 71,579,204 | Printing an std::array gives random values | I am trying to print out an std::array as seen below, the output is supposed to consist of only booleans, but there seem to be numbers in the output aswell (also below). I've tried printing out the elements which give numbers on their own, but then I get their actual value, which is weird.
My main function:
float f(float x, float y)
{
return x * x + y * y - 1;
}
int main()
{
std::array<std::array<bool, ARRAY_SIZE_X>, ARRAY_SIZE_Y> temp = ConvertToBinaryImage(&f);
for(int i = 0; i < (int)temp.size(); ++i)
{
for(int j = 0; j < (int)temp[0].size(); ++j)
{
std::cout << temp[i][j] << " ";
}
std::cout << std::endl;
}
}
The function that sets the array:
std::array<std::array<bool, ARRAY_SIZE_X>, ARRAY_SIZE_Y> ConvertToBinaryImage(float(*func)(float, float))
{
std::array<std::array<bool, ARRAY_SIZE_X>, ARRAY_SIZE_Y> result;
for(float x = X_MIN; x <= X_MAX; x += STEP_SIZE)
{
for(float y = Y_MIN; y <= Y_MAX; y += STEP_SIZE)
{
int indx = ARRAY_SIZE_X - (x - X_MIN) * STEP_SIZE_INV;
int indy = ARRAY_SIZE_Y - (y - Y_MIN) * STEP_SIZE_INV;
result[indx][indy] = func(x, y) < 0;
}
}
return result;
}
The constants
#define X_MIN -1
#define Y_MIN -1
#define X_MAX 1
#define Y_MAX 1
#define STEP_SIZE_INV 10
#define STEP_SIZE (float)1 / STEP_SIZE_INV
#define ARRAY_SIZE_X (X_MAX - X_MIN) * STEP_SIZE_INV
#define ARRAY_SIZE_Y (Y_MAX - Y_MIN) * STEP_SIZE_INV
My output:
184 225 213 111 0 0 0 0 230 40 212 111 0 0 0 0 64 253 98 0
0 0 0 0 1 0 1 0 1 1 1 1 6 1 0 0 168 0 0 0
0 183 213 111 0 0 0 0 0 0 0 0 0 0 0 0 9 242 236 108
0 0 0 1 64 1 1 0 1 1 1 1 240 1 1 1 249 1 0 0
0 21 255 0 0 0 0 0 98 242 236 108 0 0 0 0 0 0 0 0
0 0 0 1 128 1 1 0 1 1 1 1 128 1 1 1 0 1 1 0
0 1 255 1 0 1 1 0 1 1 1 1 0 1 1 1 31 1 1 1
0 0 0 0 184 225 213 111 0 0 0 0 2 0 0 0 0 0 0 0
9 1 0 1 0 1 1 0 1 1 1 1 0 1 1 1 64 1 1 1
0 1 0 1 64 1 1 0 1 1 1 1 96 1 1 1 249 1 1 1
0 1 213 1 0 1 1 0 1 1 1 1 0 1 1 1 32 1 1 1
0 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1
0 21 255 0 0 0 0 0 80 59 117 0 0 0 0 0 32 112 64 0
0 1 0 1 17 1 1 16 1 1 1 1 104 1 1 1 0 1 1 1
0 0 144 1 249 1 1 0 1 1 1 1 0 1 1 1 0 1 1 0
0 0 0 1 80 1 1 0 1 1 1 1 24 1 1 1 0 1 1 0
0 0 0 0 0 0 0 0 17 0 1 16 0 0 0 0 112 7 255 0
0 0 0 1 134 1 1 30 1 1 1 1 8 1 1 1 0 1 0 0
0 0 0 0 0 1 1 0 1 1 1 1 0 1 1 1 32 0 0 0
0 0 0 0 0 0 1 0 1 1 1 1 0 1 0 0 0 0 0 0
| Floating point maths will often not produce accurate results, see Is floating point math broken?.
If we print out the values of indx and indy:
20, 20
20, 19
20, 18
20, 17
20, 15
20, 14
20, 13
20, 13
20, 11
20, 10
20, 9
20, 9
20, 8
20, 6
20, 5
20, 5
20, 3
20, 3
20, 1
20, 1
19, 20
19, 19
19, 18
19, 17
...
You can see that you are writing to indexes with the value 20 which is out of bounds of the array and also you aren't writing to every index leaving some of the array elements uninitialised. Though normally booleans are only true or false they are usually actually stored as a byte allowing storing values between 0 and 255, printing the uninitialised values is undefined behaviour.
We can fix your code in this particular instance by calculating the indexes a little more carefully:
int indx = std::clamp(int(round(ARRAY_SIZE_X - (x - X_MIN) * STEP_SIZE_INV)), 1, ARRAY_SIZE_X)-1;
int indy = std::clamp(int(round(ARRAY_SIZE_Y - (y - Y_MIN) * STEP_SIZE_INV)), 1, ARRAY_SIZE_Y)-1;
There are two fixes here, you were generating values between 1 and 20, the -1 reduces this to 0 to 19. The round solves the issue of not using all the indexes (you were simply truncating by assigning to an int). The clamp ensures the values are always in range (though in this case the calculations work out to be in range).
As you want to always write to every pixel a better solution would be to iterate over the values of indx and indy and calculate the values of x and y from the indices:
for (int indx = 0; indx < ARRAY_SIZE_X; indx++)
{
float x = X_MIN - (indx - ARRAY_SIZE_X) * STEP_SIZE;
for (int indy = 0; indy < ARRAY_SIZE_Y; indy++)
{
float y = Y_MIN - (indy - ARRAY_SIZE_Y) * STEP_SIZE;
result[indx][indy] = func(x, y) < 0;
}
}
|
71,578,994 | 71,579,044 | Member initialization while using delegate constructor | The C++ standard does not allow delegate constructors and member initializers in a single mem-initializer-list, yet the following code compiles fine with clang++ and g++.
#include <iostream>
class Shape {
public:
Shape();
};
class Circle : public Shape {
public:
std::string name;
Circle(std::string name);
};
Shape::Shape() {
std::cout << "Shape constructor" << std::endl;
}
Circle::Circle(std::string name) : Shape::Shape(), name(name) { /* <--- Expected an error here! */
std::cout << "Circle constructor" << std::endl;
}
int main() {
Circle c("my_circle");
std::cout << c.name << std::endl;
return 0;
}
The relevant quote from the C++ 20 standard is (emphasis mine):
(§11.10.2/6) A mem-initializer-list can delegate to another constructor of the constructor’s class using any class-or-decltype that denotes the constructor’s class itself. If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer; the constructor is a delegating constructor, and the constructor selected by the mem-initializer is the target constructor.[...]
Did I misread the C++ standard? Do clang++ and g++ deviate from the standard here?
| You are not using a delegating constructor.
A delegating constructor calls another constructor in the same class.
For example, in:
struct Foo
{
Foo(int) : Foo("delegate") {} // #1
Foo(std::string) {} // #2
};
#1 and #2 are both constructors for Foo, and constructor #1 delegates to constructor #2.
In your case, you have a class that is derived from another class, and in:
Circle::Circle(std::string name) : Shape::Shape(), name(name)
You are initializing the base Shape portion of the Circle object, by calling Shapes default constructor. You then move on after that to finish initializing the rest of the members of the Circle class. This is not a delegating constructor.
|
71,579,286 | 71,579,532 | QT push button to create object | I am trying to create a little game using a pile structure, and im using QT Widget Application, my problem is: i have a class Pile that needs to be initialized with Pile p1(size), and "size" is obtained when the button "Create" is pushed. The problem is: when i do this, my object p1 will be exclusive to the PushButton function, and consequently the other functions of my program cannot access p1 as it disappears as soon as the PushButton function ends, and i need to access p1 with other functions from my mainwindow.cpp.
How to solve this problem? Do i need to initialize p1 differently?
| One of many possible solutions. Assuming that class Pile is not a QObject and you need to create plural instances of this class, we would nee so container to store those Piles. There are standard containers and there is Qt's own container template QList, which is a mixture of list, vector and queue.
Ensure that you use QList in mainwindow.h header:
#include <QList>
In MainWindow class declare member variable:
QList<Pile> piles;
In function that handles click signal:
void MainWindow::buttonClick() {
Pile p(size);
// do some stuff with p
piles.append(p); // or just piles.append(Pile(size));
// instead of creating separate copy Pile p(size);
}
That's all. Destructor of MainWindow would destroy created objects and you can access them from other member functions.
What is the downside of this simplistic approach? QList copies Pile class into its dynamic storage by value. Your Pile class has to be properly copyable or at least trivial. QList hides a lot of what it does to object and storage, the objects may be not stored continuously if they are big enough.
Story is slightly different if Pile is a Qt class.
QList's value type must be an assignable data type. This covers most
data types that are commonly used, but the compiler won't let you, for
example, store a QWidget as a value; instead, store a QWidget *.
You must use a pointer to a QObject if you wish to use it with a QList. The objects have to be allocated and deallocated properly, although Qt offers mechanics of automatic deallocation when parent object stops to exist.
|
71,579,360 | 71,579,919 | Why is user defined copy constructor calling base constructor while default copy constructor doesn't? | Consider the following example:
class A
{
public:
A()
{
cout<<"constructor A called: "<<this<<endl;
};
A(A const& other) = default;
};
class B : public A
{
public:
B()
{
cout<<"constructor B called: "<<this<<endl;
};
//This calls A's constructor
B(B const& other)
{
cout<<"B copy constructor called: "<<this<<endl;
};
//While this doesn't call A's constructor
//B(B const& other) = default;
};
int main()
{
B b;
B b2(b);
cout<<"b: "<<&b<<endl;
cout<<"b2: "<<&b2<<endl;
return 0;
}
Output:
constructor A called: 0x7fffc2fddda8
constructor B called: 0x7fffc2fddda8
constructor A called: 0x7fffc2fdddb0
B copy constructor called: 0x7fffc2fdddb0
b: 0x7fffc2fddda8
b2: 0x7fffc2fdddb0
Why is the constructor of A is called when copying B?
Shouldn't the copy constructor of A be called instead?
However, if you change class B's copy constructor to be default, the constructor of A is not called when copying which makes sense.
It will be nice if someone can give a reasonable explanation as to why.
|
Why is the constructor of A is called when copying B? Shouldn't the copy constructor of A be called instead?
No, it shouldn't.
A derived class must always initialize a base class. If the derived class has a constructor that is implemented explicitly by the user, but it does not explicitly call a base class constructor in its member initialization list, the compiler will make an implicit call to the base class's default constructor, regardless of the type of the derived constructor. The compiler does not make any assumption about the user's intent in implementing the derived constructor. If the user wants a specific base class constructor to be called, they need to make that call themselves.
Since B has an explicitly implemented copy constructor that lacks a member initialization list, the compiler initializes A by calling its default constructor, not its copy constructor.
IOW, this:
B(B const& other)
{
...
}
Is equivalent to this:
B(B const& other) : A()
{
...
}
NOT to this, as you are thinking:
B(B const& other) : A(other)
{
...
}
However, if you change class B's copy constructor to be default, the constructor of A is not called when copying which makes sense.
Correct, a default'ed copy constructor will call the base class's copy constructor, not its default constructor. The compiler is implicitly implementing the entire derived constructor, and so it will choose the appropriate base class constructor to call.
|
71,579,930 | 71,580,090 | Would not deleting the head in a linked list cause a memory leak? | I'm currently trying to make my own destructor for my Linked List class, and I know that I can't delete the head in the destructor because curr is using it in the code above, but would not deleting the head cause memory leaks in my code? Do I even need to set head equal to null?
~LinkedList(){//Destructor
Node*curr = head;
Node* next = nullptr;
while(curr->next != nullptr){
next = curr->next;
delete curr;
curr = next;
}
head = nullptr;
cout<<"Destructor called"<<endl;
}
|
I know that I can't delete the head in the destructor because curr is using it in the code above
Then what you know is wrong, because you can and must free the head node, otherwise it will be leaked if the list is not empty. Just because curr points to the head node does not mean you can't free that node. Just don't use that pointer anymore until you reassign it to point at a different valid node.
but would not deleting the head cause memory leaks in my code?
Yes.
Do I even need to set head equal to null?
It is not strictly needed, no. But it doesn't hurt anything, either. Since the object being destructed is effectively dead to the outside world, any further access to it by outside code is undefined behavior, regardless of whether you set its head member to nullptr or not.
That said, the code you have shown is fine, except for 1 small mistake:
while(curr->next != nullptr)
needs to be changed to this instead:
while(curr != nullptr)
In your original code, if the list is empty, curr will be nullptr and so accessing curr->next will be undefined behavior. And if the list is not empty, the loop will skip freeing the last node in the list where curr->next will be nullptr.
The correct code should look like this:
~LinkedList(){//Destructor
cout << "Destructor called" << endl;
Node *curr = head, *next;
while (curr != nullptr){
next = curr->next;
delete curr;
curr = next;
}
}
Which can be simplified to:
~LinkedList(){//Destructor
cout << "Destructor called" << endl;
while (head){
Node *next = head->next;
delete head;
head = next;
}
}
|
71,580,681 | 71,650,283 | SSL gRPC client works fine in C#, but fails with UNAVAILABLE "Empty update" in C++ | On Windows 10 Pro 21H2 with VS2022 17.1.2 and .NET 6, I am porting a simple C# gRPC client to C++, but the C++ client always fails to connect to the server despite my code seemingly doing the same, and I ran out of ideas why.
My gRPC server is using SSL with a LetsEncrypt generated certificate (through LettuceEncrypt), thus I use default SslCredentials.
In C# (with Grpc.Core), I use gRPC as follows:
// Channel and client creation
var channel = new Channel("my.domain.org:12345", new SslCredentials());
var client = new MyGrpc.MyGrpcClient(channel);
// Sample call
LoginUserReply reply = client.LoginUser(new LoginUserRequest()
{
Username = username
});
I converted this to C++ as follows, mostly based on examples given on the gRPC website:
// Channel and client creation
auto channelCreds = SslCredentials(SslCredentialsOptions());
auto channel = CreateChannel("my.domain.org:12345", channelCreds);
auto stub = MyGrpc::NewStub(channel);
// Sample call
ClientContext context;
LoginUserRequest request;
request.set_username(username);
LoginUserReply reply;
Status status = m_stub->LoginUser(&context, request, &reply);
However, with the code like this in C++, status always reports failure with UNAVAILABLE (14) "Empty update".
Why is that the case, and how can I fix this?
Investigation I did so far:
Using only InsecureChannelCredentials() results in UNAVAILABLE (14) "failed to connect to all addresses".
Running the server in plain-text, the call does work with OK (0) for testing purposes only (suggested by Lei Yang).
I set GRPC_TRACE=all and GRPC_VERBOSITY=DEBUG environment variables, but saw no extra logging from the client.
In the C# server, I set the Grpc logging level to Debug, and only noticed getting no "Reading message" log line as with working / unencrypted clients.
| This is a known issue in the Windows C++ implementation of the gRPC client (and apparently macOS too). There is a small note on the gRPC authentication guide stating:
Non-POSIX-compliant systems (such as Windows) need to specify the root certificates in SslCredentialsOptions, since the defaults are only configured for POSIX filesystems.
So, to implement this on Windows, you populate SslCredentialsOptions as follows:
#include <wincrypt.h>
SslCredentialsOptions getSslOptions()
{
// Fetch root certificate as required on Windows (s. issue 25533).
SslCredentialsOptions result;
// Open root certificate store.
HANDLE hRootCertStore = CertOpenSystemStoreW(NULL, L"ROOT");
if (!hRootCertStore)
return result;
// Get all root certificates.
PCCERT_CONTEXT pCert = NULL;
while ((pCert = CertEnumCertificatesInStore(hRootCertStore, pCert)) != NULL)
{
// Append this certificate in PEM formatted data.
DWORD size = 0;
CryptBinaryToStringW(pCert->pbCertEncoded, pCert->cbCertEncoded,
CRYPT_STRING_BASE64HEADER, NULL, &size);
std::vector<WCHAR> pem(size);
CryptBinaryToStringW(pCert->pbCertEncoded, pCert->cbCertEncoded,
CRYPT_STRING_BASE64HEADER, pem.data(), &size);
result.pem_root_certs += utf8Encode(pem.data());
}
CertCloseStore(hRootCertStore, 0);
return result;
}
And if you need the utf8Encode method too:
std::string utf8Encode(const std::wstring& wstr)
{
if (wstr.empty())
return string();
int sizeNeeded = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(),
NULL, 0, NULL, NULL);
std::string strTo(sizeNeeded, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(),
&strTo[0], sizeNeeded, NULL, NULL);
return strTo;
}
There is a (sadly constantly staling) feature request on the gRPC repository to add out-of-the-box support for this on Windows aswell to make the behavior of default SslCredentials() the same on all systems.
|
71,581,135 | 71,581,174 | Why it is needed to use const A& instead of just A&? | I was wondering why it is needed to use const A& in this situation, Why can't I use just A&? according to what I read is because it specified that it won't change the object. Is there any other reason? I would like a better explanation.
Code:
#include<iostream>
#include<set>
class A{
public:
int x;
A(int x=0): x{x} {std::cout<<"Construct"<<std::endl;};
A(const A& rhs) {x=rhs.x;std::cout<<"Copy"<<std::endl;}
};
bool operator < (const A& lhs,const A& rhs) {return lhs.x<rhs.x;}
int main(){
std::set<A> Set;
A a(10);
Set.insert(a);
Set.emplace(10);
return 0;
}
| A& is an lvalue reference, which means it can change the thing it's looking at. With
A(A& rhs)
you can call it like
int x = 10;
A a(x);
And then any changes to rhs in the constructor will change the actual variable x. And that's fine. But when you do
A a(10);
That's a problem. Because if someone changes rhs in the constructor, that means we have to "change" the number 10, and that's not really even a meaningful thing to do. 10 += 1 is nonsense in C++, for instance.
const A& is a guarantee that we aren't going to change the thing being pointed to, so it becomes safe to pass a temporary value like 10 to the function.
If we knew it was always a "small" datatype like int, we might take it by value, but we don't want to take an A as argument, since some types (like vectors) can be expensive to copy, and others (like unique_ptr) are outright impossible to copy.
Depending on your use case, you can consider using A&&, an rvalue reference. This is useful if you intend to move the value into the class you're constructing, rather than make a copy of it. You can read more about move semantics on this question, but if you're just starting out in C++, it's probably best to stay away from rvalue references. It is good to be aware that they exist, though.
|
71,581,252 | 71,581,417 | Calling private method from a Public method in the same class | I am trying to call the method gcd() in my multiplication method but I'm not sure what the correct way is. When I run the code below the console displays blank lines, when it should print a fraction. I've tried calling this->gcd(), fraction2.gcd() and gcd().
EDIT: Added cout override and main() to be able to run
#include <iostream>
using namespace std;
class Fraction {
friend ostream & operator<<(ostream & os, Fraction fraction) {
os << " " << fraction.numerator << "\n" << "---" << "\n" << " " << fraction.denominator;
return os;
}
friend istream & operator>>(istream &, Fraction);
private:
int numerator;
int denominator;
int gcd(int num1, int num2) {
int absNum1 = abs(num1);
int absNum2 = abs(num2);
while (absNum2 != 0) {
int remainder = absNum1 % absNum2;
absNum1 = absNum2;
absNum2 = remainder;
}
return absNum2;
};
public:
Fraction(int n, int d) {
this->denominator = d;
this->numerator = n;
}
Fraction(int n) {
this->numerator = n;
this->denominator = 1;
}
Fraction() {
this->numerator = 1;
this->denominator = 1;
}
Fraction operator*(Fraction fraction2) const {
Fraction multipliedFraction = Fraction();
multipliedFraction.numerator = this->numerator * fraction2.denominator;
multipliedFraction.denominator = this->denominator * fraction2.numerator;
int fractionGCD = this->gcd(multipliedFraction.numerator, multipliedFraction.denominator);
multipliedFraction.numerator = multipliedFraction.numerator / fractionGCD;
multipliedFraction.denominator = multipliedFraction.denominator / fractionGCD;
return multipliedFraction;
}
};
int main() {
Fraction fraction1 = Fraction(1, 2);
Fraction fraction2 = Fraction(1, 2);
fraction2 = fraction1 * fraction2;
cout << fraction2;
return 0;
}
| ok here goes
why this->gcd doesnt work. YOu have
class Fraction {
int gcd(int num1, int num2) {
int absNum1 = abs(num1);
int absNum2 = abs(num2);
while (num2 != 0) {
int remainder = absNum1 % absNum2;
absNum1 = absNum2;
absNum2 = remainder;
}
return absNum2;
};
public:
Fraction &operator*(const Fraction &fraction2) const {
....
}
in operator* this is const - it says so on the end of the statement. So you cannot invoke a non-const method on it.
gcd is a non const method.
This can be fixed by
int gcd(int num1, int num2) const {
It compiles now
But as other have pointed out this does not need to be a member function. What does it even mean to say frac.gcd(a,b), the method doesnt even look at frac.
You want
static int gcd(int num1, int num2) {
now you can call it like this
int gcd = Fraction::gcd(multipliedFraction.numerator, multipliedFraction.denominator);
Note that I changed the calling signature of your operator* to be
Fraction operator*(const Fraction &fraction2) const
this is what it should be as per
https://gist.github.com/beached/38a4ae52fcadfab68cb6de05403fa393
|
71,581,531 | 72,770,957 | HALO support on recent compilers for C++ coroutines | I have read the article Using Coroutine TS with zero dynamic allocations, and the author insists that HALO would work for coroutines and he provides an godbolt link which shows generator example HALO applied with clang 5.0.
However, with more recent version of clang(clang 13.0.1 on godbolt) I can see calls to operator new. As a matter of fact, I cannot find any recent compiler which supports HALO for corouine. I have tested on MSVC 2019/2022, GCC 11.2 and all assembly shows calls to operator new.
Is it true I can rely on HALO as the author insisted in that article? For instance, RVO was pretty reliable even before C++17 which brings copy ellision into standard. What should I care to expect HALO for my coroutines?
| The original example does HALO with -O3, just not with -O2.
Seems like HALO does happen, but depends on additional optimization passes.
All I did was update it to C++20 and stdx -> std.
https://godbolt.org/z/qrvWo68Yz
|
71,582,622 | 71,583,398 | How does stoi() function work with stringstream in C++? | So I'm new to C++, so bear with me here. I'm trying to read a csv file and parsing the data into smaller strings to hold in my class. As I attempt t do this, I come across a problem with stoi(). Every time I try to convert my string to an int, I get an error "terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi".
I have tried checking to see if my string is an actual number and it is. I have checked if there is a space or any other weird character, there isn't. I'm not sure what's wrong. Guidance will be appreciated.
Edit: Here is my code
class MusicData
{
public:
void setDate(string theDate) {date = theDate;}
void setRank(int theRank) {rank = theRank;}
void setSongName(string theSong) {song = theSong;}
void setArtist(string theArtist) {artist = theArtist;}
void setLastWeek(int theLastWeek) {lastWeek = theLastWeek;}
void setPeakRank(int thePeakRank) {peakRank = thePeakRank;}
void setTotalWeeks(int total) {weeksOnBoard = total;}
string getDate() {return date;}
int getRank() {return rank;}
string getSong() {return song;}
string getArtist() {return artist;}
int getLastWeek() {return lastWeek;}
int getPeakRank() {return peakRank;}
int getTotalWeeks() {return weeksOnBoard;}
private:
int rank, lastWeek, peakRank, weeksOnBoard;
string date, song, artist;
};
void readFromFile( const char fileName[], vector <string>& hold )
{
MusicData aSong;
ifstream file;
file.open(fileName);
assert(file.fail() == false);
string data;
string date, str_ranks, songName, artist, str_last_week;
int ranks, lastWeek;
while (getline(file, data))
{
stringstream s(data);
getline(s, date, ',');
aSong.setDate(date);
getline(s, str_ranks, ',');
ranks = stoi(str_ranks);
}
file.close();
}
| The operator>> will read a stream directly into an integer (you don't need to manually convert it).
string data;
int rank;
while (getline(file, data))
{
stringstream s(data);
// Always check stream operations worked.
if (getline(s, date, ',')) {
aSong.setDate(date); // Why is Date a string.
// Should this not be its own type?
char sep = 'X';
if (s >> rank >> sep && sep == ',') {
aSong.setRank(rank)
}
}
}
Though I would write operator>> for the MusicData class so that it can read its own data from the stream.
class MusicData
{
// STUFF
friend std::istream& operator>>(std::istream& str, MusicData& value);
};
|
71,582,876 | 71,586,011 | gcov coverage limited to test files in minimal g++ project | After failing to get coverage with-cmake I set up a minimalistic project to see if I can get coverage working that way.
It's derived from using-gtest-without-cmake
It has a src folder with a header and source file in it.
QuickMaths.hpp :
#include <cstdint>
using size_t = std::size_t;
size_t
multiply(size_t a, size_t b);
inline size_t
add(size_t a, size_t b)
{
return a + b;
}
class QuickMaths
{
public:
size_t operator*() const;
friend QuickMaths operator+(QuickMaths const&, QuickMaths const&);
QuickMaths(size_t x);
private:
size_t x;
};
QuickMaths.cpp:
#include "QuickMaths.hpp"
size_t
multiply(size_t a, size_t b)
{
return a * b;
}
size_t
QuickMaths::operator*() const
{
return x;
}
QuickMaths::QuickMaths(size_t x)
: x(x)
{}
QuickMaths
operator+(QuickMaths const& a, QuickMaths const& b)
{
return a.x + b.x;
}
And a test folder with
QuickMaths.cpp :
#include <gtest/gtest.h>
#include <QuickMaths.hpp>
TEST(AddTest, shouldAdd)
{
EXPECT_EQ(add(1UL, 1UL), 2UL);
}
TEST(MultiplyTest, shouldMultiply)
{
EXPECT_EQ(multiply(2UL, 4UL), 8UL);
}
TEST(QuickMathTest, haveValue)
{
auto v = QuickMaths{ 4UL };
EXPECT_EQ(*v, 4UL);
}
and main.cpp :
#include <gtest/gtest.h>
int
main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
I create a build folder and cd into it, then compile using g++ --coverage -O0 ../src/QuickMaths.cpp ../test/*.cpp -I../src/ -pthread -lgtest -lgtest_main -lgcov
I run ./a.out => output shows tests being run and passing
Lastly I run gcovr -r ../ . and get the following output:
------------------------------------------------------------------------------
GCC Code Coverage Report
Directory: ../
------------------------------------------------------------------------------
File Lines Exec Cover Missing
------------------------------------------------------------------------------
src/QuickMaths.hpp 2 0 0% 9,11
test/QuickMaths.cpp 7 0 0% 5,7,10,12,15,17-18
test/main.cpp 3 3 100%
------------------------------------------------------------------------------
TOTAL 12 3 25%
------------------------------------------------------------------------------
So it's visible that the gtest setup situated in main is being picked up, but the test cases themselves as well as the code from the src directory is not picked up as executed.
| This error occurs because you are linking multiple files with the same name.
There are two clues to the problem:
When running the test, you will see a warning such as the following:
libgcov profiling error:REDACTED/a-QuickMaths.gcda:overwriting an existing profile data with a different timestamp
The coverage report lists three files:
src/QuickMaths.hpp
test/QuickMaths.cpp
test/main.cpp
But one file is missing entirely:
src/QuickMaths.cpp
What has happened?
When your tests shut down, raw coverage data is written by the test process into .gcda files. The name of these files depends on the compilation unit.
Looking into your build dir, we see the following data (.gcda) and notes (.gcno) files:
build
|-- a-QuickMaths.gcda
|-- a-QuickMaths.gcno
|-- a-main.gcda
|-- a-main.gcno
`-- a.out
You have provided a total of three files to your compilation command
Your command is g++ ... ../src/QuickMaths.cpp ../test/*.cpp ....
The three files are src/QuickMaths.cpp, test/QuickMaths.cpp, test/main.cpp
The autogenerated names for the compilation units seems to only consider the input file's basename, ignoring the directory. Since two files have the same basename, the same name for the compilation unit a-QuickMaths is used.
Since there's a name clash for the compilation unit, there is also a conflict for the coverage data file names.
The result is corrupted coverage data.
The solution is to compile each compilation unit separately and linking them afterwards. You must give each compilation unit a distinct name, possibly using multiple subdirectories. For example:
set -euo pipefail
# compile foo/bar.cpp -> build/foo/bar.o
for source in src/*.cpp test/*.cpp; do
mkdir -p build/"$(dirname "$source")"
cd build
g++ --coverage -O0 -pthread -I../src -c -o "${source%.cpp}".o ../"${source}"
cd -
done
# link the tests
cd build;
g++ --coverage -pthread -o testcase src/*.o test/*.o -lgtest
cd -
# run the test
cd build
./testcase
cd -
tree build # show directory structure
# run gcovr
cd build
gcovr -r ..
cd -
In this example, the build directory would look like:
build
|-- src
| |-- QuickMaths.gcda
| |-- QuickMaths.gcno
| `-- QuickMaths.o
|-- test
| |-- QuickMaths.gcda
| |-- QuickMaths.gcno
| |-- QuickMaths.o
| |-- main.gcda
| |-- main.gcno
| `-- main.o
`-- testcase
And the coverage report is as expected:
------------------------------------------------------------------------------
GCC Code Coverage Report
Directory: ..
------------------------------------------------------------------------------
File Lines Exec Cover Missing
------------------------------------------------------------------------------
src/QuickMaths.cpp 9 7 77% 20,22
src/QuickMaths.hpp 2 2 100%
test/QuickMaths.cpp 10 10 100%
test/main.cpp 3 3 100%
------------------------------------------------------------------------------
TOTAL 24 22 91%
------------------------------------------------------------------------------
Additional notes:
You're providing a main() but are also linking -lgtest_main. This is unnecessary.
The --coverage flag already includes -lgcov.
|
71,583,142 | 71,583,425 | Template interface singleton | I was hoping to use an interface to make a generic template class I can add to any other class to easily create singletons. (By easily create singletons I mean avoid having to re-write the 6 lines for GetInstance)
template <class T>
class Singleton
{
public:
static T* GetInstance();
};
template<class T>
inline T* Singleton<T>::GetInstance()
{
static T* myInst;
if (!myInst)
{
myInst = new T();
}
return(myInst);
}
The only issue is that with this to work I have to have the constructor for the class be public, which I would like to avoid as it sort of ruins the Singleton design pattern.
Is there a solution I may not be aware of to get an instance for the generic type without having a public constructor? I do realise this might be a stupid question but I would really like this class to work.
Thanks
| First of all, your singleton should look differently as yours isn't thread safe. Then there are at least 2 solutions. First, is to make a particular instantiation a friend, so it would look something like this:
template <class T>
class Singleton
{
public:
static T* GetInstance();
};
template<class T>
T* Singleton<T>::GetInstance()
{
static T myInst;
return &myInst;
}
class Test
{
public:
void print()
{
std::cout << "Hello!\n";
}
private:
Test() = default;
friend class Singleton<Test>;
};
That would require the modification of the user class which isn't ideal. So we can employ another solution like this:
template <class T>
class Singleton: private T
{
public:
static T* GetInstance();
private:
using T::T;
};
template<class T>
T* Singleton<T>::GetInstance()
{
static Singleton<T> myInst;
return &myInst;
}
class Test
{
public:
void print()
{
std::cout << "Hello!\n";
}
protected:
Test() = default;
};
The only modification to the user class is making its ctor to be protected instead of private which is not a problem, in my opinion. The limitation is that the user class should not be final.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.