question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,650,522 | 70,650,615 | how to guarantee initilization of a stack variable with a compile time constant | In C++20 we now have constinit. constexpr and consteval.
I can now guarantee that a static variable is initialized by the result of a constexpr or consteval function by using constinit. OK
I also can guarantee that a stack variable is initialized with the result of a consteval function executed in compile time.
But how can I force to run a constexpr function to calculate a result in compile time to init a variable on stack?
// Lets assume that we have a much more complex function so that the compiler will not
// always decide to compile time evaluation automatically
constexpr int func( int i )
{
return i+2;
}
int main()
{
??? int i = func(8);
...
i = 9;
}
If we use constexpr the variable is implicitly const and constinit is not allowed here. Any chance to initialize this var with the compile time evaluated result of a constexpr function without making it const? I am simply wondering why constinit is limited to static variables. For my it makes not much sense.
| I think it is better to use consteval function, but if you cannot change it, you can simply use a temporary variable which will surely optimize later:
constexpr int func( int i )
{
return i+2;
}
int main()
{
constexpr int i1 = func(8);
auto i2 = i1;
i2 = 9;
}
Although you may not like this method, I think it works without any problem....
You can also use something like this(Based on StoryTeller idea):
template<typename T> constexpr std::remove_const_t<T> const_eval(T&& res) { return res; }
which support returning references from method too.
|
70,651,203 | 70,652,275 | how to set shared memory between python and c++ in linux and osx | I was able to share memory on windows simply using winapi in cpp and mmap.mmap in python. just match "name".
And I was able to set the name of the shared memory using <boost/interprocess/shared_memory_object.hpp> on mac.
But python's mmap.mmap() didn't work. Even in the official documentation the parameters were different. It didn't have a parameter to set a name for.
So I gave up and decided to use <sys/ipc.h>.
It was able to communicate with python using the key, but write() to sysv_ipc in python gives the following error:
ValueError: Attempt to write past end of memory segment
python code
shm = sysv_ipc.SharedMemory(777)
if shm:
offset = 0
for idx in range(0, 21):
shm.write(struct.pack(
'f', hand_landmarks.landmark[idx].x), offset)
offset += 4
shm.write(struct.pack(
'f', hand_landmarks.landmark[idx].y), offset)
offset += 4
shm.write(struct.pack(
'f', hand_landmarks.landmark[idx].z), offset)
offset += 4
c++ code
shmid = shmget(777, 512, IPC_CREAT | 0666)
shared_memory = shmat(shmid, NULL, 0)
fptr = reinterpret_cast<float *>(shared_memory);
for (int i = 0; i < 63; i += 3)
{
std::cout << fptr[i] << " " << fptr[i + 1] << " " << fptr[i + 2] << "\n";
}
What should I do?
| The issues is that shmget second parameters in in bits, not bytes.
So the correct way to write the code is:
shmid = shmget(777, 512 * 8, IPC_CREAT | 0666)
|
70,651,317 | 70,651,425 | How can I create an array of void pointers through variadic templates? | I have something like:
class A
{
public:
A(B* b, int* i)
{
void* args[] = { (void*)&b, (void*)&i };
}
};
But I need it to be more generic, in the sense that I want to the constructor of A to accept any number of variables, of any type.
How do I accomplish this with templates?
| You can write your constructor this way:
class A {
public:
template <class... Args>
A(Args*... pargs) {
void* args[] = { (void*)&pargs... };
}
};
Note that you are storing the address of the pointers, not the pointers themselves, in args.
Also I wouldn't use that kind of things unless you have a very good reason to in actual code.
|
70,651,696 | 70,651,803 | Difference between ordinary parameter, reference parameter and const reference parameter passed by ordinary object and object created temporary | Since I'm a beginner in c++, some questions don't quite understand. This question came across by accident while I was reading C++ primer 5th.
I have a Cat class with 3 different constructors(named by Constructor 1, Constructor 2, Constructor 3):
class Cat {
friend class Cats;
private:
std::string name;
public:
Cat() = default;
// Constructor 1
Cat(std::string n): name(n) {
std::printf("Call: Cat(std::string n)\n");
}
// Constructor 2
Cat(std::string& n): name(n) {
std::printf("Call: Cat(std::string& n)\n");
}
// Constructor 3
Cat(const std::string& n): name(n) {
std::printf("Call: Cat(const std::string &n)\n");
}
};
And I want to instantiate the class in two different ways:
class C7T17_Main {
public:
void run() {
// Instantiation 1
Cat cat(std::string("Cathy"));
// Instantiation 2
std::string s("Mike");
Cat cat2(s);
}
};
Then the problem comes:
For Constructor 1:
Instantiation 1 and Instantiation 2 both work well
For Constructor 2:
Instantiation 1 raises an error. The compiler complains that 'Candidate constructor not viable: expects an lvalue for 1st argument'
Instantiation 2 works normally.
For Constructor 3:
Instantiation 1 and Instantiation 2 both work well
My guess is:
Instantiation 1 does not actually create a variable, but a temporary value for initializing cat, so it is not suitable as a reference parameter.
For constructor 3, the const reference parameter represents a constant that can accept a temporary value for initialization
Looking forward to your help. :)
| It's pretty simple:
ctor 1 receives the argument by copy (pass by value);
ctor 2 receives the argument by non-const lvalue reference, so it only supports non-const lvalues.
ctor 3 receives argument by const lvalue reference so it supports const-lvalue, non-const lvalue, const rvalue and non-const rvalue.
Instantiation 1 does not actually create a variable, but a temporary value for initializing cat, so it is not suitable as a reference parameter.
Yes, it creates a prvalue, and it can be passed by reference like this:
// ctor 4
Cat( std::string&& n ) // see the double ampersand
ctor 4 only accepts temporaries (rvalues) by reference.
For constructor 3, the const reference parameter represents a constant that can accept a temporary value for initialization
Yes, it can bind to all the values as I mentioned previously.
For Constructor 2:
Instantiation 1 raises an error. The compiler complains that 'Candidate constructor not viable: expects an lvalue for 1st argument'
This is the expected behavior.
Important Note:
Cat(std::string&& n): name(n) { // here n is of type rvalue refernece to string
std::printf("Call: Cat(std::string& n)\n");
}
Function parameters that are of type rvalue reference are lvalues themselves. So in the above code, n is a variable and it's an lvalue. Thus it has an identity and can not be moved from (you need to use std::move in order to make it movable).
Extra note:
You can even pass an lvalue to a function that only accepts rvalues like this:
Cat( std::string&& n );
std::string s("Mike");
Cat cat2( std::move(s) );
std::move performs a simple cast. It casts an lvalue to an xvalue so it becomes usable by a function that only accepts an rvalue.
Value Category in C++11
Take a look at this:
Explanation for the above image
In C++11, expressions that:
have identity and cannot be moved from are called lvalue expressions;
have identity and can be moved from are called xvalue expressions;
do not have identity and can be moved from are called prvalue ("pure rvalue") expressions;
do not have identity and cannot be moved from are not used[6].
The expressions that have identity are called "glvalue expressions" (glvalue stands for "generalized lvalue"). Both lvalues and xvalues are glvalue expressions.
The expressions that can be moved from are called "rvalue expressions". Both prvalues and xvalues are rvalue expressions.
Read more about this topic at value categories.
|
70,651,941 | 70,652,946 | Boost::Spirit doubles character when followed by a default value | I use boost::spirit to parse (a part) of a monomial like x, y, xy, x^2, x^3yz. I want to save the variables of the monomial into a map, which also stores the corresponding exponent. Therefore the grammar should also save the implicit exponent of 1 (so x stores as if it was written as x^1).
start = +(potVar);
potVar=(varName>>'^'>>exponent)|(varName>> qi::attr(1));// First try: This doubles the variable name
//potVar = varName >> (('^' >> exponent) | qi::attr(1));// Second try: This works as intended
exponent = qi::int_;
varName = qi::char_("a-z");
When using the default attribute as in the line "First try", Spirit doubles the variable name.
Everything works as intended when using the default attribute as in the line "Second try".
'First try' reads a variable x and stores the pair [xx, 1].
'Second try' reads a variable x and stores the pair [x, 1].
I think I solved the original problem myself. The second try works. However, I don't see how I doubled the variable name. Because I am about to get familiar with boost::spirit, which is a collection of challenges for me, and there are probably more to come, I would like to understand this behavior.
This is the whole code to recreate the problem. The frame of the grammar is copied from a presentation of the KIT https://panthema.net/2018/0912-Boost-Spirit-Tutorial/ , and Stackoverflow was already very helpful, when I needed the header, which enables me to use the std::pair.
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <cmath>
#include <map>
#include <utility>//for std::pair
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp> //https://stackoverflow.com/questions/53953642/parsing-map-of-variants-with-boost-spirit-x3
namespace qi = boost::spirit::qi;
template <typename Parser, typename Skipper, typename ... Args>
void PhraseParseOrDie(
const std::string& input, const Parser& p, const Skipper& s,
Args&& ... args)
{
std::string::const_iterator begin = input.begin(), end = input.end();
boost::spirit::qi::phrase_parse(
begin, end, p, s, std::forward<Args>(args) ...);
if (begin != end) {
std::cout << "Unparseable: "
<< std::quoted(std::string(begin, end)) << std::endl;
throw std::runtime_error("Parse error");
}
}
class ArithmeticGrammarMonomial : public qi::grammar<
std::string::const_iterator,
std::map<std::string, int>(), qi::space_type>
{
public:
using Iterator = std::string::const_iterator;
ArithmeticGrammarMonomial() : ArithmeticGrammarMonomial::base_type(start)
{
start = +(potVar);
potVar=(varName>>'^'>>exponent)|(varName>> qi::attr(1));
//potVar = varName >> (('^' >> exponent) | qi::attr(1));
exponent = qi::int_;
varName = qi::char_("a-z");
}
qi::rule<Iterator, std::map<std::string, int>(), qi::space_type> start;
qi::rule<Iterator, std::pair<std::string, int>(), qi::space_type> potVar;
qi::rule<Iterator, int()> exponent;
qi::rule<Iterator, std::string()> varName;
};
void test2(std::string input)
{
std::map<std::string, int> out_map;
PhraseParseOrDie(input, ArithmeticGrammarMonomial(), qi::space, out_map);
std::cout << "test2() parse result: "<<std::endl;
for(auto &it: out_map)
std::cout<< it.first<<it.second << std::endl;
}
/******************************************************************************/
int main(int argc, char* argv[])
{
std::cout << "Parse Monomial 1" << std::endl;
test2(argc >= 2 ? argv[1] : "x^3y^1");
test2(argc >= 2 ? argv[1] : "xy");
return 0;
}
Live demo
|
I think I solved the original problem myself. The second try works.
Indeed. It's how I'd do this (always match the AST with your parser expressions).
However, I don't see how I doubled the variable name.
It's due to backtracking with container attributes. They don't get rolled back. So the first branch parses potVar into a string, and then the parser backtracks into the second branch, which parses potVar into the same string.
boost::spirit::qi duplicate parsing on the output
Understanding Boost.spirit's string parser
Parsing with Boost::Spirit (V2.4) into container
Boost Spirit optional parser and backtracking
boost::spirit alternative parsers return duplicates
It can also crop up with semantic actions:
Boost Semantic Actions causing parsing issues
Boost Spirit optional parser and backtracking
In short:
match your AST structure in your rule expression, or use qi::hold to force the issue (at performance cost)
avoid semantic actions (Boost Spirit: "Semantic actions are evil"?)
For inspiration, here's a simplified take using Spirit X3
Live On Compiler Explorer
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <fmt/ranges.h>
#include <map>
namespace Parsing {
namespace x3 = boost::spirit::x3;
auto exponent = '^' >> x3::int_ | x3::attr(1);
auto varName = x3::repeat(1)[x3::char_("a-z")];
auto potVar
= x3::rule<struct P, std::pair<std::string, int>>{}
= varName >> exponent;
auto start = x3::skip(x3::space)[+potVar >> x3::eoi];
template <typename T = x3::unused_type>
void StrictParse(std::string_view input, T&& into = {})
{
auto f = input.begin(), l = input.end();
if (!x3::parse(f, l, start, into)) {
fmt::print(stderr, "Error at: '{}'\n", std::string(f, l));
throw std::runtime_error("Parse error");
}
}
} // namespace Parsing
void test2(std::string input) {
std::map<std::string, int> out_map;
Parsing::StrictParse(input, out_map);
fmt::print("{} -> {}\n", input, out_map);
}
int main() {
for (auto s : {"x^3y^1", "xy"})
test2(s);
}
Prints
x^3y^1 -> [("x", 3), ("y", 1)]
xy -> [("x", 1), ("y", 1)]
Bonus Notes
It looks to me like you should be more careful. Even if you assume that all variables are 1 letter and no terms can occur (only factors), then still you need to correctly handle x^5y^2x to be x^6y^2 right?
Here's Qi version that uses semantic actions to correctly accumulate like factors:
Live On Coliru
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
#include <iostream>
#include <map>
namespace qi = boost::spirit::qi;
using Iterator = std::string::const_iterator;
using Monomial = std::map<char, int>;
struct ArithmeticGrammarMonomial : qi::grammar<Iterator, Monomial()> {
ArithmeticGrammarMonomial() : ArithmeticGrammarMonomial::base_type(start) {
using namespace qi;
exp_ = '^' >> int_ | attr(1);
start = skip(space)[ //
+(char_("a-z") >> exp_)[_val[_1] += _2] //
];
}
private:
qi::rule<Iterator, Monomial()> start;
qi::rule<Iterator, int(), qi::space_type> exp_;
};
void do_test(std::string_view input) {
Monomial output;
static const ArithmeticGrammarMonomial p;
Iterator f(begin(input)), l(end(input));
qi::parse(f, l, qi::eps > p, output);
std::cout << std::quoted(input) << " -> " << std::endl;
for (auto& [var,exp] : output)
std::cout << " - " << var << '^' << exp << std::endl;
}
int main() {
for (auto s : {"x^3y^1", "xy", "x^5y^2x"})
do_test(s);
}
Prints
"x^3y^1" ->
- x^3
- y^1
"xy" ->
- x^1
- y^1
"x^5y^2x" ->
- x^6
- y^2
|
70,652,383 | 70,668,665 | Freeze/Fail when using functional with OpenMP [Pybind11/OpenMP] | I have a problem with the functional feature of Pybind11 when I use it with a for-loop with OpenMP. I've done some research and my problem sounds pretty similar to the one in this Pull Request from 2 years ago, but although this PR is closed and the issue seems to be fixed I still have this issue. A code example I created will hopefully explain my problem better:
b.h
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <omp.h>
namespace py = pybind11;
class B {
public:
B(int n, const int& initial_value);
void map(const std::function<int(int)> &f);
private:
int n;
int* elements;
};
b.cpp
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include "b.h"
namespace py = pybind11;
B::B(int n, const int& v)
: n(n) {
elements = new int[n];
#pragma omp parallel for
for (int i = 0; i < n; i++) {
elements[i] = v;
}
}
void B::map(const std::function<int(int)> &f) {
#pragma omp parallel for
for (int i = 0; i < n; i++) {
elements[i] = f(elements[i]);
}
}
PYBIND11_MODULE(m, handle) {
handle.doc() = "Example Module";
py::class_<B>(handle, "B")
.def(py::init<int, int>())
.def("map", &B::map)
;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.4...3.18)
project(example)
find_package(OpenMP)
add_subdirectory(pybind11)
pybind11_add_module(m b.cpp)
if(OpenMP_CXX_FOUND)
target_link_libraries(m PUBLIC OpenMP::OpenMP_CXX)
else()
message( FATAL_ERROR "Your compiler does not support OpenMP" )
endif()
test.py
from build.m import *
def test(i):
return i * 20
b = B(2, 2)
b.map(test)
I basically have an array where I want to apply a Python function to every element using a for-loop. I know that it is an issue with functional and OpenMP specifically because in other parts of my project I am using OpenMP successfully and functional is also working if I am not using OpenMP.
Edit: It freezes at the map function and has to be terminated. I am using Ubuntu 21.10, Python 3.9, GCC 11.2.0, OpenMP 4.5, and the newest version of the pybind11 repo.
| You're likely experiencing a deadlock between OpenMP's scheduler and Python's GIL (Global Interpreter Lock).
I suggest attaching gdb to your process and looking at where the threads are to verify that's really the problem.
IMHO mixing Python functions and OpenMP like that is asking for trouble. If you want multi-threading of Python functions you can use multiprocessing.pool.ThreadPool. But unless your functions release the GIL most of the time you won't benefit from multi-threading.
|
70,652,546 | 70,743,356 | IncrediBuild configure build order | I have a solution with multiple projects in it. From those numerous projects some depend on the Libs projects and the test projects depend on the code, obviously.
How do I configure IncrediBuild to build Libs first, then build code and only then proceed to building tests?
I have:
Microsoft Visual Studio Professional 2017 Version 15.9.40
IncrediBuild Version 9.5.0 (build 3385)
| I opened Project -> Project Dependencies... went over every project and configured the code to depend on Libs and Tests to depend on the code projects and now they are built in the correct order and I don't have to go over every Lib and build/rebuid it every time I pull a minute change in it from the repository.
In the end the answer wasn't related to IncrediBuild at all, just Visual Studio functionality.
|
70,652,769 | 70,660,313 | Can multi-threading improve the performance definitely | I'm using C++11 to develop a project.
In some function, I got some parallel tasks as below:
void func() {
auto res1 = task1();
auto res2 = task2();
auto res3 = task3();
...
std::cout << res1 + res2 + res3 + ...;
}
Well, each task is a little heavy, let's say each task would spend 300ms.
Now I'm thinking that making each task to be a std::thread should improve the performance.
But as my understanding, it's the OS who schedules the threads. I'm not sure if the OS ensures that it will execute these threads immediately or it may need to wait for some other stuff?
So my question is if making the tasks multi-threading can definitely improve the performance, or in some cases, this method would get a worse performance?
BTW, I know that too many threads can cause a very bad performance because of context switch, in my real case, the counts of the tasks is less than 10 and they don't share any data.
|
I'm not sure if the OS ensures that it will execute these threads
immediately or it may need to wait for some other stuff?
The OS will try to start up the threads as quickly as it can. They aren't guaranteed to already be running at the exact instant your thread object's constructor constructor returns, but OTOH the OS won't deliberately wait around before starting them up, either. (e.g. on a system that isn't terribly loaded-down, you can generally expect them to be running within a small number of milliseconds)
So my question is if making the tasks multi-threading can definitely
improve the performance, or in some cases, this method would get a
worse performance?
Adding multithreading to a program and finding that your program actually takes longer to complete than the single-threaded version is actually a fairly common experience, especially for programmers who are new to multithreaded programming.
It's similar to adding more cooks to a kitchen -- if the cooks work together well and stay out of each other's way, they can get more food cooked in less time, but if they don't, they may well spend most of their time waiting for each other to finish using the various tools/ingredients, or talking about who is supposed to be doing what, and end up being slower than a single cook would be.
In general, multithreading can speed things up, if you are running on a multi-core system, and your various threads don't need to communicate with each other too much, and the threads don't need to obtain exclusive access to shared resources too often, and your threads aren't doing anything grossly inefficient (like intensive polling or busy-waiting). Whether these conditions are easy to achieve or difficult depends a lot on the task you are trying to accomplish.
|
70,652,803 | 70,654,845 | C++ dangling reference strange behaviour | int*& f(int*& x, int* y){
int** z = &y;
*z = x;
return *z;
}
Hello everyone, I've been given this code on an exam and I had some problems with it.
My understanding is that given a reference to a pointer (x) and a pointer copy constructed (y) in the body of the function a local double pointer (z) is beeing created and initialized with y l-value, then dereferenced 1 time, so y is beeing accessed and the address contained in y noe becomes the address contained in x. Afterwards *z is returned as a pointer reference I assume of y.
If my previous part is correct I'm not explaining why returning y who gets deallocated on the exit of the function (since a temporary parameter) does not create any problems in the program, indeed the exam answer was that the function was returning a dangling reference and I agree with that, but, copypasting the code, and "playing" with the returned variable, even doing random stuff after the parameter is returned in order to "edit the stack" where the deallocated y still is present and "ready to be overwritten"(if I'm still right) does not present any undefined behaviour of the program.
My only explaination is that the return only copies the r-value contained in y or maybe it returns l-value and r-value (since returns a reference to a pointer) but when associated to an external pointer "calling" the function y doesn't get properly deallocated or in some way the pointer that gets the value takes the place of the y pointer that gets deallocated.
On the bottom you can find the code used to test the function int*& f(int*&, int*).
My question is: Is this a proper dangling reference or is a borderline case where such a thing could be used in a program?
#include <iostream>
using namespace std;
int a = 65;
int*& f(int*& x, int* y)
{
cout<<"indirizzo di y: "<<&y<<endl;
cout<<"indirizzo di x: "<<&x<<endl;
int** z = &y;
cout<<"indirizzo di *z prima: "<<*z<<endl;
*z=x;
cout<<"indirizzo di *z dopo: "<<*z<<endl;
cout<<"y punta a: "<<y<<endl;
cout<<"z dopo: "<<z<<endl;
return *z;
}
int*& crashaFisso() //function that crashes every time with a "proper" dangling reference
{
int a=10;
int* x =&a;
return x;
}
int main()
{
system("CLS");
int b = 20;
int codicerandom=0;
int* i = &a;
cout<<"indirizzo di i: "<<i<<endl;
int* u = &b;
cout<<"indirizzo funzione: "<<&f(i,u)<<endl;
int* aux = f(i,u);
int* crash = crashaFisso();
cout<<"crash: "<<*crash<<endl;
cout<<"aux: "<<*aux<<endl;
for(int i=0;i<100;i++)
codicerandom +=i;
for(int i=0;i<100;i++)
codicerandom +=i;
for(int ji=100;ji>0;ji--)
{
codicerandom +=ji;
for(int x=100;x>0;x--)
{
codicerandom -= x*2;
}
}
cout<<codicerandom<<endl;
cout<<"crash: "<<*crash<<endl;
cout<<"aux: "<<*aux<<endl;
cout<<"crash: "<<*crash<<endl;
cout<<"aux: "<<*aux<<endl;
a=32;
cout<<"aux: "<<*aux<<endl;
return 0;
}
| Your test is not as sharp as it could be: In order to show that the reference is dangling you should actually store the reference and not a copy of the value of the deceased object it refers to.
To understand why that would be more interesting let's dissect the function for a sec.
int** z = &y; makes z point to y; *z is now an alias for y.
*z=x; makes a copy of the address value the pointer referenced by x contains and assigns it to the entity known as y or *z. That address is entirely valid (f() is called with the address of main's a).
return *z; returns an lvalue reference (that is, a reference you could syntactically assign to) to the lvalue *z aka y. That lvalue is of type pointer to int and contains the valid address of main's a. The issue with the code is that what is referred to, namely y, is destroyed as soon as the function has returned so that reading the value through it in cout<<"indirizzo funzione: "<<&f(i,u) is undefined behavior, and the compiler warns about it.
The reason that the program doesn't crash is that immediately after f returns, the memory of its former local variables is still intact. Of course it's illegal to access it, but if you look at the memory it's all there. Consequently, int* aux = f(i,u); simply reads the (valid) address stored in the recently deceased y and stores it as a copy in aux. You can now write on the stack as much as you like: aux will contain a valid value.
That's why you were not successful in your attempts to write on the stack in order to overwrite it.
If instead you store the returned reference to *z aka y you'll refer to the deceased object itself which inevitably will be overwritten by future stack operations or used in other ways by the compiler.
Here is an anglicized, minimal example using a reference instead of a copy (note the definition of the variable dangling_ref). I compile and run it it twice, with standard optimization and with maximum optimization. Simply changing the compiler options changes the output (and, what I'd assume is a bug, determines whether the warning is output!). Here is a sample session on msys2.
$ cat dangling-ref.cpp
#include <iostream>
using namespace std;
int*& dangling_ref_ret(int*& x, int* y)
{
int** z = &y;
*z = x;
cout << "ret addr " << *z << " (should be == " << y << ")" << ", val = " << **z << endl;
return *z;
}
int main()
{
int b = 1;
int* pb = &b;
int c = 2;
int*& dangling_ref = dangling_ref_ret(pb, &c);
cout << "val of dangling_ref " << dangling_ref << " is " << *dangling_ref << endl;
}
$ gcc --version
gcc (GCC) 10.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ -Wall -o dangling-ref dangling-ref.cpp && ./dangling-ref.exe
ret addr 0xffffcc34 (should be == 0xffffcc34), val = 1
val of dangling_ref 0xffffcc34 is 1
$ g++ -Wall -O3 -o dangling-ref dangling-ref.cpp && ./dangling-ref.exe
dangling-ref.cpp: In function ‘int*& dangling_ref_ret(int*&, int*)’:
dangling-ref.cpp:9:13: warning: function may return address of local variable [-Wreturn-local-addr]
9 | return *z;
| ^
dangling-ref.cpp:4:38: note: declared here
4 | int*& dangling_ref_ret(int*& x, int* y)
| ~~~~~^
ret addr 0xffffcc10 (should be == 0xffffcc10), val = 1
val of dangling_ref 0xffffcc14 is 2
Visual Studio also behaves differently between Debug and Release mode.
You can try different compilers and options on godbolt.
|
70,652,825 | 70,658,373 | eBPF: raw_tracepoint arguments | I am getting into eBPF programming and want to use raw tracepoints, but I do not really understand, how to use them and how to access the arguments correctly. I would appreciate any help and hints to documantation.
My questions:
How do I get the arguments from the syscall by using a raw_tracepoint instead of a tracepoint?
BTW: What is the uint16_t common_type; of a raw tracepoint?
System: Ubuntu 2004 with Kernel 5.4 generic, x86_64
Explanation/Example:
I started with the "normal tracepoint" sys_enter_kill, where I can create the struct with arguments from sudo cat /sys/kernel/debug/tracing/events/syscalls/sys_enter_kill/format:
// sudo cat /sys/kernel/debug/tracing/events/syscalls/sys_enter_kill/format
// name: sys_enter_kill
// ID: 184
// format:
// field:unsigned short common_type; offset:0; size:2; signed:0;
// field:unsigned char common_flags; offset:2; size:1; signed:0;
// field:unsigned char common_preempt_count; offset:3; size:1;signed:0;
// field:int common_pid; offset:4; size:4; signed:1;
// field:int __syscall_nr; offset:8; size:4; signed:1;
// field:pid_t pid; offset:16; size:8; signed:0;
// field:int sig; offset:24; size:8; signed:0;
struct syscalls_enter_kill_args
{
unsigned short common_type;
unsigned char common_flags;
unsigned char common_preempt_count;
int common_pid;
long syscall_nr;
long pid;
long sig;
};
SEC("tracepoint/xxx")
int main_entry(struct syscalls_enter_kill_args *ctx)
{
if(ctx->sig != 9)
return 0;
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid;
bpf_printk("Catched function call; PID = : %d.\n", pid);
return 0;
}
This simple bpf program just outputs some text, whenever a kill signal is invoked. It only logs SIGKILL, not SIGINT, SIGQUIT, ...
Now I want to do the same functionality with the raw tracepoint sys_enter.
// sudo cat /sys/kernel/debug/tracing/events/raw_syscalls/sys_enter/format
// name: sys_enter
// ID: 22
// format:
// field:unsigned short common_type; offset:0; size:2; signed:0;
// field:unsigned char common_flags; offset:2; size:1; signed:0;
// field:unsigned char common_preempt_count; offset:3; size:1;signed:0;
// field:int common_pid; offset:4; size:4; signed:1;
// field:long id; offset:8; size:8; signed:1;
// field:unsigned long args[6]; offset:16; size:48; signed:0;
struct sys_enter_args
{
uint16_t common_type;
uint8_t common_flags;
uint8_t common_preempt_count;
int32_t common_pid;
int64_t id;
uint64_t args[6]; // Je 4 Bytes
};
SEC("raw_tracepoint/xxx")
int main_entry_raw(struct sys_enter_args *ctx)
{
if(ctx->id != SYS_kill) // 62
return 0;
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid;
bpf_printk("Catched function call; PID = : %d.\n", pid);
bpf_printk(" type: %u\n", ctx->common_type);
bpf_printk(" id: %u\n", ctx->id);
uint64_t* args = ctx->args;
uint64_t arg3 = 0;
bpf_probe_read(&arg3, sizeof(uint64_t), args + 3);
bpf_printk(" Arg3: %u \n", arg3);
}
I thought, I might get the signal (SIGKILL/SIGINT/SIGQUIT/...) via
field:int sig; offset:24; size:8; signed:0; from args[]:
Offset=24 => Byte 3; size 8 => Type u64 = unsigned long.
However, this results no useful values.
So how do I get the value of the signal, which I can access in the tracepoint, also in the raw_tracepoint?
Thanks for help!
| I think I worked it out, based on this article.
The ctx of a raw_tracepoint program is struct bpf_raw_tracepoint_args. Which is defined in bpf.h as
struct bpf_raw_tracepoint_args {
__u64 args[0];
};
So basically just an array of numbers/pointers. The meaning of these arguments are depend on how the tracepoint prototype is defined. When looking at the source code where the tracepoint is defined we find:
TRACE_EVENT_FN(sys_enter,
TP_PROTO(struct pt_regs *regs, long id),
TP_ARGS(regs, id),
TP_STRUCT__entry(
__field( long, id )
__array( unsigned long, args, 6 )
),
TP_fast_assign(
__entry->id = id;
syscall_get_arguments(current, regs, __entry->args);
),
TP_printk("NR %ld (%lx, %lx, %lx, %lx, %lx, %lx)",
__entry->id,
__entry->args[0], __entry->args[1], __entry->args[2],
__entry->args[3], __entry->args[4], __entry->args[5]),
syscall_regfunc, syscall_unregfunc
);
Lets focus on TP_PROTO(struct pt_regs *regs, long id), this means that args[0] is struct pt_regs *regs and args[1] is long id. struct pt_regs is a copy of the CPU registers at the time sys_enter was called. id is the ID of the syscall.
We can get to the arguments of the syscall by extracting them from the CPU registers. The System V ABI specifies which parameters should be present in which CPU registers. To make our lives easier, libbpf defines PT_REGS_PARM{1..5} macros in bpf_tracing.h
So, if believe this should be a correct program:
SEC("raw_tracepoint/sys_enter")
int main_entry_raw(struct bpf_raw_tracepoint_args *ctx)
{
unsigned long syscall_id = ctx->args[1];
struct pt_regs *regs;
if(syscall_id != SYS_kill) // 62
return 0;
regs = (struct pt_regs *)ctx->args[0];
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid;
bpf_printk("Catched function call; PID = : %d.\n", pid);
bpf_printk(" id: %u\n", syscall_id);
uint64_t arg3 = 0;
bpf_probe_read(&arg3, sizeof(uint64_t), PT_REGS_PARM3(regs));
bpf_printk(" Arg3: %u \n", arg3);
}
|
70,653,013 | 70,653,212 | Add the instance name to the constructor arguments as an std::string with Macros | More precisely, I have a class:
struct S
{
template <class... T>
S(std::string instance_name, T*... ptrs);
}
That needs to be constructed in a way like:
STRUCT(example(arg1, arg2, arg3));
Where STRUCT is the macro that expands to:
S example(std::string("example"), arg1, arg2, arg3);
I have been trying with #define X(a) #a but can't figure out how to make it all work.
Thanks
EDIT:
I have a map filled with pairs of <std::string, void*> where functions pointers are stored. Those functions stored there have a counterpart function with the signature: example(Args args), where both functions have same arguments.
So I have entries in the map such as ("example", &example_counterpart) and I want the user to be able to call example_counterpart(...) with something like: OTHER(example(Args args));
The solution you gave is quite close, but the function is called (in the constructor of S) with MACRO(example, arg1, arg2), which is not exactly what I need.
I m open to other suggestions to achieve this, the use of the class is just an idea I had but its not important, the things I cant change is the fact I have those counterpart functions stored in a map and I need to call them with some sort of flag to differentiate it from the normal function call.
I hope my intent it's clear, even tho the reasons might not
| Suggestion:
#define STRUCT(inst,...) S inst(std::string(#inst),__VA_ARGS__)
It would then be used slightly different from what you want:
STRUCT(example, arg1, arg2, arg3);
... but it expands to exactly what you want:
S example(std::string("example"), arg1, arg2, arg3);
Demo
|
70,653,375 | 70,654,432 | Conversion operator with const-result - GCC/Clang discrepancy | Given the following code snippet:
struct Foo {
};
struct Bar {
operator const Foo() {
return Foo();
}
};
int main() {
Bar bar;
Foo foo(bar);
return 0;
}
See here on godbolt
It compiles fine with gcc 11.2 but fails to compile with clang 12.0 with the following error:
<source>:12:13: error: no viable conversion from 'Bar' to 'Foo'
Foo foo(bar);
^~~
<source>:1:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'Bar' to 'const Foo &' for 1st argument
struct Foo {
^
<source>:1:8: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'Bar' to 'Foo &&' for 1st argument
struct Foo {
^
<source>:5:5: note: candidate function
operator const Foo() {
^
<source>:1:8: note: passing argument to parameter here
struct Foo {
^
Which implementation is correct?
Is this actually valid C++?
PS: I know it can be fixed by removal of the const or return of a const reference.
| I think this is the open CWG issue 2077.
Basically,
Foo foo(bar);
is direct-initialization, meaning that it will consider the constructors of Foo for overload resolution and choose the best viable one. The candidates are the implicit copy and move constructor with signatures
Foo(const Foo&);
Foo(Foo&&);
If you look at the linked CWG issue and for more details the related Clang bug, then we see that this is exactly the situation described there, only that our function call is a constructor call, while theirs is a normal function call.
If we simply believe the argument made in the CWG issue, then overload resolution should apparently by current rules pick the Foo&& overload, while not actually being allowed to bind the reference, resulting in an ill-formed program.
I will try to reproduce the reasoning from the linked sources here:
When considering conversions to the constructor's parameter from bar, the reference cannot directly bind bar because of the type mismatch.
According to [over.ics.ref]/2 in such a case the conversion sequence is determined as if by copy-initialization of a temporary of the referenced type.
In this case the conversion is Bar -> const Foo -> Foo via the user-defined constructor for the move constructor.
For the copy constructor it is Bar -> const Foo.
However in the copy-initialization of the temporary, const-qualifier conversions are "subsumed" in the initialization. [over.ics.ref]/2 Therefore the move constructor sequence is not worse than that of the copy constructor.
In such a case the rvalue reference is a tie-breaker and so the move constructor is chosen in overload resolution.
However, a const Foo cannot be bound to a non-const rvalue reference. Therefore the program is ill-formed. ([dcl.init.ref]/5.4.3, DR 1604)
Also note that the rest of [over.ics.ref] gives requirements on the binding of references to influence the viability of an overload, but do not include binding of const rvalues to non-const rvalue references.
This is not a problem in e.g. copy-initialization (Foo foo = bar;), because that can use the conversion operator directly without going through the constructor.
It is also not a problem before C++11, because the move constructor doesn't exist there.
For the same reason it is not a problem if the copy constructor of Foo is explicitly declared, because that would inhibit the declaration of the implicit move constructor.
It is also not a problem in C++17 and later because mandatory copy elision makes it so the move constructor will never be called.
I think this explains all of Clang's behaviors.
GCC and MSVC seem to choose the copy constructor instead of the move constructor in overload resolution, which while apparently not correct by the current wording of the standard, is probably what is intended to happen and what the linked CWG issue aims for, by removing the function overload with the ill-formed reference binding from the set of viable functions.
|
70,653,670 | 70,654,777 | Obtaining decoder MFT for H.264 video | i am trying to get a hardware decoder from media foundation. i know for sure my gpu supports nvdec hardware decoding. i found an example on github which gets the encoder, nvenc without any problem. but when i switch the params to decoder, i either get a bad hresult or a crash. i tried even getting a software decoder by changing the hardware flag, and still bad hresult. any one have an idea what is wrong? i cant think of anything else left for me to try or change
HRESULT get_decoder(CComPtr<IMFTransform>& out_transform, CComPtr<IMFActivate>& out_activate,
CComPtr<IMFAttributes>& out_attributes)
{
HRESULT hr = S_OK;
// Find the decoder
CComHeapPtr<IMFActivate*> activate_raw;
uint32_t activateCount = 0;
// Input & output types
const MFT_REGISTER_TYPE_INFO in_info = { MFMediaType_Video, MFVideoFormat_H264 };
const MFT_REGISTER_TYPE_INFO out_info = { MFMediaType_Video, MFVideoFormat_NV12 };
// Get decoders matching the specified attributes
if (FAILED(hr = MFTEnum2(MFT_CATEGORY_VIDEO_DECODER, MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_SORTANDFILTER, &in_info, &out_info,
nullptr, &activate_raw, &activateCount)))
return hr;
// Choose the first returned decoder
out_activate = activate_raw[0];
// Memory management
for (int i = 1; i < activateCount; i++)
activate_raw[i]->Release();
// Activate
if (FAILED(hr = out_activate->ActivateObject(IID_PPV_ARGS(&out_transform))))
return hr;
// Get attributes
if (FAILED(hr = out_transform->GetAttributes(&out_attributes)))
return hr;
std::cout << "- get_decoder() Found " << activateCount << " decoders" << std::endl;
return hr;
}
| There might be no dedicated decoder MFT for hardware decoding (even though some vendors supply those). Hardware video decoding, in contrast to encoding, is available via DXVA 2 API, and - in turn - is covered by Microsoft H264 Video Decoder MFT.
This stock MFT is capable to decode using hardware and is also compatible with D3D9 and D3D11 enabled pipelines.
Microsoft H264 Video Decoder MFT
6 Attributes:
MFT_TRANSFORM_CLSID_Attribute: {62CE7E72-4C71-4D20-B15D-452831A87D9D} (Type VT_CLSID, CLSID_CMSH264DecoderMFT)
MF_TRANSFORM_FLAGS_Attribute: MFT_ENUM_FLAG_SYNCMFT
MFT_INPUT_TYPES_Attributes: MFVideoFormat_H264, MFVideoFormat_H264_ES
MFT_OUTPUT_TYPES_Attributes: MFVideoFormat_NV12, MFVideoFormat_YV12, MFVideoFormat_IYUV, MFVideoFormat_I420, MFVideoFormat_YUY2
Attributes
MF_SA_D3D_AWARE: 1 (Type VT_UI4)
MF_SA_D3D11_AWARE: 1 (Type VT_UI4)
CODECAPI_AVDecVideoThumbnailGenerationMode: 0 (Type VT_UI4)
CODECAPI_AVDecVideoMaxCodedWidth: 7680 (Type VT_UI4)
CODECAPI_AVDecVideoMaxCodedHeight: 4320 (Type VT_UI4)
CODECAPI_AVDecNumWorkerThreads: 4294967295 (Type VT_UI4, -1)
CODECAPI_AVDecVideoAcceleration_H264: 1 (Type VT_UI4)
...
From MSDN:
CODECAPI_AVDecVideoAcceleration_H264 Enables or disables hardware acceleration.
...
Maximum Resolution 4096 × 2304 pixels
The maximum guaranteed resolution for DXVA acceleration is 1920 × 1088 pixels; at higher resolutions, decoding is done with DXVA, if it is supported by the underlying hardware, otherwise, decoding is done with software.
...
DXVA The decoder supports DXVA version 2, but not DXVA version 1. DXVA decoding is supported only for Main-compatible Baseline, Main, and High profile bitstreams. (Main-compatible Baseline bitstreams are defined as profile_idc=66 and constrained_set1_flag=1.)
To decode with hardware acceleration just use Microsoft H264 Video Decoder MFT.
|
70,653,992 | 70,654,641 | Generate a random prime using c++11 std::uniform_int_distribution | Trying to generate a random prime p in the range [2,2147483647] using the C++11 std::uniform_int_distribution.
It's been commented that this approach might not be correct:
It is not immediately obvious that this p is uniformly distributed
over the set of all primes <= 2^31 - 1. Whatever uniformity and bias
guarantees the random-number generator has, they refer to all integers
within the range, but the code is "sieving" just the primes out of it.
However, from another similar S.O. article, it notes
As long as the input random numbers are uniformly distributed in the
range, the primes chosen by this method will be uniformly distributed
among the primes in that range, too.
Question
Is this code truly correct to generate a random prime?
https://onlinegdb.com/FMzz78LBq
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <random>
int isPrimeNumber (int num)
{
if (num == 1) return 0;
for (int i = 2; i <= sqrt (num); i++)
{
if (num % i == 0)
{
// not prime
return 0;
}
}
// prime
return 1;
}
int main ()
{
std::random_device rd;
std::mt19937 rng (rd ());
// Define prime range from 2 to 2^31 - 1.
std::uniform_int_distribution<int>uni (2, 2147483647);
int prime;
// Generate a random prime.
do { prime = uni(rng); } while (!isPrimeNumber(prime));
printf ("prime = %d", prime);
return 0;
}
| The code you presented:
Uniformly picks a random prime number in the range. Any given prime number in the range will have the same probability of coming up as any other prime in the range.
will not produce numbers that are uniformly distributed around the range of integers. E.g. there will be much more numbers in the range 1-1000 than there will be in the range 1000001-1001000.
is extremely inefficient (if you were to generate many numbers)
You should get clarity on exactly what you want. If you wanted 2. above you need something different.
|
70,654,064 | 70,657,188 | Why does CppCheck flag static constexpr members as unusedStructMember, when it is used later in the struct definition | CppCheck is flagging the definition of BufLen as an unusedStructMember, even though it is used on the next line to define the length of the array.
(style) struct member 'TxDetails_t::BufLen' is never used. [unusedStructMember]
static struct TxDetails_t
{
static constexpr int32_t BufLen = 128;
uint8_t buffer[BufLen];
uint8_t* ptr;
int32_t num_bytes;
} TxData;
Is CppCheck wrong to report this, or is there a better way for me to define this struct?
| This is indeed a false positive and it is fixed in the upcoming Cppcheck 2.7. I can reproduce it with 2.6 but not with the latest head.
Looking at the list of fixed issues it appears you encountered https://trac.cppcheck.net/ticket/10485.
|
70,654,703 | 70,664,957 | Passing a c# array of object to COM interface method | I should pass a pointer of object array to a COM interface with the following IDL and C++ definitions:
C++ code:
UpdateItem( LONG lID, LONG lNumOfFields, FieldIdEnum* pFields, VARIANT* pvValues )
IDL:
HRESULT UpdateItem( [in] LONG lID, [in] LONG lNumOfFields, [in, size_is(lNumOfFields)] FieldIdEnum* pFields, [in, size_is(lNumOfFields)] VARIANT* pvValues );
tlbimp generated C# code:
UpdateItem([In] int lID, [In] int lNumOfFields, [In] ref FieldIdEnum pFields, [In][MarshalAs(UnmanagedType.Struct)] ref object pvValues);
... and I try to call with:
FieldIdEnum[] fieldIDs = { FieldIdEnum.fi1ID, FieldIdEnum.fi2At };
object[] values = { 3, DateTime.UtcNow };
mi.UpdateItem(1, 2, ref fieldIDs[0], ref values[0]);
I get this interface from my system as result of login and authentication process... The UpdateItem method is a public member of that interface.
I want to pass two or more field and value pairs (in same time) by the two array.
The field array always is passed correctly to C++ code. I have debugged C++ code and the "FieldIdEnum* pFields" represents the first element of an integer array and the 2nd element (pFields1) is correct too. The pField[] is a c-style array.
But the 2nd array is a variant array with various element type in this case an integer and a date time. This appears as a SafeArray at c++ side instead of c_style array. I have checked this 2nd array too, it is a simple variant array if the method calling starts from another C code, but C# tries to marshal it to safearray.
I have changed the C# definition to
UpdateItem([In] int lID, [In] int lNumOfFields, [In] ref FieldIdEnum pFields, [In] ref object pvValues);
It does not work I always get an exception like "Value does not fall within the expected range." "System.Exception {System.ArgumentException}"
I have tried to use/marshal various managed/unmanaged types and Intptr, did not work.
I have found an other topic with same/similar problem, I could not make it work.
How should I pass a pointer of object array to COM interface?
| I have found the solution.
I have redefined the interface method:
void UpdateItem([In] int lID, [In] int lNumOfFields, [In] ref FieldIdEnum pFields, [In][MarshalAs(UnmanagedType.LPArray)] object[] pvValues);
... and call this as:
FieldIdEnum[] updateFieldIDs = { FieldIdEnum.fi1ID, FieldIdEnum.fi2At };
object[] values = { 3, DateTime.UtcNow };
mi.UpdateItem(id, updateFieldIDs.Length, ref updateFieldIDs[0], values);
Thank you for guidance.
|
70,654,795 | 70,655,355 | Why doesn't C++ automatically throw an exception on arithmetic overflow? | The C++ Standard at some point states that:
5 Expressions [expr]
...
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows...]
I'm trying to understand why most(all?) implementations choose to ignore overflows rather than doing something like throwing an std::overflow_error exception. Is it not to incur any additional runtime cost? If that's the case, can't the underlying arithmetic processing hardware be used to do that check for free?
|
If that's the case, can't the underlying arithmetic processing hardware be used to do that check for free?
Raising an exception always has a cost. But perhaps some architectures can guarantee that when an exception is not raised, then the check is free.
However, C++ is designed to be efficiently implementable on a wide range of architectures. It would violate the design principles of C++ to mandate checking for integer overflow, unless all architectures could support such checks with zero cost in all cases where overflow does not occur. This is not the case.
|
70,654,850 | 70,655,222 | Big Integer Class C++ | I'd like to write an unsigned Big Int library in C++ as an exercise, however I would like to stay away from using the traditional vector of chars storing individual digits. Due to the amount of memory wasted by this approach.
Would using a vector of unsigned short ints (ie. 16 bit postive integers) work, or is there a better way of doing this?
To Clarify, I would store "12345678" as {1234, 5678}.
| Storing digits in corresponding chars is certainly not traditional, because of the reason you stated - it wastes memory. Using N-bit integers to store N corresponding bits is the usual approach. It wastes no memory, and is actually easier to implement (though harder to debug, because the integers are typically large).
Yes, using unsigned short int for individual units of information (generalized "digits") is a good idea. However, consider using 32-bit or 64-bit integers - they are closer to the size of the CPU registers, so your implementation will be more efficient.
General idea of syntax:
class BigInt
{
private:
std::vector<uint64_t> digits;
};
You should decide whether you store least significant digits in smaller or larger indices. I think smaller is better (because addition, subtraction and multiplication algorithms start from LSB), but it's your choice.
|
70,655,605 | 70,655,966 | Is there any performance benefit capturing only needed variables in scope in a lambda expression with [&var] instead of capturing all with [&]? | Or does it make any difference at all, because unused references are optimized away by the compiler?
"When a lambda definition is executed, for each variable that the lambda captures, a clone of that variable is made (with an identical name) inside the lambda. These cloned variables are initialized from the outer scope variables of the same name at this point."
ref: https://www.learncpp.com/cpp-tutorial/lambda-captures/.
I suppose the clone takes time also?
| The way the compilers I am familiar with implement closures is to effectively create a struct of all the captures and pass a pointer to the struct as a parameter to the function. The compiler will only add to the struct those captures explicitly listed, and in the case of the general capture, only those visible variables that are actually used in the body of the lambda.
So in short, explicitly listing the captures for a lambda is possibly a pessimization since it might copy more values than are strictly necessary. The optimizer can and does eliminate some unused captures or change them from by-reference to by-value when it can do so.
By the time the optimizer has done its job you're unlikely to notice any performance penalty even in tight inner loops. You are better off making your captures explicit because it expresses intent and that's the expensive part of software development.
|
70,655,695 | 70,657,229 | How to define struct field type in Metal Shading Language? | It is not clear how to define ref or ptr type of struct field?
struct uint128_t {
uint64_t lo;
uint64_t hi;
device uint64_t& operator[](int i) {
return (i == 0) ? lo : hi;
}
...
}
Reference to type 'device uint64_t' (aka 'device unsigned long') could not bind to an lvalue of type 'uint64_t' (aka 'unsigned long')
| You need to specify an address space for the function itself. Otherwise, you can't use address-space specific stuff.
Here's the right definition:
struct uint128_t {
uint64_t lo;
uint64_t hi;
device uint64_t& operator[](int i) device {
return (i == 0) ? lo : hi;
}
};
|
70,655,807 | 70,656,214 | Program compiles, but cannot run because of missing library that exists | I have an OpenGL program. I have all the include directories, and everything.
Directory Structure:
Main.cpp
Lib/
GL/
GLEW/
glm/
I compile the program by running:
g++ main.cpp -lGL -lm -lX11 -lpthread -lXi -lXrandr -ldl -I. -lglfw -Llib/ -o main -lGLEW
The error is on -lGLEW. The program compiles with no errors, but when I run ./main, it gives me this:
Error while loading shared libraries: libGLEW.so.2.2: No such file or directory.
This is confusing, as in my lib/ directory, libGLEW.so.2.2 is present, so is libGLEW.so and libGLEW.a.
Can someone please help me?
| When running a dynamic linked executable, the linker must be able to find all the libraries it needs. It always searches
a list of fixed default paths like /lib and /usr/lib
additional paths defined by the environment variable LD_LIBRARY_PATH
any non-standard paths hard-coded in the binary by the -Wl,-rpath g++ option.
These are your options for making this non-standard library known to the runtime linker.
So either use export LD_LIBRARY_PATH=<somepath>/lib when running or use -Wl,-rpath=<somepath>/lib (with comma and without spaces) when building.
|
70,655,977 | 70,656,381 | C++ map with adjacent_difference | Really confused by some errors I'm getting related to using a std::map container with a call to std::adjacent_difference. The documentation for adjacent_difference says the following about defining a custom operator:
op - binary operation function object that will be applied.
The signature of the function should be equivalent to the following:
Ret fun(const Type1 &a, const Type2 &b);
The signature does not need to have const &.
The types Type1 and Type2 must be such that an object of type
iterator_traits::value_type can be implicitly converted to both of them. The
type Ret must be such that an object of type OutputIt can be dereferenced and assigned a
value of type Ret.
So in the following code (snippet), I have a lambda that returns an integer to a final container to hold the differences between values stored in the map.
std::map<char, int> m;
// Do stuff to initialize map contents here
// ...
std::vector<int> d;
typedef std::pair<char, int> P;
std::adjacent_difference(m.begin(), m.end(), std::back_inserter(d),
[](const P & a, const P & b)->int { return std::abs(a.second - b.second);}
);
And I get some error that is clearly referring to an invalid assignment made between a pair and an integer. Not how I interpreted the documentation, and I'm not sure what I'm missing. I thought the documentation was pretty clear in saying the return value of the lambda is assigned to the result container, but clearly that is not what's happening?
/usr/local/include/c++/8.3.0/bits/stl_numeric.h:374:17: error: no match for ‘operator=’ (operand types are ‘std::back_insert_iterator<std::vector<int> >’ and ‘_ValueType’ {aka ‘std::pair<const char, int>’})
*__result = __value;
~~~~~~~~~~^~~~~~~~~
Have I crossed my wires somewhere else?
| Studying the cppreference link you provided shows that std::adjacent_difference() cannot transform its output to a type different from the input:
both acc (the accumulated value) and the result of val - acc or
op(val, ACC) <...> must be writable to OutputIt.
So, to use algorithms, you would first need to use std::transform() to convert the map into std::vector<int>, and next use std::adjacent_difference(). But a manual loop will probably make more sense.
|
70,657,424 | 70,657,492 | What is meant by a "Relative Comparison" and an "Absolute Comparison"? | Quoting from this article:
REAL NUMBERS
Binary search can also be used on monotonic functions whose domain is
the set of real numbers. Implementing binary search on reals is
usually easier than on integers, because you don’t need to watch out
for how to move bounds:
binary_search(lo, hi, p):
while we choose not to terminate:
mid = lo + (hi - lo) / 2
if p(mid) == true:
hi = mid
else :
lo = mid
return lo
Since the set of real numbers is dense, it should be clear that we
usually won’t be able to find the exact target value. However, we can
quickly find some x such that f(x) is within some tolerance of the
border between no and yes. We have two ways of deciding when to
terminate: terminate when the search space gets smaller than some
predetermined bound (say 10-12) or do a fixed number of iterations. On
Topcoder, your best bet is to just use a few hundred iterations, this
will give you the best possible precision without too much thinking.
100 iterations will reduce the search space to approximately 10-30 of
its initial size, which should be enough for most (if not all)
problems.
If you need to do as few iterations as possible, you can terminate
when the interval gets small, but try to do a relative comparison of
the bounds, not just an absolute one. The reason for this is that
doubles can never give you more than 15 decimal digits of precision so
if the search space contains large numbers (say on the order of
billions), you can never get an absolute difference of less than 10-7.
The last paragraph suggests doing a relative comparison, and not just an absolute one. What does that mean?
| The last paragraph explains the issue with using the absolute difference:
If you need to do as few iterations as possible, you can terminate when the interval gets small, but try to do a relative comparison of the bounds, not just an absolute one. The reason for this is that doubles can never give you more than 15 decimal digits of precision so if the search space contains large numbers (say on the order of billions), you can never get an absolute difference of less than 10-7.
The absolute difference between a and b is
auto diff = std::abs(a - b);
if (diff < 0.00000001) break;
As floating point numbers have only limited number of significant digits, with large absolute values you may never see an absolute difference as small as 1e-7.
Relative difference does not depend on the magnitude of the compared values:
auto rel_diff = std::abs( a - b) / a;
if (rel_diff < 0.00000001) break;
In other words, typically the following evaluates to true:
double very_big_number = 100000000.0;
double very_small_number = 0.000000001;
auto ups = (very_big_number + very_small_number) == very_big_number;
The smallest difference you can meaningfully expect from two big floating point numbers is in their last significant digit, which can be much larger in magnitude than eg 1e-7.
|
70,657,844 | 70,668,801 | Using 3rd Party Shared Object Library and header files in CMake | I am trying to use this ZED Open Capture library for using the ZED Mini camera for my project on RaspberryPi. I succesfully installed the library and the shared object file is at /usr/local/lib/libzed_open_capture.so and the include headers are at the location /usr/local/include/zed-open-capture/.
To include this library I am adding the following lines to my CMakeLists.txt
find_library(ZED_LIB zed_open_capture)
include_directories("/usr/local/include/zed-open-capture/")
add_executable(zed_pub src/zed_pub.cpp)
target_link_libraries(zed_pub ${ZED_LIB})
Now when I use this code , it shows this error "‘sl_oc::video’ has not been declared"
#include "videocapture.hpp" //Library Header File
sl_oc::video::VideoCapture cap;
cap.initializeVideo();
const sl_oc::video::Frame frame = cap.getLastFrame();
Can someone please explain me how a Shared Object Library file along with header files should be used in CMake? The library has already been installed using CMake build and sudo make install on my Linux system.
The github repo of the library is at https://github.com/stereolabs/zed-open-capture
Also I cannot find Find_PKG_name.cmake so I cannot use find_package() option.
| videocapture.hpp wraps the definitions you need inside #ifdef VIDEO_MOD_AVAILABLE. It seems likely that this is not defined. The root CMakeLists.txt in the ZED package defaults BUILD_VIDEO to ON, so this was likely all defined for the package build. But as others have pointed out, the package does not persist this information anywhere in the installation. The "right" way for the package to do it would be EITHER to configure/modify the include files at install time to account for the build configuration, probably by generating a "config.hpp" file with the appropriate definitions. OR to include a zed-config.cmake file in the installation, with all the necessary imports and definitions.
Your short-circuit solution should be fine. Just add target_compile_definitions(zed_pub PUBLIC VIDEO_MOD_AVAILABLE). If you want to do it more cleanly for the future, create an IMPORTED target for zed_lib, and set both the include_directories and compile_definitions on that target, so that all users of the library get this defined automatically.
|
70,658,037 | 70,658,859 | Problem understanding the behaviour of std::map try_emplace for a composite key | I have a std::map<CompositeKey, std::string>, where CompositeKey is a class I wrote.
This CompositeKey has three int data members, all the constructors, all the copy assignment operators and a friend bool operator<, which compares the sum of the three data members.
I understood how to use emplace and emplace_hint.
For example:
// emplace
std::map<CompositeKey, std::string> my_map;
int first_id = 10, second_id = 100, third_id = 1000;
std::string my_string = "foo";
auto [ insertedIt, success ] = my_map.emplace(std::piecewise_construct,
std::forward_as_tuple(first_id, second_id, third_id),
std::forward_as_tuple(my_string));
// emplace_hint
first_id = 5, second_id = 50, third_id = 500;
my_string = "bar";
std::tie(insertedIt, success) = my_map.emplace_hint(insertedIt
std::piecewise_construct,
std::forward_as_tuple(first_id, second_id, third_id),
std::forward_as_tuple(my_string));
The only way I was able to use try_emplace was in the version without hint:
first_id = 1, second_id = 10, third_id = 100;
my_string = "foobar";
std::tie(insertedIt, success) = my_map.try_emplace({first_id, second_id, third_id},
my_string);
My questions are:
Is this the only way to call try_emplace, without hint? If not, how could I call it?
How could I call the try_emplace version with a hint? I made some attempts but always failed.
Is it correct to assume that try_emplace "move" or "copy" the CompositeKey inside the map? I am asking about the behaviour of try_emplace both because I read something similar on another discussion, and because I wrote a verbose copy and move constructors to make a test.
I am sorry, I made my research but do not understand these points from the cppreference documentation
| I think you may be misunderstanding the cppreference documentation. In your code, you are always trying to add a key that is not in the map. And you are passing that key as an lvalue reference. The only difference with your two cases is that you are using a hint in the second call. So the two try_emplace versions you are using, according to cppreference, are 1 and 3.
template< class... Args > pair<iterator, bool> try_emplace( const Key& k, Args&&... args ); (1) (since C++17)
template< class... Args > iterator try_emplace( const_iterator hint, const Key& k, Args&&... args ); (3) (since C++17)
Notice:
Both versions receive the key as an lvalue reference (Key&).
First version returns a pair<iterator, bool, but second version just returns an iterator.
Now, the text below doesn't tell how you have to build your try_emplace arguments; instead, it says what try_emplace is doing internally.
1) If a key equivalent to k already exists in the container, does nothing.
Otherwise, behaves like emplace except that the element is constructed as
value_type(std::piecewise_construct,
std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...))
In short, just call try_emplace passing a CompositeKey object and a string as arguments (and, optionally, an iterator as a hint). The code below calls try_emplace with an lvalue and an rvalue (the second call with a hint), so it would use the versions 1 and 4.
[Demo]
std::map<CompositeKey, std::string> my_map;
std::cout << "Case 1:\n";
auto key1{CompositeKey{10, 100, 1000}};
auto value1{std::string{"foo"}};
auto [insertedIt, success] = my_map.try_emplace(key1, value1);
std::cout << "Case 2:\n";
insertedIt = my_map.try_emplace(insertedIt, {5, 50, 500}, "bar");
// Outputs:
//
// Case 1:
// custom ctor
// copy ctor
// Case 2:
// custom ctor
// move ctor
Is it correct to assume that try_emplace "move" or "copy" the CompositeKey inside the map?
Whatever you pass is forwarded to try_emplace implementation. In the example above, both CompositeKey arguments are first "custom constructed" ; then, they are passed to try_emplace, where the lvalue is copy constructed while the rvalue is move constructed.
|
70,658,493 | 70,658,773 | Program not showing the values inserted in a binary search tree | I have tried writing a code to implement a binary search tree, however when I run my code outputs nothing and closes a program. I think my insert function is correct since I wrote cout<<"yes" at multiple places in the insert function, and to show all the nodes of the binary search tree I have used in order traversal which is done recursively inside a simple function.
Here is my code:
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *right;
Node *left;
};
void insert(Node **root_ref, int value)
{
Node *temp = new Node();
temp->data = value;
temp->right = NULL;
temp->left = NULL;
Node *current = *root_ref;
if (*root_ref == NULL)
{
*root_ref = temp;
return;
}
while (current != NULL)
{
if ((temp->data < current->data) && (current->left == NULL))
{
current->left = temp;
return;
}
else if ((temp->data > current->data) && (current->right == NULL))
{
current->right = temp;
return;
}
else if ((temp->data > current->data))
{
current = current->right;
}
else
{
current = current->left;
}
}
}
void printinorder(Node *root1)
{
printinorder(root1->left);
cout << " " << root1->data << " ";
printinorder(root1->right);
}
int main()
{
Node *root = NULL;
insert(&root, 60);
insert(&root, 50);
insert(&root, 70);
insert(&root, 30);
insert(&root, 53);
insert(&root, 80);
insert(&root, 65);
printinorder(root);
}
| For starters the function insert can produce a memory leak when a value is added to the tree when there is already a node with the same value because in this case only this else statement can be evaluated
while (current != NULL)
{
//...
else
{
current = current->left;
}
}
So the loop will end its iterations and nothing will be added to the tree though a node was already allocated.
The function can be written for example the following way
void insert( Node **root_ref, int value )
{
Node *temp = new Node { value, nullptr, nullptr };
while ( *root_ref != nullptr )
{
if ( ( *root_ref )->data < value )
{
root_ref = &( *root_ref )->right;
}
else
{
root_ref = &( *root_ref )->left;
}
}
*root_ref = temp;
}
In the recursive function printinorder
void printinorder(Node *root1)
{
printinorder(root1->left);
cout << " " << root1->data << " ";
printinorder(root1->right);
}
you are not checking whether the passed argument is equal to nullptr. So the function invokes undefined behavior.
The function can be written the following way
std::ostream & printinorder( const Node *root, std::ostream &os = std::cout )
{
if ( root != nullptr )
{
printinorder( root->left, os );
os << " " << root->data << " ";
printinorder( root->right, os );
}
return os;
}
|
70,658,717 | 70,659,283 | How do I sort a vector of pairs by both of the values rather than just the second one? | What I am looking to do is sort a vector of pairs in a way where the first value is lowest to greatest and the second being greatest to lowest and having priority over the first value ordering whilst keeping them together. For example, let's say I had this code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
pair<int, double> p;
vector<pair<int, double> > vp;
p.first = 2;
p.second = 2.4;
vp.push_back(p);
p.first = 9;
p.second = 3.0;
vp.push_back(p);
p.first = 10;
p.second = 3.1;
vp.push_back(p);
p.first = 1;
p.second = 2.4;
vp.push_back(p);
p.first = 5;
p.second = 3.1;
vp.push_back(p);
}
if I were to print it out via loop I'd want it to go from outputting this:
2, 2.4
9, 3.0
10, 3.1
1, 2.4
5, 3.1
to outputting this
5, 3.1
10, 3.1
9, 3.0
1, 2.4
2, 2.4
Now imagine if those values weren't given manually but instead they were random and being randomized over a for loop that loops a random amount of times from between 0 and 100 inclusive each time the code is run, each new random value of both sides of the pair being stored in the vector (which would give the vector a size of 10.)
How do I sort out the vector so it would have output that is ordered the same as the above example?
| The simplest way is to use the standard functions std::sort() and std::tie().
Here is a demonstration program:
#include <iostream>
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::pair<int, double>> v =
{
{ 2, 2.4 },
{ 9, 3.0 },
{ 10, 3.1 },
{ 1, 2.4 },
{ 5, 3.1 }
};
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) < std::tie( p1.second, p2.first );
} );
for (const auto &p : v)
{
std::cout << p.first << ' ' << p.second << '\n';
}
}
The program output is:
5 3.1
10 3.1
9 3
1 2.4
2 2.4
|
70,658,753 | 70,660,089 | Iterating vector-based priority_queue | I need to iterate over std::vector-based priority_queue. As many answers here suggest, I can inherit from priority_queue and access underlying container (std::vector in my case).
Is it guaranteed that priority_queue elements are stored starting from element 0 of the underlying vector and that vector size equals queue size?
PS. I am iterating regardless of priority, so I iterate: for (int i = 0; i < c.size(); ++i)...
| In short, yes.
The standard [priqueue.members] defines the operators on a priority queue in terms of push/emplace/pop_back and heap operations. It is trivial to see that the size of the underlying container will be equal to the size of the priority queue, and that elements will be stored starting from the beginning of the container.
In fact, the standard even guarantees that the underlying container will be a heap as defined by the standard make_heap algorithm.
That said, it is likely worth considering whether or not priority_queue is the best solution for your problem if iteration is required.
|
70,659,217 | 70,659,632 | Exactly which parts of the standard require this breaking change involving operator <? | A change was made in C++20, and I'm having a hard time finding where in the standard I can go look to learn that this change happened. Would someone please quote me the section of the standard that tells me this will happen?
I am aware of this question: Breaking change in std::tuple lexicographic comparison in C++20 with conversion operators?
but it does not answer the question about where I can find this out in the standard.
With both gcc 11.2 and clang this code prints out 01 (the expected result) with -std=c++17 and 10 with -std=c++20. Is this correct behavior? If it is, where in the standard should I look to find out why?
#include <iostream>
struct S {
int a;
S( int a ) : a( a ){ }
operator
int() const {
return a;
}
friend bool
operator<( const S & lhs, const S & rhs ){
return lhs.a > rhs.a;
}
};
int
main(){
std::pair< int, S > p1{ 0, 1 }, p2{ 0, 2 };
std::cout << (p1 < p2) << (p2 < p1) << std::endl;
}
| In C++17, [pairs.spec] defined all the relational operators. For instance, operator< was specified as:
template <class T1, class T2>
constexpr bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y);
Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second).
In C++20, with the adoption of <=>, this looks a bit different. Also in [pairs.spec]:
template<class T1, class T2>
constexpr common_comparison_category_t<synth-three-way-result<T1>,
synth-three-way-result<T2>>
operator<=>(const pair<T1, T2>& x, const pair<T1, T2>& y);
Effects: Equivalent to:
if (auto c = synth-three-way(x.first, y.first); c != 0) return c;
return synth-three-way(x.second, y.second);
Where synth-three-way(x, y) will do x <=> y if possible, otherwise do x < y and then y < x (see [expos.only.func]).
The issue here is that x <=> y for your type is actually valid, but does something different from x < y, so you get a different result.
|
70,659,577 | 70,659,908 | How to find a substring in only a portion of a std::string? | I have a std::string and i want to be able to find text only in a section of it : so i need to specify a start and an end position.
In std::string::find() one can only specify the start position.
I am trying to find the best way to search only in a portion of haystack. That would consist of giving an end_pos to stop the search even though it doesn't reach the end of haystack.
For example, search only from its 100th character to its 200th character.
Does anybody know how I could achieve this (elegantly)?
only by searching in haystack itself, not in a substr() of it
without creating a copy of haystack
in C++98
| std::string does not have a method that suits your requirement to search a sub-range of the haystack string. Have a look at std::search() for that instead, eg:
std::string needle = ...;
std::string::iterator end_iter = haystack.begin() + end_pos;
std::string::iterator found_iter = std::search(haystack.begin() + start_pos, end_iter, needle.begin(), needle.end());
if (found_iter != end_iter) {
// needle found...
}
else {
// needle not found...
}
If your compiler does not have std::search() available, then just write your own search() function, such as with the implementation provided on cppreference.com, eg:
namespace my {
template<class ForwardIt1, class ForwardIt2>
ForwardIt1 search(ForwardIt1 first, ForwardIt1 last,
ForwardIt2 s_first, ForwardIt2 s_last)
{
while (1) {
ForwardIt1 it = first;
for (ForwardIt2 s_it = s_first; ; ++it, ++s_it) {
if (s_it == s_last) return first;
if (it == last) return last;
if (!(*it == *s_it)) break;
}
++first;
}
}
}
...
std::string needle = ...;
std::string::iterator end_iter = haystack.begin() + end_pos;
std::string::iterator found_iter = my::search(haystack.begin() + start_pos, end_iter, needle.begin(), needle.end());
if (found_iter != end_iter) {
// needle found...
}
else {
// needle not found...
}
|
70,659,585 | 70,661,299 | Avoiding undefined behaviour: passing a temporary to a `std::function` which has a const ref member variable | The following example is a simplified version found in production code
#include <string>
#include <functional>
#include <iostream>
#include <vector>
struct A
{
std::string myString = "World";
};
struct B
{
void operator()()
{
std::cout << a.myString;
}
const A& a;
};
std::vector<std::function<void()>> v;
void Store(std::function<void()> myFunc)
{
v.emplace_back(myFunc);
}
void Print()
{
v[0]();
}
int main()
{
A a; a.myString = "Hello";
Store(B{a}); // temporary passed with a const-ref of on-the-stack `A`
Print();
}
In production code, accessing the string A (i.e. invoking the function through the vector which in turn accesses myString in A) results in a crash. Compiler Explorer seems to be okay with it, however if this behaviour is undefined, the output probably cannot be trusted: https://godbolt.org/z/cPPKeK9zd
Assuming this is undefined behaviour and I can only store a const & to A, what can I do in the Store(...) function to issue a compiler error and try to catch the undefined behaviour at compile time.
| This example has no undefined behavior.
Calling Store copy-initializes the argument of type std::function<void()> from the temporary object of type B. In doing so, std::function uses perfect forwarding to initialize its own internal object of type B, which is therefore move-constructed from the original temporary.
The call to emplace_back copy-constructs the function which therefore copy-constructs the internal object of type B.
That the initial B object is a temporary is irrelevant, as the copy inside the function inside the vector is not. The reference to A inside this B copy still points to the same A object, which is still within its lifetime.
|
70,659,634 | 70,659,957 | Why writing reverse iterator can affect whether an iterator is random-access-iterator or not? | I wanna write a container with random-access-iterator:
#include <cstddef>
#include <iterator>
#include <concepts>
namespace foo
{
struct container
{
struct iter
{
using difference_type = std::ptrdiff_t;
using pointer = int*;
using reference = int&;
using value_type = int;
using iterator_category = ::std::random_access_iterator_tag;
iter& operator++();
iter operator++(int);
iter& operator--();
iter operator--(int);
iter operator+(difference_type) const;
iter operator-(difference_type) const;
iter& operator+=(difference_type);
iter& operator-=(difference_type);
bool operator==(const iter&) const;
bool operator!=(const iter&) const;
bool operator<(const iter&) const;
bool operator>(const iter&) const;
bool operator<=(const iter&) const;
bool operator>=(const iter&) const;
difference_type operator-(const iter&) const;
int& operator*() const;
int& operator[](difference_type) const;
};
// code for reverse iterator, now it is comment out
/* using riter = std::reverse_iterator<iter>;
iter end();
riter rbegin()
{
return std::reverse_iterator(this->end());
}
*/
};
inline container::iter operator+(container::iter::difference_type, const container::iter&);
}
int main(void)
{
static_assert(std::random_access_iterator<foo::container::iter>, "");
return 0;
}
Then I compile it with g++-11 -std=c++20 and it can be compiled successfully.
But if I want to write a reverse iterator for this container, that is, uncomment those code for reverse iterator, there will be a compile error:
<source>:55:2: error: static_assert failed ""
static_assert(std::random_access_iterator<foo::container::iter>, "");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:55:21: note: because 'foo::container::iter' does not satisfy 'random_access_iterator'
static_assert(std::random_access_iterator<foo::container::iter>, "");
^
/opt/compiler-explorer/gcc-11.2.0/lib/gcc/x86_64-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/iterator_concepts.h:669:8: note: because '__n + __j' would be invalid: invalid operands to binary expression ('const iter_difference_t<foo::container::iter>' (aka 'const long') and 'const foo::container::iter')
{ __n + __j } -> same_as<_Iter>;
^
1 error generated.
And I also use Clang 13 but got the same result. So how should I write the iterator correctly?
| The mystery here is why adding a few lines of code that don't alter the definition of foo::container::iter causes the static_assert to fail.
This is because the implementation of std::reverse_iterator's constructor, in the body of the commented function, evaluates concept std::random_access_iterator to determine what sort of reverse iterator to create.
When this happens, operator+(difference_type, iter) hasn't been declared yet because it's further down in your code, so the your container::iter initially fails to satisfy the concept.
Later, you declare the required operator+ and your type now would satisfy concept std::random_access_iterator, were it not for the following part of the standard: [temp.constr.atomic]
... If, at different points in the program, the satisfaction result is different for identical atomic constraints and template arguments, the program is ill-formed, no diagnostic required.
At different points in your code, the concept std::random_access_iterator has different satisfaction results! So your code is ill-formed, no diagnostic required. (GCC does actually diagnose this - clang just gives you the error message from when it first evaluated the concept, which is why you were confused).
You can fix this by moving your declaration of operator+ before using std::reverse_iterator. For example:
struct container {
struct iter {
// all your methods, as before
friend iter operator+(difference_type, iter);
}
using riter = std::reverse_iterator<iter>;
iter end();
riter rbegin();
}
|
70,659,635 | 70,660,299 | Numerical implementation of n-th derivative of f(x)? | I implemented a C++ code to numerically solve the n-th derivative of a function in a point x_0:
double n_derivative( double ( *f )( double ), double x_0, int n )
{
if( n == 0 ) return f( x_0 );
else
{
const double h = pow( __DBL_EPSILON__, 1/3 );
double x_1 = x_0 - h;
double x_2 = x_0 + h;
double first_term = n_derivative( f, x_2, n - 1 );
double second_term = n_derivative( f, x_1, n - 1);
return ( first_term - second_term ) / ( 2*h );
}
}
I was wondering if this is for you a good implementation or if there can be a way to better write it in C++. The problem is that I noticed that the n-th derivative diverges for values of n higher than 3. Do you know how to solve this?
| It is not a good implementation
At least these problems.
Integer math
Use FP math as 1/3 is zero.
1/3 --> 1.0/3
Using the cube root optimal for n==1
But not certainly other n. @Eugene
Wrong epsilon
Below code is only useful for |x_0| about 1.0. When x_0 is large, x_0 - h may equal x_0. When x_0 is small, x_0 - h may equal -h.
OP's +/- some epsilon is good for fixed point, but double is a floating point.
// Bad
const double h = pow( __DBL_EPSILON__, 1.0/3 );
double x_1 = x_0 - h;
A relative scaling is needed.
#define EPS cbrt(DBL_EPSILON) // TBD code to well select this
if (fabs(x_0) >= DBL_MIN && isfinite(x_0)) {
double x_1 = x_0*(1.0 - EP3);
double x_2 = x_0*(1.0 + EPS);
double h2 = x_2 - x_1;
...
} else {
TBD_Code for special cases
}
Invalid code
f is double ( *f )( int, double ), but call is f( x_0 )
Minor: confusing names
Why first_term with x_2 and second_term with x_1?
|
70,659,662 | 70,683,799 | Visual Studio 2019 C++ project error "A dependent dll was not found", how to know which dll is not found | I found several others are puzzled by this matter as well, but no answer is satisfying. I am inheriting a big C++ program set up in Visual Studio 2019, it builds fine, but when running it, the studio complains "A dependent dll was not found" without any other useful info.
Is there anyway to know which dll is needed, or even which symbols are not found?
Any advice would be greatly appreciated.
| Using Dependency Walker, I have identified the missing DLL. It does not require installation, very good to use.
|
70,660,208 | 70,660,246 | Access from multiple source files to one struct array | I tried to upgrade my "working code" with a new function. For this I tried to outsource some functionality into separate files.
At the moment I'm not sure what to do and I can't find a solution for the problem.
The code below is only a little part of the code, but I hope it is enough to explain what is going wrong.
I need a global struct array as shown below in global_def.
I need access to the same data field from different files (functions).
If I do it in this way, I get the following error:
error: invalid use of incomplete type 'struct resultFieldColor
setFieldColor(fieldNr , resultFieldColorArray[fieldNr].resultHue , resultFieldColorArray[fieldNr].resultSaturation, resultFieldColorArray[fieldNr].reusltBrightness , ledCounter)
global_def.h
#ifndef GLOBAL_DEF_H
#define GLOBAL_DEF_H
struct resultFieldColor;
extern resultFieldColor resultFieldColorArray[];
global_def.cpp
struct resultFieldColor
{
byte resultHue = 0;
byte resultSaturation = 0;
byte reusltBrightness = 0;
};
resultFieldColor resultFieldColorArray[5];
colorFuncOne.cpp
#include <GLOBAL_DEF.h>
#include <LED_control.h>
setFieldColor(fieldNr , resultFieldColorArray[fieldNr].resultHue , resultFieldColorArray[fieldNr].resultSaturation, resultFieldColorArray[fieldNr].reusltBrightness , ledCounter);
colorFuncTwo.cpp
#include <GLOBAL_DEF.h>
#include <LED_control.h>
setFieldColor(fieldNr , resultFieldColorArray[fieldNr].resultHue , resultFieldColorArray[fieldNr].resultSaturation, resultFieldColorArray[fieldNr].reusltBrightness , ledCounter);
| The struct's layout has to be included in the header file.
struct ResultFieldColor {
byte resultHue = 0;
byte resultSaturation = 0;
byte resultBrightness = 0;
};
You may have heard people say not to do this. What they meant was that function implementations shouldn't be in the header, so if you have a function foo, the header should look like
void foo(int x);
and the C++ file should have the body, as
void foo(int x) {
// Look at me, I'm a function ^.^
}
But structs/classes need to have their layout available in the header. That includes any function declarations (though not their definitions), any template functions (definitions and declarations), and any instance variables.
Note that there are some tricks to work around this, but they tend to be complicated and carry runtime implications, so it's best to simply include the variables in the header file generally.
|
70,660,488 | 70,673,863 | why are RTLD_DEEPBIND and RTLD_LOCAL not preventing collision of static class member symbol | I am trying to write a simple plugin system for an application and would like to prevent plugins from stomping on each others symbols, however RTLD_DEEPBIND and RTLD_LOCAL don't seem to be enough when it comes to static class members when they happen to have the same name in different plugins.
I wrote a stripped down example to show what I mean.
I compiled and ran it like this:
g++ -c dumb-plugin.cpp -std=c++17 -fPIC
gcc -shared dumb-plugin.o -o dumb1.plugin
cp dumb1.plugin dumb2.plugin
g++ main.cpp -ldl -o main
./main
And the content of the output file for the second plugin showed that it reused the the class from the first plugin.
How can I avoid this?
EDIT: I compiled the plugin with clang(not main just the plugin) and it worked despite all of the RTLD_DEEPBIND stuff being in main.cpp which was still compiled with g++. It didn't work when the plugin was compiled with gcc 10.3 or 11.1 even when I tried -Bsymbolic. Is this a bug?
If I run readelf on the DSO compiled/linked with clang i see these 2 lines:
21: 00000000000040b0 4 OBJECT UNIQUE DEFAULT 26 _ZN9DumbClass7co[...]_ZN9DumbClass7co[...]
25: 00000000000040b0 4 OBJECT UNIQUE DEFAULT 26 _ZN9DumbClass7co[...]
and with gcc i get:
20: 00000000000040a8 4 OBJECT WEAK DEFAULT 24 _ZN9DumbClass7co[...]
27: 00000000000040a8 4 OBJECT WEAK DEFAULT 24 _ZN9DumbClass7co[...]
with WEAK instead of UNIQUE under the BIND column.
dumb-plugin.cpp:
#include <dlfcn.h>
#include <cstdio>
#include <string>
int global_counter = 0;
static int static_global_counter = 0;
std::string replace_slashes(const char * str) {
std::string s;
for (const char* c = str; *c != '\0'; c++)
s += (*c == '/')?
'#' : *c;
return s;
}
void foo() {}
class DumbClass {
public:
static inline int counter = 0;
};
extern "C" void plugin_func() {
static int static_local_counter = 0;
Dl_info info;
dladdr((void*)foo, &info);
std::string path = "plugin_func() from: " + replace_slashes(info.dli_fname);
auto fp = std::fopen(path.c_str(), "w");
fprintf(fp, "static local counter: %d\n", static_local_counter++);
fprintf(fp, "DumbClass::counter: %d\n", DumbClass::counter++);
fprintf(fp, "global counter: %d\n", global_counter++);
fprintf(fp, "static global counter: %d\n", static_global_counter++);
std::fclose(fp);
}
main.cpp:
#include <dlfcn.h>
#include <iostream>
#include <unistd.h>
#include <string.h>
int main () {
char path1[512], path2[512];
getcwd(path1, 512);
strcat(path1, "/dumb1.plugin");
getcwd(path2, 512);
strcat(path2, "/dumb2.plugin");
auto h1 = dlopen(path1, RTLD_NOW | RTLD_LOCAL | RTLD_DEEPBIND);
auto h2 = dlopen(path2, RTLD_NOW | RTLD_LOCAL | RTLD_DEEPBIND);
auto func = (void(*)()) dlsym(h1, "plugin_func");
func();
func = (void(*)()) dlsym(h2, "plugin_func");
func();
}
| gcc implements static inline data members (and also static data members of class templates, inline or not, and static variables in inline functions, and perhaps other things as well) as global unique symbols (a GNU extension to the ELF format). There is only one such symbol with a given name per process, by design.
clang implements such things as normal weak symbols. These will not collide when RTLD_LOCAL and RTLD_DEEPBIND are used.
There are several ways to avoid collisions, but all of them require plugin writers to take an action. The best way IMO is to use hidden symbol visibility by default, only opening symbols that are meant to be dlsymd.
|
70,660,622 | 70,663,950 | Am I using isalpha() function in c++ correctly? | I am working on a program that has a registry system where you can register new members.
To give some context, the name you register has to be different than existing names, can only be one word, and is turned into all caps before being saved to a file. To avoid potential mistakes in file handling, I only want the usernames to be letters, no numbers or special characters.
Because I want to avoid leading and trailing white space the user may accidentally enter, I decided to store the new username being registered into a char array newName, but I just cannot figure out how to properly go through the char array to check for any numbers or special characters so I can ask the user to enter a proper username instead. I've tried using different loop variations with isalpha() function but haven't found anything yet.
Here is that section of my code, which as of now only says "sorry, wrong username" no matter if I enter a username with numbers/special characters or just letters:
char newName[80];
bool valid;
do {
valid = true;
std::cin >> newName;
std::cin.sync();
for (int i = 0; i < 80; i++) {
if (!std::isalpha(newName[i]))
valid = false;
else
valid = true;
}
if (!valid)
std::cout << "Sorry, wrong username." << std::endl;
} while (!valid);
for (int i = 0; i < 80; i ++) {
if (newName[i] != '\0')
newName[i] = toupper(newName[i]);
else
break;
}
for (int i = 0; i < nameList.size(); i++) {
if (nameList.at(i) == newName) {
std::cout << "Sorry, this name already exists. If you are registering a new member, please enter a new name for them." << std::endl;
validName = false;
break;
}
if (nameList.at(i) != newName)
validName = true;
}
| The main problem is that you use C-Style char[] for strings. In C++, we use the datatype std::string for strings. std::string is that superior compared to-Style strings, that it is hard to understand, why anybody wants still to use the old stuff.
As a consequence you have the problems that you are facing now. You are using a magic constant 80 for the definition of your char array. You also use the number 80 hardcoded in the loops, so that if you change the 80 in one place, you might forget it in other places. And run into trouble.
Then, next, and that is the root cause of your problems, what will happen, if you enter shorter names than 80 charachters.
Example: You enter 'Mike'. This are 4 letters and a trailing 0. So, overall 5 characters. After this 5 letters there will be random garbage at the remaining array positions after this 5 relevant letters.
But your loop runs always until 80. So, after having check the first few correct characters you will continue to check garbage. And then you get random results in your first loop.
If you want to fix that, then you should also use the C-Style strlen function, to get the length of the string. And then you should loop up to this value.
Something like:
int length = strlen(newName);
for (int i = 0; (i < length) and (i < 80); i++) {
This will solve your problem.
But again the recomendation: Please consider using std::string
|
70,660,624 | 70,661,537 | How to mark a variable as initialized at the language level? | I am using a linked C-library to get values into a variable.
void f_wrapper(int& v){
auto s = f_legacy(&v);
if(s != success) throw std::runtime_error{};
}
...
int value; // clang-tidy complains here: using "variable 'value' is not initialized"
f_wrapper(value);
However, clang-tidy complains here: using "variable 'value' is not initialized".
As far as understand, this is simply because the compiler cannot see through the linked function.
I don't want to do int value = 0 (because I trust that the library will initialize value and I believe in "partially formed" values.)
Also, I am looking not to add // NOLINT(warning) just to suppress the warning.
(The pattern repeats often.)
Is there something I could do mark value as initialized in the language?
I am looking for something like:
void f_wrapper(int& v) {
auto s = f_legacy(&v);
if(s != success) throw std::runtime_error{};
[[mark initialized(v)]];
}
Worst case I can do this inside the wrapper, because at least I don't see the unnecessary initialization the main code, but it is very cumbersome in cases where arrays are initialized. Also I don't want to pay the prize of this initialization or choose a default value.
void f_wrapper(int& v) {
v = int{}; // initialize to suppress warning at high level code
auto s = f_legacy(&v);
if(s != success) throw std::runtime_error{};
}
| It's not what you want to hear, but there's really only one way to initialize a variable "at the language level" in standard C++ -- and that's to initialize it. It really is that straight-forward. You're basically stuck with either this, or NOLINTing it, as you've already described in your question. It's not a glamorous solution, and it's not what you're after; but there really aren't any better ways.
I'm sure there may be ways to "trick" the tooling into thinking it's initialized, but any such suggestions would amounts to hacks at best.
That said; assuming the clang-tidy check causing grief is the cppcoreguidelines-init-variables rule, it's worth noting that this only triggers for integers, booleans, floats, doubles, and pointers -- and the cost to default-initialize such a value is generally negligible. Unless you've benchmarked this cost and found default-initializing this to be a true bottleneck, there's very little reason to avoid this practice.
In general, initializing the variable is the cleanest / safest way to silence this issue, and is ultimately the best practice anyway. Without initializing, all it takes is a small bug in f_legacy to cause unexpected UB. If f_legacy has any bugs such that it returns success but forgets to set a value to v, then v will not be initialized and will formally be UB -- and this is all just to save default-initializing a primitive.
Just a suggestion:
Rather than NOLINTing the callers or having to initialize someone-else's uninitialized value, as per your "worst-case" f_wrapper example, could the API possibly be altered to return the initialized value rather than initialize what is passed in?
If you did this, you could either NOLINT it internally, so there are less NOLINTs required, or just initialize the value yourself to prevent other potential issues. Since the value is encapsulated in the function, this would be much less egregious than initializing the caller's maybe-uninitialized value, in my opinion:
int f_wrapper() {
auto v = int{};
auto s = f_legacy(&v);
if(s != success) throw std::runtime_error{};
return v;
}
|
70,660,641 | 70,660,785 | clang vs gcc - CTAD of struct deriving from template parameter | Consider the following code:
template <typename B>
struct D : B { };
D d{[]{ }};
gcc 12.x accepts it and deduces d to be D</* type of lambda */> as expected.
clang 14.x rejects it with the following error:
<source>:4:3: error: no viable constructor
or deduction guide for deduction of template arguments of 'D'
D d{[]{ }};
^
<source>:2:8: note: candidate template ignored:
could not match 'D<B>' against '(lambda at <source>:4:5)'
struct D : B { };
^
<source>:2:8: note: candidate function template not viable:
requires 0 arguments, but 1 was provided
live example on godbolt.org
Which compiler is behaving correctly here?
| In the code snippet, no deduction guide has been provided. P1816 added deduction guides for aggregate class templates in C++20, by requiring that an aggregate deduction candidate is generated.
The code is valid, but Clang just doesn't support P1816 yet.
Adding a deduction guide allows this to compile in Clang as well.
template <typename B> D(B) -> D<B>;
|
70,660,833 | 70,661,109 | cannot interprete exported function and class from another project within solution? |
I have ClassB of ProjectB rely on what is defined in ProjectA.
ProjectA is built as a .lib as shown below
ProjectB is just a exe. Below is the code.
#pragma once
#include "../../ProjectA/ClassA.h"
class ClassB
{
public:
void callClassB();
};
#include "ClassB.h"
void ClassB::callClassB()
{
//ClassA::print_msg();
outside_classA();
}
int main()
{
ClassB B;
B.callClassB();
}
Here is the code for ProjectA.
#pragma once
#define EXPORT_ATTRIBUTE __declspec(dllexport)
class EXPORT_ATTRIBUTE ClassA
{
public:
static void print_msg();
};
void EXPORT_ATTRIBUTE outside_classA();
#include "ClassA.h"
#include <iostream>
using namespace std;
void ClassA::print_msg()
{
cout << "this is class a from project A"<<endl;
}
void outside_classA()
{
cout << "print out side class a" << endl;
}
In VisualStudio:
I have the ProjectB rely on ProjectA. The ClassA and outside_classA() are exported with __declspec(dllexport). And the ProjectA is built as static library .lib .
| I suggest you read this document carefully, it will help you. Regarding your question, you need to select the Configuration Properties > C/C++ > General property page. In the Additional Include Directories property, specify the path of the library directory.
Then the program can run using my code in ClassB.cpp.
#include "ClassB.h"
#include "../StaticLib2/ClassA.h"
#pragma comment(lib,"StaticLib2.lib")
void ClassB::callClassB()
{
//ClassA::print_msg();
outside_classA();
}
int main()
{
ClassB B;
B.callClassB();
}
|
70,660,993 | 70,742,911 | Can't compile c++ program using gcc on Mac after updating to Monterey | *Update:
Regarding the similar question macos-wchar-h-file-not-found, the command line tool switch(xcode-select --install) doesn't exist anymore.
I am running on macOS Monterey system and I am trying to compile a simple hello world .cpp file using the g++-11 commend (I installed gcc using homebrew), I am getting the following error:
/usr/local/Cellar/gcc/11.2.0_3/include/c++/11/cwchar:44:10: fatal error: wchar.h: No such file or directory
44 | #include <wchar.h>
| ^~~~~~~~~
I tried two compile commands:
g++-11 -c hello.cpp -o hell.o
g++-11 -std=c++11 -c hello.cpp -o hell.o
Here is the file I am trying to compile:
//
// main.cpp
// Test
//
// Created by Jiali Zhu on 1/9/22.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| I also had the same problem and in my case the problem was outdated
command line developer tools.
I found out it by running
$ brew doctor
...
Warning: Your Command Line Tools are too outdated.
Update them from Software Update in System Preferences or run:
softwareupdate --all --install --force
If that doesn't show you any updates, run:
sudo rm -rf /Library/Developer/CommandLineTools
sudo xcode-select --install
Alternatively, manually download them from:
https://developer.apple.com/download/all/.
You should download the Command Line Tools for Xcode 13.1.
I tried to update them via softwareupdate -l, however this did not give me any update information.
So removed them and reinstalled with xcode-select --install.
After this g++-11 stopped giving me an error about this header.
Now brew config tells me that I have CLT: 13.0.0.0.1.1627064638
P.S.
Also I started the xcode and it asked me whether additional components need to be installed and I said yes.
|
70,661,070 | 70,661,272 | Can vector cause false sharing | I'm working with C++11 on a project and here is a function:
void task1(int* res) {
*res = 1;
}
void task2(int* res) {
*res = 2;
}
void func() {
std::vector<int> res(2, 0); // {0, 0}
std::thread t1(task1, &res[0]);
std::thread t2(task2, &res[1]);
t1.join();
t2.join();
return res[0] + res[1];
}
The function is just like that. You see there is a std::vector, which store all of the results of the threads.
My question is: can std::vector cause false sharing? If it can, is there any method to avoid false sharing while using std::vector to store the results of threads?
|
can std::vector cause false sharing?
Containers aren't something that "cause" false sharing. It's writing to objects that may cause false sharing. Specifically, writing in one thread to an object that is in the same "cache line" as another object that is accessed in another thread causes false sharing.
Elements of an array are adjacent in memory and hence adjacent small elements of an array are very likely in the same cache line. Vector is an array based data structure. The pattern of accessing the elements of the vector in your example are a good example of false sharing.
is there any method to avoid false sharing while using std::vector to store the results of threads?
Don't write into adjacent small elements of an array (or a vector) from multiple threads. Ways to avoid it are:
Divide the array into contiguous segments and only access any individual segment from a separate thread. The size of the partition must be at least the size of the cache line on the target system.
Or, write into separate containers, and merge them after the threads have finished.
|
70,661,636 | 70,673,278 | Operator= slowing down simulation | I am running a Monte Carlo simulation of a polymer. The entire configuration of the current state of the system is given by the object called Grid. This is my definition of Grid:
class Grid{
public:
std::vector <Polymer> PolymersInGrid; // all the polymers in the grid
int x; // length of x-edge of grid
int y; // length of y-edge of grid
int z; // length of z-edge of grid
double kT; // energy factor
double Emm_n ; // monomer-solvent when Not aligned
double Emm_a ; // monomer-solvent when Aligned
double Ems; // monomer-solvent interaction
double Energy; // energy of grid
std::map <std::vector <int>, Particle> OccupancyMap; // a map that gives the particle given the location
Grid(int xlen, int ylen, int zlen, double kT_, double Emm_a_, double Emm_n_, double Ems_): x (xlen), y (ylen), z (zlen), kT (kT_), Emm_n(Emm_n_), Emm_a (Emm_a_), Ems (Ems_) { // Constructor of class
// this->instantiateOccupancyMap();
};
// Destructor of class
~Grid(){
};
// assignment operator that allows for a correct transfer of properties. Important to functioning of program.
Grid& operator=(Grid other){
std::swap(PolymersInGrid, other.PolymersInGrid);
std::swap(Energy, other.Energy);
std::swap(OccupancyMap, other.OccupancyMap);
return *this;
}
.
.
.
}
I can go into the details of the object Polymer and Particle, if required.
In my driver code, this is what I am going:
Define maximum number of iterations.
Defining a complete Grid G.
Creating a copy of G called G_.
I am perturbing the configuration of G_.
If the perturbance on G_ is accepted per the Metropolis criterion, I assign G_ to G (G=G_).
Repeat steps 1-4 until maximum number of iterations is achieved.
This is my driver code:
auto start = std::chrono::high_resolution_clock::now();
Grid G_ (G);
int acceptance_count = 0;
for (int i{1}; i< (Nmov+1); i++){
// choose a move
G_ = MoveChooser(G, v);
if ( MetropolisAcceptance (G.Energy, G_.Energy, G.kT) ) {
// accepted
// replace old config with new config
acceptance_count++;
std::cout << "Number of acceptances is " << acceptance_count << std::endl;
G = G_;
}
else {
// continue;
}
if (i % dfreq == 0){
G.dumpPositionsOfPolymers (i, dfile) ;
G.dumpEnergyOfGrid(i, efile, call) ;
}
// G.PolymersInGrid.at(0).printChainCoords();
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds> (stop-start);
std::cout << "\n\nTime taken for simulation: " << duration.count() << " milliseconds" << std::endl;
This is the interesting part: if I run the simulation using condition that do not have lots of "acceptances" (low temperatures, bad solvent), the simulation runs pretty fast. However, if there are a large number of acceptances, the simulation gets incredibly slow. My hypothesis is that my assignment operator = is slowing down my simulation.
I ran some tests:
number of acceptances = 25365, wall-clock time = 717770 milliseconds (!)
number of acceptances = 2165, wall-clock time = 64412 milliseconds
number of acceptances = 3000, wall-clock time = 75550 milliseconds
And the trend continues.
Could anyone advise me on how to possibly make this more efficient? Is there a way to bypass the slowdown I am experiencing, I think, due to the = operator?
I would really appreciate any advice you have for me!
| One thing that you can certainly do to improve performance is to force moving _G rather than coping it to G:
G = std::move(G_);
After all, at this stage you don't need G_ any more.
Side remark. The fact that you don't need to copy all member data in operator= indicates that your design of Grid is far from perfect, but, well, keep it if the program is small and you're sure you control everything. Anyway, rather than using operator=, you should define and use a member function with a meaningful name, like "fast_and_dirty_swap" etc :-) Then you can define operator= the way suggested by @Jarod42, that is, using = default.
An alternative approach that I used before C++11 is to operate on pointers. In this scenario one would have two Grids, one "real" and one treated as a buffer, or sandbox, and on acceptance on would simply swap the pointers, so that the "buffer" filled with MoveChooser would become the real, current Grid.
A pseudocode:
Create two buffers, previous and current, each capable of storing a simulation state
Initialize current
Create two pointers, p_prev = &previous, p_curr = ¤rt
For as many steps as you wish
compute the next state from *p_curr and store it in *p_prev (e.g. monte_carlo_step(p_curr, p_prev)
swap the pointers: now the current system state is at p_curr and the previous at p_prev.
analyze the results stored at *p_curr
|
70,662,470 | 70,662,604 | C++ freeing memory of nested container and objects | There a great chance this question is duplicated, but I wasn't sure how to do a proper search on this. Also it may be trivial to you but it will help me as a beginner a lot!
Say I have three classes, each has a container
class A {
std::map<int, B> container1;
};
class B {
std::unordered_map<int, C> container2;
};
class C {
std::vector<int> container3;
};
If I have an object 'a' created from class A, with container1/2/3 all filled with data, my questions are the followings:
When I call a.container1.clear(), will all the memory allocated for container2 and container3 be freed? If so, how does C++ do this under the hood?
When the destructor of 'a' is called, will container2 and 3 be freed?
If 1 and 2 are true, do they apply to any nesting combination of containers? For instance here I have map->unordered_map->vector. A different combination could be vector->unordered_map->map.
My gut feeling is that they are all true. Otherwise if I have a very deeply nested structure, it doesn't make sense to go all the way to bottom and explicitly free the memory there.
| The short answer: Yes, all nested containers in this scenario will have their memory freed.
The long answer: Let's work from the top.
First, I'm going to assume that these are structs instead of classes (or that the containers have been declared public); otherwise, a.container1.clear() won't compile, as container1 would be a private member of a. However, putting that aside:
What happens when you call a.container1.clear()? Per https://www.cplusplus.com/reference/map/map/clear/, the clear method removes all elements from the container, and those are destroyed.
So, this implies that each object of type B in a.container1 will be destroyed, i.e. B's destructor will be called.
In C++, when an object of a class is destroyed, the destructor of each member of the class is called after that class's destructor has finished (in this case, B's destructor is the default compiler-generated destructor, as no user-supplied destructor is present). So, after B is destroyed, the destructor of B.container2 will be called. Since container2 is an unordered_map, its destructor will destroy all of its contained elements (https://www.cplusplus.com/reference/unordered_map/unordered_map/~unordered_map/)
Since container2's elements are of type C, each element of type C in container2 will have its destructor called. Again, container3's destructor will be called. And, as a vector, container3's storage capacity will be deallocated, i.e. freed (https://www.cplusplus.com/reference/vector/vector/~vector/).
Now, we've worked our way to the bottom, and we've seen that all memory is freed!
|
70,662,970 | 70,663,247 | Why is my answer off for certain values of binary representation provided? | The question basically asks us to convert the input binary string (only 1 and 0 provided).
Input format is as follows (each separate point is a new line):
Number of test cases
2N lines with: Length of binary string, Binary string on each alternative line
Output is to return the decimal conversion of the string.
My code:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int len;
cin >> len;
long long num = 0;
while(len--){
char digit;
cin >> digit;
num += (digit-'0')*pow(2,len);
}
cout << num << endl;
}
return 0;
}
Ik there are other methods to go about this problem, but i want to know whats the problem in mine. Inputting certain values like '10001011111110111010111011010011011011110001011000011101' gives an answer '39401750052935200' when the correct value is '39401750052935197'.
Other examples of wrong output:
269908306298371776 (correct = 269908306298371795)
1152921504606846976 (correct = 1152921504606846975)
My code runs correct for all smaller values of binary input (of length maybe less than 50). Why does it fail for such larger values by such a small margin?
|
runs correct for all smaller values of binary input (of length maybe less than 50).
num += (digit-'0')*pow(2,len); is like
num = num + (digit-'0')*pow(2,len);
and the addition is done using double math with its 53-ish bit precision infected by pow().
Instead only use integer math:
unsigned long long num = 0;
...
num = num*2 + (digit-'0');
|
70,663,087 | 70,663,265 | What is the meaning of Eigen's .resize(rows,cols) Matrix const MatrixXd as 'this' argument discards qualifiers error | When the Matrix argument is defined as constant I get
.resize(rows,cols) Matrix const MatrixXd as 'this' argument discards qualifiers error
void (const Eigen::MatrixXd &X){
X.resize(cols, rows) }
returns an error
but this works as expected:
void(Eigen::MatrixXd &X){
X.resize(cols, rows)}
I'm not too familiar with c++ (other than using it for this class) and am wondering what this means?
Thanks for any pointers.
| The warning means that the resize function that you called is not const qualified. The lack of const qualification means that the function cannot be called on a const lvalue. resize is a function that modifies the object. The rough meaning of "const" is that modification isn't allowed.
X is an lvalue reference to const, so non-const qualified functions cannot be called through the reference. You attempted to call a non-const qualified function through the const reference. Since that's not allowed, the compiler told you about the bug.
|
70,663,344 | 70,667,268 | Qt5 make a copy of ini file(QSettings) to build folder using CMake | I'm Qt5 beginner.
I saved two .ini file with QSettings for two different layout of toolbars and dockwidgets.
coolUI.ini and fantacyUI.ini
I move them to my project folder and want to copy them to the build/release folder when building with CMake.
And then I can reset to one of them anytime in my app.
If any information is needed, please tell me.
| Assuming your coolUI.ini file is in a project directory/subdirectory that contains a CMakeLists.txt file you may try to use
file(COPY_FILE ${CMAKE_CURRENT_SOURCE_DIR}/coolUI.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/coolUI.ini)
or
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/coolUI.ini DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
or
configure_file(coolUI.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/coolUI.ini COPYONLY)
command from that CMakeLists.txt file to achieve that. Otherwise you need to adapt the input and output paths. CMAKE_RUNTIME_OUTPUT_DIRECTORY is the folder where your executable will be created into.
|
70,663,430 | 70,663,550 | Why does declaring a 2D array of sufficient size cause a segfault on Linux but not macOS? | Problem
I'm trying to declare a large 2D Array (a.k.a. matrix) in C / C++, but it's crashing with segfault only on Linux. The Linux system has much more RAM installed than the macOS laptop, yet it only crashes on the Linux system.
My question is: Why does this crash only on Linux, but not macOS?
Here is a small program to reproduce the issue:
// C++ program to segfault on linux
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
cout << "Let's crash for no raisin! " << endl;
cout << "Int size: " << sizeof(int) << endl;
for (int n=1012; n < 2000; n++) {
cout << "Declaring Matrix2D of size: " << n << "x" << n << " = " << n*n << endl;
cout << "Bytes: " << n*n*sizeof(int) << endl;
// segfault on my machine at 1448x1448 = 8386816 bytes
int Matrix2D[n][n];
// these two lines can be commented out and the program still reaches segfault
// int* pM2D = (int*)malloc(n*n*sizeof(int));
// free(pM2D);
}
return 0;
}
Compile with: g++ -Wall -g -o segfault segfault.cpp
Output
Linux
Linux system has 64 GiB RAM installed!
$ ./segfault ; free --bytes
Let's crash for no raisin!
Int size: 4
[...SNIP...]
Declaring Matrix2D of size: 1446x1446 = 2090916
Bytes: 8363664
Declaring Matrix2D of size: 1447x1447 = 2093809
Bytes: 8375236
Declaring Matrix2D of size: 1448x1448 = 2096704
Bytes: 8386816
Segmentation fault (core dumped)
total used free shared buff/cache available
Mem: 67400994816 11200716800 4125982720 412532736 52074295296 55054041088
Swap: 1023406080 824442880 198963200
$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 256763
max locked memory (kbytes, -l) 65536
max memory size (kbytes, -m) unlimited
open files (-n) 65535
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 256763
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
macOS
macOS system has only 16 GB RAM installed!
$ ./segfault ; sysctl -a | grep mem ;
Let's crash for no raisin!
Int size: 4
[...SNIP...]
Declaring Matrix2D of size: 1997x1997 = 3988009
Bytes: 15952036
Declaring Matrix2D of size: 1998x1998 = 3992004
Bytes: 15968016
Declaring Matrix2D of size: 1999x1999 = 3996001
Bytes: 15984004
kern.dtrace.buffer_memory_maxsize: 5726623061
kern.dtrace.buffer_memory_inuse: 0
kern.memorystatus_sysprocs_idle_delay_time: 10
kern.memorystatus_apps_idle_delay_time: 10
kern.memorystatus_purge_on_warning: 2
kern.memorystatus_purge_on_urgent: 5
kern.memorystatus_purge_on_critical: 8
vm.memory_pressure: 0
hw.memsize: 17179869184
machdep.memmap.Conventional: 17077571584
machdep.memmap.RuntimeServices: 524288
machdep.memmap.ACPIReclaim: 188416
machdep.memmap.ACPINVS: 294912
machdep.memmap.PalCode: 0
machdep.memmap.Reserved: 84250624
machdep.memmap.Unusable: 0
machdep.memmap.Other: 0
$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) unlimited
max memory size (kbytes, -m) unlimited
open files (-n) 256
pipe size (512 bytes, -p) 1
stack size (kbytes, -s) 65532
cpu time (seconds, -t) unlimited
max user processes (-u) 2784
virtual memory (kbytes, -v) unlimited
| Although ISO C++ does not support variable-length arrays, you seem to be using a compiler which supports them as an extension.
In the line
int Matrix2D[n][n];
n can have a value up to 2000. This means that the 2D array can have 2000*2000 elements, which equals 4 million. Every element has a size of sizeof(int), which is 4 bytes on linux. This means that you are allocating a total of 16 Megabytes on the stack. This is exceeding the limit of the stack, causing a stack overflow.
The reason why it is not crashing on MacOS could be that the stack is configured for a higher maximum limit, or it could be that your program is not crashing because variable-length arrays are implemented differently, so that the program is not touching the 2D array, or maybe it is touching the 2D array, but only in such a way that it doesn't cause a crash. These are implementation-details of the compiler.
The amount of memory actually installed on the computer is not relevant. What counts is the maximum stack limit configured in the operating system.
If you want to use larger amounts of memory than would be permitted on the stack, you should use the heap instead. In that case, you should allocate the memory instead with std::make_unique, operator new or std::malloc. You can also use most STL containers such as std::vector, which will automatically store its contents on the heap, even if you create the actual container on the stack. However, beware that some STL containers will not, such as std::array.
|
70,663,669 | 70,663,725 | How to play with spdlog? | I downloaded and followed the example 1.
Moved to example 2 (Create stdout/stderr logger object) and got stuck. Actually I can run it as it is but if I change
spdlog::get("console") to spdlog::get("err_logger") it crashes.
Am I supposed to change it like that?
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
void stdout_example()
{
// create color multi threaded logger
auto console = spdlog::stdout_color_mt("console");
auto err_logger = spdlog::stderr_color_mt("stderr");
spdlog::get("err_logger")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
}
int main()
{
stdout_example();
return 0;
}
I also tried Basic file logger example:
#include <iostream>
#include "spdlog/sinks/basic_file_sink.h"
void basic_logfile_example()
{
try
{
auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
}
catch (const spdlog::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
}
}
int main()
{
basic_logfile_example();
return 0;
}
And I see it creates basic-log.txt file but there is nothing on it.
| Because you need to register err_logger logger first. There is no default err_logger as far as I know. spdlog::get() returns logger based on its registered name, not variable.
You need a code like this. Code is complex and you may not need all of it though:
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/rotating_file_sink.h"
void multi_sink_example2()
{
spdlog::init_thread_pool(8192, 1);
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >();
auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3);
std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink};
auto logger = std::make_shared<spdlog::async_logger>("err_logger", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block);
spdlog::register_logger(logger); //<-- this line registers logger for spdlog::get
}
and after this code, you can use spdlog::get("err_logger").
You can read about creating and registering loggers here.
I think spdlog::stderr_color_mt("stderr"); registers logger with name stderr so spdlog::get("stderr") may work, but have not tested myself.
|
70,663,796 | 70,678,951 | yocto image with boost 1.77: libboost_atomic.so is not on image, but is in sdk | I have an aarch64 based yocto image, and it contains also an app that I compile as a package and that app uses and links with boost 1.77 and uses boost::filesystem using cmake. The app on the image works and everything is ok.
The problem I have is: I also generated the SDK part for yocto, and that SDK contains all boost libraries, also ones that are not on the image, for example libboost_atomic.so. And when I externally compile my app using the SDK, then it links also to libboost_atomic.so.
But of course, it's not on the image, so I can't run it on my device because it does not find the atomic lib at runtime. So how should I solve this problem? The libboost_atomic.so library does not really seem to be needed, but the sdk thinks it does.
I am using yocto Honister.
| I found the problem: for the SDK, I use a cmake toolchain file, and so that file did not contain a linker option that yocto uses: -Wl,--as-needed
So using that option, the linker is not linking to libboost_atomic.so anymore and I can run my sdk-compiled version on the image!
|
70,663,939 | 70,664,103 | function CIN gets skipped every time | I wanted to make a small "game" with a little bit of story, but I did some code and I think i did some major mistakes, here's the code
int main() {
char o, z, q, r;
string f, w = "yes", e = "no";
cout << "Hello, summoner!" << endl;
cin >> o;
cout << "You know why you are here, right?" << endl;
cin >> q;
switch ( z ) {
case 'w':
cout << "Ok";
break;
case 'e':
cout << "You are here to fight for your life!";
break;
}
return 0;
}
The second cin, the cin >> q; gets skipped every time I run the code and I don't know what to do.
| It may not get skipped. You may be entering more than one characters in 'o', which is not allowed in your case and the second character automatically is stored in variable q.
Try changing the data type of the variables mentioned if you want to enter longer strings in the variables.
|
70,664,043 | 70,666,252 | Clip Raster with Polygon with GDAL C++ | I am trying to clip a raster using a polygon an GDAL. At the moment i get an error that there is a read access violation when initializing the WarpOperation. I can access my Shapefile and check the num of features so the access is fine i think. Also i can access my Raster Data (GetProjectionRef).. All files are in the same CRS. Is there a way to use GdalWarp with Cutline?
const char* inputPath = "input.tif";
const char* outputPath = "output.tif";
//clipper Polygon
auto w_read_filenamePoly = "Polygon.shp";
char* read_filenamePoly = new char[w_read_filenamePoly.length() + 1];
wcstombs(read_filenamePoly, w_read_filenamePoly.c_str(), w_read_filenamePoly.length() + 1);
GDALDataset* hSrcDS;
GDALDataset* hDstDS;
GDALAllRegister();
hSrcDS =(GDALDataset *) GDALOpen(inputPath, GA_Update);
hDstDS = (GDALDataset*)GDALOpen(outputPath, GA_Update);
const char* proj = hSrcDS->GetProjectionRef();
const char* proj2 = hDstDS->GetProjectionRef();
//clipper Layer
GDALDataset* poDSClipper;
poDSClipper = (GDALDataset*)GDALOpenEx(read_filenamePoly, GDAL_OF_UPDATE, NULL, NULL, NULL);
Assert::IsNotNull(poDSClipper);
delete[]read_filenamePoly;
OGRLayer* poLayerClipper;
poLayerClipper = poDSClipper->GetLayerByName("Polygon");
int numClip = poLayerClipper->GetFeatureCount();
//setup warp options
GDALWarpOptions* psWarpOptions = GDALCreateWarpOptions();
psWarpOptions->hSrcDS = hSrcDS;
psWarpOptions->hDstDS = hDstDS;
psWarpOptions->nBandCount = 1;
psWarpOptions->panSrcBands = (int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount);
psWarpOptions->panSrcBands[0] = 1;
psWarpOptions->panDstBands = (int*)CPLMalloc(sizeof(int) * psWarpOptions->nBandCount);
psWarpOptions->panDstBands[0] = 1;
psWarpOptions->pfnProgress = GDALTermProgress;
psWarpOptions->hCutline = poLayerClipper;
// Establish reprojection transformer.
psWarpOptions->pTransformerArg = GDALCreateGenImgProjTransformer(hSrcDS,proj, hDstDS, proj2, FALSE, 0.0, 1);
psWarpOptions->pfnTransformer = GDALGenImgProjTransform;
GDALWarpOperation oOperation;
oOperation.Initialize(psWarpOptions);
oOperation.ChunkAndWarpImage(0, 0, GDALGetRasterXSize(hDstDS), GDALGetRasterYSize(hDstDS));
GDALDestroyGenImgProjTransformer(psWarpOptions->pTransformerArg);
GDALDestroyWarpOptions(psWarpOptions);
GDALClose(hDstDS);
GDALClose(hSrcDS);
| Your psWarpOptions->hCutline should be a polygon, not a layer.
Also the cutline should be in source pixel/line coordinates.
Check TransformCutlineToSource from gdalwarp_lib.cpp, you can probably simply get the code from there.
This particular GDAL operation, when called from C++, is so full of pitfalls - and there are so many open questions about it here - that I am reproducing a full working example:
Warping (reprojecting) a raster image with a polygon mask (cutline):
#include <gdal/gdal.h>
#include <gdal/gdal_priv.h>
#include <gdal/gdalwarper.h>
#include <gdal/ogrsf_frmts.h>
int main() {
const char *inputPath = "input.tif";
const char *outputPath = "output.tif";
// clipper Polygon
// THIS FILE MUST BE IN PIXEL/LINE COORDINATES or otherwise one should
// copy the function gdalwarp_lib.cpp:TransformCutlineToSource()
// from GDAL's sources
// It is expected that it contains a single polygon feature
const char *read_filenamePoly = "cutline.json";
GDALDataset *hSrcDS;
GDALDataset *hDstDS;
GDALAllRegister();
auto poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
hSrcDS = (GDALDataset *)GDALOpen(inputPath, GA_ReadOnly);
hDstDS = (GDALDataset *)poDriver->CreateCopy(
outputPath, hSrcDS, 0, nullptr, nullptr, nullptr);
// Without this step the cutline is useless - because the background
// will be carried over from the original image
CPLErr e = hDstDS->GetRasterBand(1)->Fill(0);
const char *src_srs = hSrcDS->GetProjectionRef();
const char *dst_srs = hDstDS->GetProjectionRef();
// clipper Layer
GDALDataset *poDSClipper;
poDSClipper = (GDALDataset *)GDALOpenEx(
read_filenamePoly, GDAL_OF_UPDATE, NULL, NULL, NULL);
auto poLayerClipper = poDSClipper->GetLayer(0);
auto geom = poLayerClipper->GetNextFeature()->GetGeometryRef();
// setup warp options
GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions();
psWarpOptions->hSrcDS = hSrcDS;
psWarpOptions->hDstDS = hDstDS;
psWarpOptions->nBandCount = 1;
psWarpOptions->panSrcBands =
(int *)CPLMalloc(sizeof(int) * psWarpOptions->nBandCount);
psWarpOptions->panSrcBands[0] = 1;
psWarpOptions->panDstBands =
(int *)CPLMalloc(sizeof(int) * psWarpOptions->nBandCount);
psWarpOptions->panDstBands[0] = 1;
psWarpOptions->pfnProgress = GDALTermProgress;
psWarpOptions->hCutline = geom;
// Establish reprojection transformer.
psWarpOptions->pTransformerArg = GDALCreateGenImgProjTransformer(
hSrcDS, src_srs, hDstDS, dst_srs, TRUE, 1000, 1);
psWarpOptions->pfnTransformer = GDALGenImgProjTransform;
GDALWarpOperation oOperation;
oOperation.Initialize(psWarpOptions);
oOperation.ChunkAndWarpImage(
0, 0, GDALGetRasterXSize(hDstDS), GDALGetRasterYSize(hDstDS));
GDALDestroyGenImgProjTransformer(psWarpOptions->pTransformerArg);
GDALDestroyWarpOptions(psWarpOptions);
GDALClose(hDstDS);
GDALClose(hSrcDS);
}
|
70,664,220 | 70,664,244 | C++: Passing object to class constructor, how is it stored? | Consider the following example of a simple class implementation in C++.
foo.hpp
#include <vector>
class Foo {
private:
std::vector<double> X;
public:
Foo() = default;
~Foo() = default;
Foo(std::vector<double>&);
};
foo.cpp
#include "Foo.hpp"
Foo::Foo(std::vector<double>& X):
X(X)
{}
In this case, the vector X is passed by reference to the constructor of the class Foo. I start having doubts, though, on whether the operation X(X) in the implementation makes a copy and pastes it "in" the member X of the class.
Which is it?
| Yes, the data member X will be copy-initialized from the constructor parameter X.
If you declare the data member X as reference, then no copy operation happens. E.g.
class Foo {
private:
std::vector<double>& X;
public:
~Foo() = default;
Foo(std::vector<double>&);
};
Foo::Foo(std::vector<double>& X):
X(X)
{}
Then
std::vector<double> v;
Foo f(v); // no copies; f.X refers to v
|
70,664,337 | 70,664,538 | Run all catch2 tests in one compile unit without tag definition | I have the following project structure:
test_main.cc
#define CATCH_CONFIG_MAIN
#include "catch2.hpp"
test1.cc
#include "catch2.hpp"
TEST_CASE("test1", "[test1]") {
REQUIRE(1 == 1);
}
test2.cc
#include "catch2.hpp"
TEST_CASE("test2", "[test2]") {
REQUIRE(2 == 2);
}
Now, I can run all tests with e.g. test1 using the command line option test1 at the runtime of the test executable.
I usually tag all test in one file with the same tags, since I use one file to combine all tests for the same topic. Thus, using a file and tags violated the DRY principle.
My question is there a way to run all catch2 tests defined in one file?
| I've found in documentation this:
Catch2/command-line.md at devel · catchorg/Catch2 · GitHub
Filenames as tags
-#, --filenames-as-tags
When this option is used then every test is given an additional tag which is formed of the unqualified filename it is found in, with any extension stripped, prefixed with the # character.
So, for example, tests within the file ~\Dev\MyProject\Ferrets.cpp would be tagged [#Ferrets].
Looks like it works, so now just filter test based on that tag.
There is even exact example in documentation
...
-# [#somefile] Matches all tests from the file 'somefile.cpp'
|
70,664,433 | 70,665,261 | Why is it not possible to add a `std::chrono::hours` to a `std::chrono::sys_days` | Taking the first steps with <chrono> library,
I'm starting with basic arithmetic on a days grained time_point.
Thanks to a very useful post by @HowardHinnant,
I managed to write this:
#include <chrono>
using namespace std::chrono_literals;
int main()
{
std::chrono::sys_days d {std::chrono::January/31/2022};
d += std::chrono::days{2}; // ok
//d += 48h; // error: no match for 'operator+=' with std::chrono::hours
}
What is not clear to me is why d += 48h; isn't allowed.
The std::chrono::time_point<>::operator+= takes a duration,
and the rvalue in that expression is a std::chrono::hours that
in my mind represents a time duration.
What's the philosophy here? Are there different duration types
according to the measure unit that must be compatible with the
granularity of the time_point? Why?
On the other hand, I understand why d += 2d; gives an error,
since in this case std::literals::chrono_literals::operator""d
is a std::chrono::day, which is not a duration (that's handy
to form a date literal, although it seems a little inconsistent
to me).
I wonder if there's a more convenient way to express
a duration literal equivalent to std::chrono::days{2}.
| You can add hours to days. What you can't do is implicitly convert that into days again. You need a cast
d = std::chrono::time_point_cast<std::chrono::days>(d + 48h);
|
70,664,691 | 70,667,383 | Problem with the Tool Flags during the c++ module compilation | I'm trying to compile the module in Eclipse and generate the additional output disassembles
I've added these Tool Flags
-fverbose-asm -Wa,-adhln -save-temps=obj > %OutFile%.asm
But I receive this error
clang: error: unsupported argument '-adhln' to option 'Wa,'
Does anybody had a similar issue? If so please help
Many Thanks
| OK so the target was to generate the assemblies with the instructions HEX and relative addresses
I was not able to do that using Eclipse >> Tool Flags so I simply left one flag:
-save-temps=obj
Which generates AT&T systax assemblies but without details like (instruction Hex or relative address)
But I've managed to generate INTEL syntax assemblies with all the details I need to debug my problem using objdump
objdump -d -M intel -S DMAProcesor.o > DMAProcessor.asm
|
70,664,812 | 70,664,979 | Deduce the array-sizes in a variadic template function | I try to write a constexpr function that accepts a variable number of C-Strings. And I want to deduce all of the sizes (here: L0 and LL) of the passed arrays. Looks like a stupid error I make there, but trying to do so, I get an error:
error: parameter packs not expanded with '...':
204 | constexpr auto generate(const char (&s0)[L0], const char (&ss)[LL] ...) {
template<size_t L0, size_t... LL>
constexpr auto generate(const char (&s0)[L0], const char (&ss)[LL] ...) {
constexpr size_t ll = (LL + ...);
std::integral_constant<size_t, L0>::_;
std::integral_constant<size_t, ll>::_;
std::array<char, 1 + L0 + ll> r;
return r;
}
constexpr auto STR_X = generate("abc", "def");
This is done with gcc version 12.0 and -std=c++20.
| The problem should be the expansion of ss (that is variadic too)
// ellipsis here ...........................................VVV
constexpr auto generate(const char (&s0)[L0], const char (& ... ss)[LL]) {
|
70,665,163 | 70,673,666 | Caret position in EditBox after change in text length | I have an EditBox in a MFC-dialog. The user is supposed to enter a number. I'm trying to automatically add separators to the number while the user is inputting it:
When the number is more than 3 digits long, a separator is added between the hundreds and the thousands digit; a second one between the hundredthousands and the millions when it gets longer than 6 digits and so forth (so that 1234567 becomes 1,234,567 for example).
This is done in a function executed by ON_EN_CHANGE and basically works fine already. But the problem is that the caret position is set to the beginning of the EditBox once my function changes the length of the string in it, preventing continous typing.
I tried simulating the press of the end-key to send the caret to the end of the EditBox, which works as long as the user only enters a number from left to right. But it won't work when the user is trying to add, remove or edit digits in the middle of the number. I need the caret position at the exact spot of the number where it was before the user pressed a key.
I tried calculating the new caret position from the previous one (gotten with CEdit::GetSel()) and the previous length of the number:
OnEnChange()
{
int prevCursPos {HIWORD(m_editCtrl.GetSel())};
int prevStrLen {m_editCtrl.GetWindowTextLengthW()};
UpdateData(TRUE);
// Adding/Removing of separators as needed
UpdateData(FALSE);
int difference {m_editCtrl.GetWindowTextLengthW() - prevStrLen))};
if(difference > 0) // a separator has been added to the string
m_editCtrl.SetSel(-1, prevCursPos + 1);
}
However, the SetSel() function doesn't seem to have any effect. I also tried to send an EM_SETSEL message instead, but I couldn't figure out how to make that work either, the caret always resets itself to the beginning of the EditBox.
Does anyone have another idea on how to accomplish what I'm trying to do?
|
It is unclear how you are handling "/ Adding/Removing of separators as needed".
SetSel with the first parameter set to -1 will position the caret at the beginning of the string if the string changes after calling UpdateData(false)
Create CString type of the variable (m_csEdit for example) for this edit control and
int iLen = m_csDDx.GetLength();
m_editCtrl.SetSel(iLen, -1);
or
m_editCtrl.SetSel(iLen, iLen);
You can calculate the length differently from what I suggested.
Consider using masked edit control (maybe).
Forgot to mention. Use GetNumberFormatEx to format number with thousand delimiter.
|
70,665,319 | 70,665,454 | Program only prints out the first two lines of my code, and ignores the rest entirely | So the problem I am facing here is that, the program runs only the first two lines of the code and entirely ignores the rest. I have tried rewriting it, I have also searched the internet for solution, but I found nothing and the problem continues to persist.
#include <iostream>
using namespace std;
struct customer{
char A_ID[10];
char pin[4];
char amount[20];
int input;
int csnt;
}c;
int main()
{
struct customer *p;
// Welcome Note
cout<<"Welcome to Absa,insert your card and enter you pin: "<<endl;
cin.getline(c.pin,sizeof(c.pin));
// Transaction Menu
cout<<"1. Transfer"<<endl
<<"2. Deposit"<<endl
<<"3. Change pin"<<endl
<<"4. Account Balance"<<endl;
cin>>c.input;
// Transaction Process
switch(c.input){
case 1:
cout<<"Enter amount: "<<endl;
cin>>c.amount[9];
cout<<"Enter recipient Account number: "<<endl;
cin>>c.A_ID[10];
cout<<"Payment of GHc "<<c.amount<<"made to "<<c.A_ID<<endl;
cout<<"Enter 1 to confirm or 2 to cancel: "<<endl;
cin>>c.csnt;
if(c.csnt==1){
cout<<"Transfer successful, thank you for Banking with Absa."<<endl;
}
else if(c.csnt==2){
cout<<"Transfer cancelled, thank you for Banking with Absa."<<endl;
}
}
return 0;
}
| Your p variable has not been initialized yet:
struct customer *p;
That means it does not point to an instantiated object of type customer. So this is how you can create an object on the heap:
std::unique_ptr<customer> ptr { std::make_unique<customer>{ } };
ptr will handle the deletion of the customer object for you.
But there is really no need for you to use a pointer to customer in this case. Just create it on the stack:
customer cust; // here cust is stored on the stack so no need to deal with pointers
// also struct keyword is not required here (in C++)
Then use the . operator to access its members like this:
std::cin >> cust.input;
Note: I don't understand what exactly you're trying to do here:
std::cin >>p->pin[4];
So my guess is that you are trying to assign a 4 digit number to pin array. This is not valid. But you may do this instead:
struct customer {
...
char pin[4]; // use a char array
...
}
// get exactly 4 `char`s from the user and store in `pin`
std::cin.getline( cost.pin, sizeof(cust.pin) );
// or like this
std::string temp_pin;
std::getline( std::cin, temp_pin );
if (temp_pin.size() == 4)
{ // for example print success message;
std::strncpy( cust.pin, temp_pin.data(), sizeof(cust.pin) );
}
else
{ // repeat the input process }
Also, you seem to mix C and C++ for no particular reason. Try to use only one of them to prevent any problems that might arise due to the different behaviors of C and C++ functions. Use std::cout or std::format (with C++20).
Here is the working version:
#include <iostream>
#include <string>
#include <limits>
#include <cstring>
struct Customer
{
char A_ID[10 + 1] { }; // plus 1 for '\0' character
char pin[4 + 1] { }; // plus 1 for '\0' character
int amount { };
};
int main( )
{
Customer cust;
// Welcome Note
std::cout << "Welcome to Absa, insert your card and enter you pin: \n";
std::string pin; // temporary var for getting pin
std::getline( std::cin, pin );
std::strncpy( cust.pin, pin.data( ), sizeof( cust.pin ) - 1 ); // copy temp var to pin of cust
cust.pin[4] = '\0'; // do this to make it null-terminated
// Transaction Menu
std::cout << "1. Transfer\n"
<< "2. Deposit\n"
<< "3. Change pin\n"
<< "4. Account Balance\n";
std::string input { };
std::getline( std::cin, input );
// Transaction Process
std::string amount; // temp var for amount
std::string A_ID; // temp var for A_ID
std::string csnt { };
switch ( input[0] ) // compare the 1st char of input with test cases
{
case '1' :
std::cout << "Enter amount: \n";
std::getline( std::cin, amount );
cust.amount = std::stoi( amount ); // convert string to integer
std::cout << "Enter recipient Account number: \n";
std::getline( std::cin, A_ID );
std::strncpy( cust.A_ID, A_ID.data( ), sizeof( cust.A_ID ) - 1 );
cust.A_ID[10] = '\0';
std::cout << "Payment of GHc " << cust.amount<< " made to " << cust.A_ID << '\n';
std::cout << "Enter 1 to confirm or 2 to cancel: \n";
std::getline( std::cin, csnt );
if ( csnt[0] == '1' )
{
std::cout << "Transfer successful, thank you for Banking with Absa.\n";
}
else if ( csnt[0] == '2' )
{
std::cout << "Transfer canceled, thank you for Banking with Absa.\n";
}
break;
case '2' : // I leave these cases for you
case '3' :
case '4' :
default:
break;
}
return 0;
}
|
70,665,558 | 70,666,939 | How To Access Dynamically Created Buttons Click events Qt C++ | I Created buttons dynamically for data from the database
QPushButton *btnComment = new QPushButton("Comment");
btnComment->setProperty("id",qry.value(0).toString());
Is the button that i created dynamically
I set a connect
connect(btnComment, &QPushButton::clicked, this, &Planner::commentButton);
and created a function on slots
public slots:
void commentButton();
How can I get the id value so I can execute a SQL query after the button click
I tested the function
void Planner::commentButton()
{
QMessageBox inpass;
inpass.setText("Comment");
inpass.exec();
return;
}
It works but after clicking OK the application closes
I get something like this in the console
QMainWindowLayout::addItem: Please use the public QMainWindow API instead
Any possible approach ?
Update
I was able to solve the lambda issue by declaring the passing variable as a global variable
connect(btnComment, &QPushButton::clicked, this, [this]{ commentButton(taskID); });
| As mentioned in the comment you can connect to a lambda rather than directly to a non-static member.
Change the signature/definition of Planner::commentButton to...
void Planner::commentButton (QPushButton *button)
{
/*
* Use button accordingly.
*/
}
Then simply change your connect call to...
connect(btnComment, &QPushButton::clicked, this,
[this, btnComment]
{
commentButton(btnComment);
});
Now a pointer to the QPushButton that triggered the call will be passed to Planner::commentButton.
|
70,665,994 | 70,667,565 | How to extract tuple into a function parameters | I'm working with C++ on Linux and I need to develop a common library to simplify the multi-threading development.
Well, I know that there are some mechanism of multi-threading in C++11, such as std::async, std::future etc. But I have to work with pthread because of some historical reason.
Basically, what I'm trying to do is to make a very very simple template function, which is kind of like std::future. Here it is.
template<typename S>
struct signature;
template<typename R, typename... Args>
struct signature<R(*)(Args...)> {
using return_type = R;
using argument_type = std::tuple<R(*)(Args...), Args...>; // f, args...
};
template<typename F, typename... Args>
void func(F* f, Args&&... args) {
typename signature<decltype(f)>::argument_type tp = std::make_tuple(f, std::forward<Args>(args)...);
pthread_t td;
pthread_create(&td, nullptr, [](void *p){
auto param = static_cast<typename signature<decltype(f)>::argument_type*>(p);
std::get<0>(*param)(std::get<1>(*param)); // ???
return (void*)nullptr;
}, &tp);
}
void f(int a) {}
void f2(int a, int b) {}
int main() {
func(f, 1);
// func(f2, 2, 2); ERROR!
return 0;
}
In a word, I try to wrap the parameters of the function into a tuple and pass the tuple into the third parameter of pthread_create, which is a labmda.
So in the piece of code, std::get<0>(*param) is the function, and the rest part of the tuple *param is the parameter list which should be passed to the function. But I don't know how to expand it. Obvisouly, std::get<0>(*param)(std::get<1>(*param)); is not OK because it can only handle the function with one parameter. If I want to pass a function with two parameters, I will get an error.
So how to expand the tuple there?
BTW, please ignore other issues, such as why don't call pthread_join. I just remove them here to minimize my post.
| As mentioned in the comments, std::apply is suitable for your case.
pthread_create(
&td, nullptr,
[](void* p) {
auto param = static_cast<typename signature<decltype(f)>::argument_type*>(p);
std::apply([](auto& f, auto&&... args) {
f(std::forward<decltype(args)>(args)...);
}, *param);
return (void*)nullptr;
},
&tp);
Demo.
|
70,666,090 | 70,666,144 | How do I call an object of a class that inherits another class that has arguments in its constructor? | I am working with multiple classes and files, so I have created this dummy code to better define my problem. I have a parent class Parent and a child class Child. I've separated both of these in a .h and a .cpp file
parent.h
class Parent
{
Parent(int a, int b, int c);
protected:
void somefunc();
};
parent.cpp
#include<iostream>
#include "parent.h"
Parent::Parent(int a, int b, int c)
{
std::cout<<"Answer is: "<<a+b+c;
}
void Parent::somefunc()
{
std::cout << "I am some func";
}
child.h
#include "parent.h"
class Child : public Parent
{
public:
void funk();
};
child.cpp
#include"child.h"
void Child::funk()
{
somefunc();
}
And I'm using another file running.cpp to run this.
#include "child.h"
int main()
{
Child a;
a.funk();
return 0;
}
Trying to build this using g++, gives me the error:
running.cpp: In function ‘int main()’:
running.cpp:4:11: error: use of deleted function ‘Child::Child()’
Child a;
^
In file included from running.cpp:1:0:
child.h:2:7: note: ‘Child::Child()’ is implicitly deleted because the default definition would be ill-formed:
class Child : public Parent
^~~~~
child.h:2:7: error: no matching function for call to ‘Parent::Parent()’
In file included from child.h:1:0,
from running.cpp:1:
parent.h:3:5: note: candidate: Parent::Parent(int, int, int)
Parent(int a, int b, int c);
^~~~~~
parent.h:3:5: note: candidate expects 3 arguments, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(const Parent&)
class Parent
^~~~~~
parent.h:1:7: note: candidate expects 1 argument, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(Parent&&)
parent.h:1:7: note: candidate expects 1 argument, 0 provided
The g++ command I'm using is g++ *.cpp -o test
I understand that I'm somehow supposed to give arguments to run the constructor of Parent, but I'm not sure how to do that.
How do I get rid of this error?
If the error is unrelated to this, how do I make an object of a Child Class when it is inheriting a class that has arguments in its constructor? I need to invoke the argument constructor as well, so I can't just make another blank constructor and use that instead.
|
How do I get rid of this error?
You can solve this error by adding the default constructor in class Parent as shown below. Also, note that you need to make the constrcutors public.
parent.h
class Parent
{ public: //ADDED PUBLIC KEYWORD
Parent(int a, int b, int c);
//ADD DEFAULT CONSTRCUTOR
Parent()=default;
protected:
void somefunc();
};
|
70,666,139 | 70,666,177 | What happens when opeator= returns void rather than T&? | In operator overloading, the assignment operator is normally defined as follows:
T& T::operator =(const T2& b);
which returns T& as result. But I want to know what happens when we return void. For example, the assignment operator of std::atmoic<std::shared_ptr<T>> returns void:
void operator=( std::shared_ptr<T> desired ) noexcept;
as defined here and here. What happens in this case? Is it ok to always implement the assignment operator like this? I guess this prevents assignments like a=b=c; which is good sometimes, isn't it?
| You won't be able to chain assignments
a = b = c;
(Nor introduce more complicated cases, like (a = b).method(); or if((a = b));.)
OTOH, with void return type you don't need the ubiquitous return *this; boilerplate.
|
70,666,224 | 70,666,848 | convert a text to another text with another structure | I just want to write an code to change the input to another text with another structure.
for example a text is given. and I should convert them intoanother text like I say below.
this is the input :
typedef enum
{
RED,
GREEN,
BLUE
} Color;
and this should be the output :
enum class Color
{
RED = 0,
GREEN = 1,
BLUE = 2
};
#include <iostream>
#include<string>
#include <vector>
using namespace std;
int main()
{
string example = "typedef enum {RED,GREEN,BLUE} Color;";
string var_name;
for(int i=0; i <example.size(); i++)
{
if(example[i] == ';') break;
var_name += example[i];
}
//cout << var_name << endl;
int i = var_name.length() - 1; // last character
while (i != 0 && !isspace(var_name[i]))
{
--i;
}
string lastword = var_name.substr(i+1); // +1 to skip leading space
cout << lastword << endl;
///////////////////////////////
return 0;
}
I could only get the color. can anybody help me to complete this:)?
the enum of c is just a text and I have to convert it into an another text which look like an anum in c++. its just working with strings and charecters.
| #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string temp;
vector <string> lines;
while(true){
getline(cin,temp);
lines.push_back(temp);
if(temp.back()==';')
break;
}
cout<<"enum class "<<lines.back().substr(2,lines.back().size()-3)<<endl;
cout<<lines[1]<<endl;
for(int i=2 ; i<lines.size()-1 ; i++){
if (i!=lines.size()-2){
cout<<lines[i].substr(0,lines[i].size()-1)<<" = "<< i-2<< ","<<endl;
}
else
cout<<lines[i]<<" = "<< i-2<<endl;
}
cout <<"};";
}
|
70,666,773 | 70,667,123 | Why is shared_ptr implemented using control block and not a static map? | To me, it looks like an implementation of std::shared_ptr which stores a reference counter in a static std::unordered_map<void*, struct Counters> would be much more simpler and also allow us to avoid some dirty workarounds like std::enable_shared_from_this (because std::shared_ptr<T>{this} wouldn't create new control block, only increment a counter for a pointer that already exists in a map).
So why does a committee decided to stick with a control block implementation?
|
So why does a committee decided to stick with a control block implementation?
It doesn't. The committee writes requirements that implementers must follow. They do not specify that std::shared_ptr be implemented in any particular way, so long as that way meets the requirements.
Having said that, your proposed static std::map<T*, size_t> runs foul of this general (unless otherwise specified) requirement:
A C++ standard library function shall not directly or indirectly
access objects ([intro.multithread]) accessible by threads other than
the current thread unless the objects are accessed directly or
indirectly via the function's arguments, including this.
[res.on.data.races#2]
Another compelling reason is that std::shared_ptr type-erases the deleter, so at best you'd have a static std::map<void *, struct { size_t count; size_t weak_count; std::function<void(void*)> deleter; }>, at which point you have two dynamic allocations for the control block, rather than the one (possibly merged with the owned object) that current implementers prefer.
|
70,666,930 | 70,667,061 | Taylor expansion in C++: function factory? | In some application I need to have access to the elements of some polynomial expansion (for example x^i for i = 0,1,...). My idea was to create a "function factory" like
#include <functional>
#include <iostream>
std::function<double(double)> Taylor(unsigned int i)
{
return [i](double y) {return std::pow(y, i);};
}
int main()
{
unsigned int n = 3; // the wanted degree in your polynomial basis
auto f = Taylor(n);
double a = f(3);
std::cout << "a = " << a << std::endl;
return 0;
}
In the example above, we would get the output a = 27.
This would be useful in the context of function estimation (i.e., roughly, find the coefficients of some polynomial expansion given data).
Is there some better way to do this? Also, if the polynomial basis is not just x^i but something more complicated, using a lambda function could be inappropriate...
| C++, long before lambdas were added to it, has always had a solution for this:
Just implement a class with an operator(), so that instances become callables, i.e. useful as functions. We call such objects functors.
#include <iostream>
#include <memory>
#include <vector>
// Just an interface base class – not strictly necessary
class realmap {
public:
virtual double operator()(double parameter) = 0;
virtual ~operator();
};
class identity : public realmap {
double operator()(double parameter) override { return parameter; }
};
class twice : public realmap {
double operator()(double parameter) override { return 2 * parameter; }
};
class monomial : public realmap {
private:
const unsigned int exponent;
public:
monomial(unsigned int exponent) : exponent(exponent) {}
double operator()(double parameter) override {
double result = 1;
for (unsigned int pot = 0; pot < exponent; ++pot) {
result *= parameter;
}
return result;
}
};
int main() {
auto cube = monomial(3);
std::cout << cube(1.3) << std::endl;
std::vector<std::unique_ptr<realmap>> operations;
operations.emplace_back(new twice());
operations.emplace_back(new monomial(2));
operations.emplace_back(new twice());
operations.emplace_back(new monomial(3));
double value = 3.141;
for (auto &operation : operations) {
value = (*operation)(value);
}
// now is [(3.141 * 2)²·2]³
std::cout << value << std::endl;
}
|
70,667,492 | 70,667,798 | Obtain using definition from templated class | Given the following classes:
// Some random class
class A { };
// A templated class with a using value in it.
template<class TYPE_B>
class B {
public:
using TYPE = TYPE_B;
};
Next we use these two classes in class C. But if we are using B as the template parameter we would like to obtain the TYPE defined in it.
template<class TYPE_C>
class C {
// A check to see if we have a class of type B
static constexpr bool IS_B = std::is_same<B<int32_t>, TYPE_C>::value ||
std::is_same<B<int64_t>, TYPE_C>::value;
public:
// This is what not works. How to get B::TYPE here?
using TYPE = std::conditional<IS_B, TYPE_C::TYPE, TYPE_C>;
};
Class C would we used like:
C<A> ca;
C<B<int32_t>> cb32;
C<B<int64_t>> cb64;
I am compiling this in GCC. My fear what I would like not have to do is to use the std::is_same statement for each type used with B. Put that in the std::conditional. Are there any alternatives?
| You have two issues in your code:
You are missing a typename before TYPE_C::TYPE. Since TYPE_C::TYPE is a dependent name, you need to use typename to tell the compiler that you are looking for a type.
You cannot use TYPE_C::TYPE ins the std::conditional1 expression because when TYPE_C is not B<>, that expression is invalid, but will still be evaluated.
One simple solution is to use an intermediate template to access the type, using template specialization, e.g.
template <class T>
struct get_C_type {
using type = T;
};
template <class T>
struct get_C_type<B<T>> {
using type = T;
};
template<class TYPE_C>
class C {
public:
// you still need a typename here
using TYPE = typename get_C_type<TYPE_C>::type;
};
1 You probably want to use std::conditional_t or std::conditional<>::type here.
|
70,667,513 | 70,667,652 | CMAKE_CXX_STANDARD vs target_compile_features? | I'm itching to upgrade our project to C++20. My CMakeLists.txt files generally say
set (CMAKE_CXX_STANDARD 17)
set (CMAKE_CXX_STANDARD_REQUIRED ON)
but I get the sense that's not the Right Way to do it. What is the Right Way? Is it this?:
target_compile_features(Foo PUBLIC cxx_std_20)
where Foo is the name of my target (and same for every target?) If I do that, do I the remove all the set (CMAKE_CXX_STANDARD*) lines everywhere?
Along the same lines, If I have
target_compile_features(Foo PUBLIC cxx_std_20)
target_compile_features(Bar PUBLIC cxx_std_17)
target_link_libraries(Bar PUBLIC Foo)
does that mean that when it goes to build Bar it will note that it needs to include headers from Foo and Foo needs cxx_std_20 and cxx_std_20 includes cxx_std_17 and so Bar will be built with C++20?
| The newer alternative is definitely
target_compile_features(Foo PUBLIC cxx_std_20)
And with this you can and should remove the old set(CMAKE_CXX_STANDARD*).
However the new version has an issue if you also want to disable compiler extensions with set(CMAKE_CXX_EXTENSIONS OFF). Its not possible with the new syntax as far as I know and combining both of them does not work either.
And the second part of your question: Yes, cmake will recognize the dependencies and put the compiler in c++-20 mode whenever necessary.
|
70,667,719 | 70,667,834 | Console couts a memory address instead of string | As I understand that strings can be treated like arrays, so I tried to insert each character of a string by iterating with a while loop. However the final cout pointed to a memory address, not the string I hoped it would print.
int main()
{
int i = 0;
int n = 2;
char input;
string str1[n];
while(i<=n){
cout<<"enter letter: ";
cin>>input;
str1[i] = input;
i++;
}
cout<<"Your word is: "<<str1;
return 0;
}
The output was:
enter letter: a
enter letter: b
enter letter: c
Your word is: 0x7ffd505af1f0
How can I print my string at the end, instead of a pointer to a mem address?
More interestingly, when I adjusted the final line to cout str1[n] instead of str1, the console prints the next character in the alphabet from the last input!
cout<<"Your word is: "<<str1[n];
and the output is
enter letter: a
enter letter: b
enter letter: c
Your word is: d
How is this happening?
| When people say that strings are like arrays, they mean specifically "c-strings", which are just char arrays (char*, or char []). std::string is a separate C++ class, and is not like an array. See this question for a definition of C-strings.
In your example, str1 is actually an array of std::strings, and when you print it, you're printing the pointer address.
Below is an example using both C++ std::string, and a C-string, to illustrate the difference. In general, when writing C++, you should prefer std::string.
const int n = 2;
std::string str1; //A c++ std::string, which is not like an array
char cstr1[n+1]; // a c-string, which is array-like
for(int i = 0; i < n; ++i) {
char input = '\0';
cout<<"enter letter: ";
cin>>input;
str1.push_back(input); //Append to c++ string
cstr1[i] = input; //Add to array-like c-string
}
cstr1[n] = '\0'; //Ensure C-string is null-terminated
cout << "As C++: " << str1 << std::endl;
cout << "AS C: " << cstr1 << std::endl;
cout << "C++ can convert to C-string: " << str1.c_str() << std::endl;
Added const to n, to make it valid C++, since you shouldn't create arrays from non-const variables
|
70,667,811 | 70,669,434 | I/O Completion ports C++ And Threadpools | I'm trying to understand which is true, i read in multiple sources that IOCPs can be used to implement a threadpool, i'm using multiple IOCPs each in it's thread to do interprocess communication and i'm trying to reimplement my code to use just one IOCP and a threadpool to manage all my processes.
can i use just one thread and let the IOCP's own internal threadpool manage the asynchronous I/O or do i have to use a Threadpool object to so ?
edit to clarify do the IOCP has it's own threadpool and all i have to do is link my handles to it and let it manage the asynchronous IO ? or do i have to create the treads myself ?
the MSDN documentation is not very clear about this. thanks in advance
|
does the IOCP has it's own internal threadpool ?
no. if you create IOCP ( KQUEUE) by self - you need by self call GetQueuedCompletionStatus[Ex] (ZwRemoveIoCompletion[Ex] ). from which thread(s) - completelly your task.so here you need yourself create some "thread pool" which will be pop packets from IOCP and handle it.
if you use system api for thread pool(s) - it internal use IOCP but you never direct access IOCP - even can not got it handle. here all on system - create IOCP, create thread pool, listen on IOCP, call you callbacks. in this scheme - you instead pop packets from IOCP youself - register some callbacks - which system called when pop packet from IOCP.
for instance - BindIoCompletionCallback
Associates the I/O completion port owned by the thread pool with the specified file handle.
note - I/O completion port owned by the thread pool, but not thread pool owned by the I/O completion port
but in this api - no IOcp handle as parameter. default (because no way here specify another pool) system thread pool used. and it iocp. if file object saved pointer to iocp after this api call and when I/O completed - packet will be queued to this iocp, system pool pop this packet and call your callback.
or CreateThreadpoolIo - do the same thing as BindIoCompletionCallback - Associates the I/O completion port owned by the thread pool with the specified file handle.
but here written in the not the best way
Creates a new I/O completion object.
you may think that new IOCP is created by call this api. but no. some user mode structure - yes, but not new IOCP. object != port here. IOCP is single per thread pool and created only once. by this api.
CreateThreadpool
Allocates a new pool of threads to execute callbacks.
and as part of this task - Creates a new I/O completion port. so indirect - by create new pool - you create new IOCP (despite never have direct access to it). then you need:
To use the pool, you must associate the pool with a callback environment. To create the callback environment, call
InitializeThreadpoolEnvironment. Then, call SetThreadpoolCallbackPool
to associate the pool with the callback environment.
and then you can pass this callback environment to CreateThreadpoolIo for instance. so main different between this api and more old BindIoCompletionCallback - you can use not default thread pool here. however in most case i think - only single, default, thread pool used in process.
so in general - if you create IOCP by self - you by self and need manage it and create dedicated threads, for pop packets from IOCP - this is and called "thread pool"
or you can use system pools. in this case you never direct access IOCP at all. despite this is may be not direct documented - exist exactly single IOCP per thread pool. if you use default only process thread pool - you use and single IOCP too. if you create aditional thread pool - indirect you create additional IOCP.
and IOCP - not create any threads by self. like event object - not create threads, which will be wait on this event
|
70,667,971 | 70,676,906 | Configuring Visual Studio 2019 to automatically pick up the highlighted option from intellisense in C++ by hitting enter | The intro text says it all. I tried messing around with options related with the intellisense on VS, but no success. I mean, it does pick our options via enter, but, by the default, we gotta confirm the selection with the arrow keys first, which is an unnecessary step. Any clues?
| To implement your idea, you need to set Member List Commit Aggressive to true.
The specific path is Tools->Options->Text Editor->C/C++->Advanced->Member List Commit Aggressive.
|
70,668,318 | 70,668,445 | Why does this code compile with MSVC, but not in GCC or Clang? | And how to fix the code?
Here is the code:
https://godbolt.org/z/vcP6WKvG5
#include <memory>
#include <utility>
enum class Format {
Number,
Text,
};
template <template <Format> typename Visitor, typename... Args>
void switchByFormat(Format format, Args&&... args) {
switch(format) {
case Format::Number:
Visitor<Format::Number>::visit(std::forward<Args>(args)...);
break;
case Format::Text:
Visitor<Format::Text>::visit(std::forward<Args>(args)...);
break;
}
}
struct AstNode {};
template <Format format>
struct ANode: public AstNode {};
using AstNodePtr = std::shared_ptr<AstNode>;
template <template <Format> typename AstNodeT,
typename... Args>
struct AstNodeFactory {
template <Format format>
struct Visitor {
static void visit(AstNodePtr& result, Args&&... args)
{
result = std::make_shared<AstNodeT<format>>(std::forward<Args>(args)...);
}
};
};
template <template <Format> typename AstNodeT,
typename... Args>
AstNodePtr makeAstNode(Format format, Args&&... args)
{
AstNodePtr result;
switchByFormat<typename AstNodeFactory<AstNodeT, Args...>::Visitor>(format,
result,
std::forward<Args>(args)...);
return result;
}
int main() {
auto textAnode = makeAstNode<ANode>(Format::Text);
}
Clang link: https://godbolt.org/z/9fxWE9j71
The error in Clang is:
source>:45:64: error: typename specifier refers to class template member in 'AstNodeFactory<ANode>'; argument deduction not allowed here
switchByFormat<typename AstNodeFactory<AstNodeT, Args...>::Visitor>(format,
GCC link: https://godbolt.org/z/4EvrzGWYE
GCC error:
In instantiation of 'AstNodePtr makeAstNode(Format, Args&& ...) [with AstNodeT = ANode; Args = {}; AstNodePtr = std::shared_ptr<AstNode>]':
<source>:52:53: required from here
<source>:45:5: error: 'typename AstNodeFactory<ANode>::Visitor' names 'template<enum class Format format> struct AstNodeFactory<ANode>::Visitor', which is not a type
45 | switchByFormat<typename AstNodeFactory<AstNodeT, Args...>::Visitor>(format,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Since Visitor is a template class rather than a type, you need to specify the template keyword
switchByFormat<AstNodeFactory<AstNodeT, Args...>::template Visitor>(
//^^^^^^^^
format, result, std::forward<Args>(args)...);
Demo.
|
70,669,183 | 70,671,583 | OpenCV returns no error when open is called, but gstreamer does | I have the problem when I open a camera with GStreamer, and the camera is not connected, I don't get an error code back from OpenCV. GStreamer returns an error in the console. When I check if the camera is open with .isOpend() the return value is true. When the camera is connected, it works without any issue.
std::string pipeline = "nvarguscamerasrc sensor_id=0 ! video/x-raw(memory:NVMM), width=(int)3264, height=(int)2464, format=(string)NV12, framerate=(fraction)21/1 ! nvvidconv flip-method=2 ! video/x-raw, width=(int)3264, height=(int)2464, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink"
cap_device_.open(pipeline, cv::CAP_GSTREAMER);
bool err = cap_device_.isOpened();
if (!err) {
printf("Not possible to open camera");
return EXIT_FAILURE;
}
The GStreamer error code in the console is:
(Argus) Error Timeout: (propagating from src/rpc/socket/client/SocketClientDispatch.cpp, function openSocketConnection(), line 219)
(Argus) Error Timeout: Cannot create camera provider (in src/rpc/socket/client/SocketClientDispatch.cpp, function createCameraProvider(), line 106)
Error generated. /dvs/git/dirty/git-master_linux/multimedia/nvgstreamer/gst-nvarguscamera/gstnvarguscamerasrc.cpp, execute:720 Failed to create CameraProvider
[ WARN:0] global /home/nvidia/host/build_opencv/nv_opencv/modules/videoio/src/cap_gstreamer.cpp (933) open OpenCV | GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1
If I understand everything correct, .isOpend() should return false. If not, how can I check if the pipeline is initialized correct?
My system runs with Ubuntu 18.04 on an Nvidia Jetson Nano with a MIPI-CSI camera.
GStreamer version 1.14.5, OpenCV version 4.1.1
| This may just be because of a typo. nvarguscamerasrc has no property sensor_id but has sensor-id. It should work after fixing this.
In not working case, cap.read() should return false.
|
70,669,886 | 70,679,371 | trying to convert functions to c++ how do I change target to scene component |
grapplecomponent.h
protected:
virtual void BeginPlay() override;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool m_hooked;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool m_hookfinished;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FVector m_hook_location;
UFUNCTION(BlueprintCallable)
void m_set_visibility(const bool new_visibility, const bool propagate_to_children);
UFUNCTION(BlueprintCallable)
void m_setworldlocation(const FVector& new_location, const bool sweep, const bool teleport, FHitResult& sweep_hit_result);
grapplecomponent.cpp
void Agrapplecomponent:: m_set_visibility(const bool new_visibility, const bool propagate_to_children)
{
}
void Agrapplecomponent::m_setworldlocation(const FVector& new_location, const bool sweep, const bool teleport, FHitResult& sweep_hit_result)
{
}
I have no idea how to change the target of m_setworldlocation and m_set_visibility to scene component like the normal blueprint function does how do I fix this? the stuff that starts with an M are converted to c++
| The SetVisibility and SetWorldLocation functions already have a C ++ implementation.
Better to call the entire function from C ++:
//.h
UFUNCTION(BlueprintCallable)
void StopGrapple();
//.cpp
void Agrapplecomponent::StopGrapple()
{
FVector Location(0.f, 0.f, 0.f);
m_hooked = false;
m_hookfinished = false;
GrappleHookCable->SetVisibility(false);
GrappleHookCable->SetWorldLocation(Location);
}
Update
In the Blueprint, change the name of the GrappleHookCable to BlueprintGrappleHookCable. Save and Compile. Close UE.
In {ProjectName}.build.cs add "CustomMeshComponent"
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "UMG", "CustomMeshComponent"});
Character:
//.h
#include "CustomMeshComponent.h"
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
UCustomMeshComponent* GrappleHookCable;
//.cpp
Construct
{
GrappleHookCable = CreateDefaultSubobject<UCustomMeshComponent>(TEXT("GrappleHookCable"));
GrappleHookCable->SetupAttachment(GetRootComponent());
}
Compile. Open project. Open Blueprint. Variables -> Components -> Right click "BlueprintGrappleHookCable" -> Replace Reference.
Find "GrappleHookCable" in "Replace with".
Turn on "Only show and replace result from ...".
Click "Find and Replace References in ..."
|
70,670,143 | 70,680,246 | Initialize member array with constructor argument (with plain old arrays) | Very similar to this: C++ Initialize Member Array with Constructor Argument
But I don't use std::array, or rather, really rather not use it if there are other options.
I have this class (simplified):
template<typename T, int length> // Line 53
class StaticArray
{
public:
T items[length];
StaticArray() = default;
StaticArray(T newItems[length]) : items{newItems} { }
};
int main()
{
StaticArray<int, 4> a; // Works (uninitialized)
StaticArray<int, 4> b = StaticArray<int, 4>(); // Works (initialized to 0)
//StaticArray<int, 4> c = StaticArray<int, 4>({}); // Does not compile
//StaticArray<int, 4> d = StaticArray<int, 4>({1, 2, 3, 4}); // Does not compile
//StaticArray<int, 4> e = {1}; // Does not compile
return 0;
}
The lines with a and b work fine. But c does not compile:
....main.cpp:59: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
....main.cpp:66:51: required from here
....main.cpp:59:49: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
59 | StaticArray(T newItems[length]) : items{newItems} { }
| ^~~~~~~~
| |
| int*
Neither does d:
no matching function for call to ‘StaticArray<int, 4>::StaticArray(<brace-enclosed initializer list>)’
....main.cpp: In function ‘int main()’:
no matching function for call to ‘StaticArray<int, 4>::StaticArray(<brace-enclosed initializer list>)’
67 | StaticArray<int, 4> d = StaticArray<int, 4>({1, 2, 3, 4});
| ^
....main.cpp:59:9: note: candidate: ‘StaticArray<T, length>::StaticArray(T*) [with T = int; int length = 4]’
59 | StaticArray(T newItems[length]) : items{newItems} { }
| ^~~~~~~~~~~
....main.cpp:59:23: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘int*’
59 | StaticArray(T newItems[length]) : items{newItems} { }
| ~~^~~~~~~~~~~~~~~~
....main.cpp:58:9: note: candidate: ‘StaticArray<T, length>::StaticArray() [with T = int; int length = 4]’
58 | StaticArray() = default;
| ^~~~~~~~~~~
....main.cpp:58:9: note: candidate expects 0 arguments, 1 provided
....main.cpp:54:7: note: candidate: ‘constexpr StaticArray<int, 4>::StaticArray(const StaticArray<int, 4>&)’
54 | class StaticArray
| ^~~~~~~~~~~
....main.cpp:54:7: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const StaticArray<int, 4>&’
....main.cpp:54:7: note: candidate: ‘constexpr StaticArray<int, 4>::StaticArray(StaticArray<int, 4>&&)’
....main.cpp:54:7: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘StaticArray<int, 4>&&’
e doesn't because StaticArray is not an "aggregate type".
I don't understand the intricacies of C++ well enough to know what's going on here. I do understand that given int a[4]; int b[4]; you can't simply do a = b;. But replacing items{newItems} in the constructor with items{1, 2, 3, 4} works fine, and so does items{{1, 2, 3, 4}}!
I suspect that the whole argument type decay thing is screwing this up.
I can remove all constructors entirely and have e work, but that then allows initialization with lists that are not of the proper size, which is quite silly.
Any pointers to workarounds? I would really rather not faff about with template magic or std::array-like kajiggery. The "purer" the better.
| This constructor:
template<typename... TNewItems>
StaticArray(TNewItems... newItems)
: items{newItems...}
{
static_assert(sizeof...(newItems) == length, "Number of supplied items must match the length of the array.");
}
Use like this:
StaticArray<int, 4> a; // Works (uninitialized for int, calls the default constructor for complex types)
StaticArray<int, 4> b = StaticArray<int, 4>(); // Works (0, 0, 0, 0)
StaticArray<int, 4> c = StaticArray<int, 4>({}); // Weirdly works (0, 0, 0, 0; does not call the custom constructor)
StaticArray<int, 4> d = StaticArray<int, 4>({1, 2, 3, 4}); // Works (1, 2, 3, 4)
StaticArray<int, 4> e = {1, 2, 3, 4}; // Works (1, 2, 3, 4)
//StaticArray<int, 4> f = StaticArray<int, 4>({1, 2}); // Fails to compile
//StaticArray<int, 4> g = {1, 2}; // Fails to compile
The template-magic is reasonably minimal. Error messages for wong types (as far as C++ catches wrong types in general) in the initializer list are quite legible, even for templated classes.
The static_assert allows checking for an incorrect number of items. The error message in case of a mismatch is very legible.
The empty initializer list causing everything to be initializd to 0 is a bit weird, but not too bad.
|
70,670,599 | 70,671,134 | Templated operator=() and overload resolution | Consider the following code snippet:
#include <utility>
struct test {
template <class Other>
test& operator=(Other&&);
int& i_;
};
int main() {
int i = 0;
test t1{i}, t2{i};
t1 = std::move(t2); // tries to select the implicitly-declared one!
}
When trying to compile with GCC11.1 (with -std=c++2a), it attempts to select the compiler-generated operator=, which is deleted, and fails. The previous GCC versions successfully build this code.
To my understanding, the implicitly-generated deleted operator= is not viable, so the operator template should be selected. Is it a GCC bug or am I missing something?
| It seems like a bug. It looks for templated method on GCC 11.2 but as you mentioned, it sees deleted method on GCC 11.1.
|
70,670,604 | 70,670,815 | Avoid code duplication between two functions, but one returns in the middle of the code | Lets say i have two functions inside a class:
vector<int> getAllPossibleNumbers() {
vector<int> nums;
for (int i=0; i < MAX; i++)
if (isAPossibleNumber(i))
nums.push_back(i);
return nums;
}
bool hasAtLeastOnePossibleNumber() {
for (int i=0; i < MAX; ++i)
if (isAPossibleNumber(i))
return true;
return false;
}
I could rewrite the second function as
bool hasAtLeastOnePossibleNumber() {
return getAllPossibleNumbers().size() > 0;
}
But it's obvious, especially with a very high MAX number, how the first is much more efficent.
So, how can I avoid code duplication of this kind?
I would prefer a general solution, that can work with more complicated functions and can compile with C++11.
| One option would be to move most of the logic into a third function with a callback to the outer functions which gives the numbers. The result of the callback can be used to determine whether to continue the loop:
template <typename Callback>
void checkNumbers(Callback callback)
{
for (int i=0; i < MAX; i++)
{
if (isAPossibleNumber(i))
{
if (!callback(i))
{
break;
}
}
}
}
std::vector<int> getAllPossibleNumbers() {
std::vector<int> nums;
checkNumbers([&](int i){ nums.push_back(i); return true; });
return nums;
}
bool hasAtLeastOnePossibleNumber() {
bool result = false;
checkNumbers([&](int i){ result = true; return false; });
return result;
}
The extra function should be optimised away by modern compilers.
|
70,670,766 | 70,673,487 | Copying with memcpy externally? | Is it possible to copy a function to an external application's shared library in memory? If so, how? I'm trying to achieve external hooking by making a trampoline hook externally.
| This require very deep understanding of the binary formats used by the operating system. Not all code is relocatable, your code must be compiled with -fPIC for this to work for sure. You will need also to resolve manually all external symbols. In fact, you will have reimplement parts of the ELF loader. It is possible but definitely not trivial and very machine dependant.
Also you will have to find a way around the new execution restriction - nowadays most OSs have various protections against writing in executable memory regions.
|
70,671,328 | 70,671,397 | Why segmentation fault in this simple C ++ program? | I am trying to merge two sorted subarrays. I have spent hourse of frustration removing segmentation fault error in vs code but with no success.
I am using a temporary array to store the newly ordered array.
comparing elements of two subarrays simultaneously and incrementing the index of the subarray whose arr[index] is smaller.
Copying the leftover elements of the subarray whose traversal index has not reached the end.
#include<iostream>
#include<math.h>
using namespace std;
void merge(int start1,int end1,int start2,int end2,int arr[],int temp_arr[]){
int i = start1;
int j = start2;
while (i <= end1 && j <= end2)
{
if(arr[i] < arr[j]){
//using start1 as index on purpose
temp_arr[start1++] = arr[i];
i++;
}else{
temp_arr[start1++] = arr[j];
j++;
}
}
//if first array elements are left
while(i <= end1 ){
temp_arr[start1++] = arr[i];
}
//if second array elements are left
while(j <= end2){
temp_arr[start1++] = arr[j];
}
}
int main(){
int arr[] = {5,6,7,1,2,3};
int n = sizeof(arr)/sizeof(int);
int temp[n];//temporary array
int a;
//to find where the next sorted subarray begins
for(int i = 0;i <n-1;i++){
if(arr[i] > arr[i+1]){
a= i;
break;
}
}
merge(0,a,a+1,n-1,arr,temp);
for(int i = 0;i < n;i++){
cout << temp[i] << " ";
}
}
| This is an infinite loop:
while(i <= end1 ){
temp_arr[start1++] = arr[i];
}
So is this one.
while(j <= end2){
temp_arr[start1++] = arr[j];
}
In both cases, since neither i, j, end1, nor end2 ever change in these loops, start1 will keep increasing way past the array boundary, introducing more undefined behavior on each iteration that makes an assignment.
That may not be your only bug.
|
70,671,329 | 70,671,385 | c++ - conditional assignment of const, without ternary? | suppose I want to assign a const variable based on complex calculations which depend on a conditional.
if the situation were simple, I could do:
const int N = myBool ? 1 : 2;
but it's more like
const int N = myBool ? <lengthy calculation> : <other lengthy calculation>;
What I'm doing is this, but I'd like something cleaner:
int N_nonconst;
if (myBool) {
N_nonconst = <lengthy calculation>;
}
else {
N_nonconst = <other lengthy calculation>;
}
const int N = N_nonconst;
obviously, I could also do this:
int possibility1 = <lengthy calculation>;
int possibility2 = <other lengthy calculation>;
const in N = myBool ? possibility1 : possibility2;
but I'd like to actually perform only one of those lengthy calculations.
If I were extending the language, I'd consider making something like a const_deferredAssignment declaration:
const_deferredAssignment int N;
if (myBool) {
N = <...>;
}
else {
N = <...>;
}
I could also wrap those calculations up in functions/methods, but they use a bunch of locals, so it would be a fairly verbose function call.
| You could wrap each calculation in a lambda, and capture the local variables to reduce the verbosity of their arguments
{
// ...
auto firstFunc = [&]() -> int { ... };
auto secondFunc = [&]() -> int { ... };
const int N = myBool ? firstFunc() : secondFunc();
}
In this way only one of the two functions are actually executed.
|
70,672,136 | 70,673,480 | why "missing double brace warning" for BaseClass Aggregate initialisation in Clang 12 but not Clang 13 or GCC 11? | This code compiles without warning in GCC 11 and Clang 13 (in C++20 mode)
struct A {
int x, y;
};
struct B : A { };
int main () {
A a{1,2};
B b{3,4}; // Clang 12 wants B b{{3,4}}
return a.x * b.x + a.y * b.y;
}
but in Clang 12 We get
<source>:10:9: warning: suggest braces around initialization of subobject [-Wmissing-braces]
B b{3,4};
https://godbolt.org/z/Kdnon9575
Might be related to:
Why does Clang 12 refuse to initialize aggregates in the C++20 way?
and these papers
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0960r3.html
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1975r0.html
Are single braces officially supported (without warnings) under C++20 for initialising these simple POD Derived classes? If so, where does the standard say that, so we can rely on it?
In C++17 the double braces are required, to avoid warnings, yes?
And in C++14 single braces are a hard error because a derived struct is not an aggregate, yes?
| C++17 as well as C++20, https://timsong-cpp.github.io/cppwp/n4659/dcl.init.aggr#12 and https://timsong-cpp.github.io/cppwp/n4868/dcl.init.aggr#15, respectively, allows brace elision for the initialization of aggregates:
Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the members of a subaggregate; it is erroneous for there to be more initializer-clauses than members. If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializer-clauses from the list are taken to initialize the members of the subaggregate; any remaining initializer-clauses are left to initialize the next member of the aggregate of which the current subaggregate is a member.
Class B in the OP's example is an aggregate in both C++17 and C++20 (as per C++17's P0017R1 and its updates primarily to [dcl.init.aggr]/1), where the requirements for what qualifies as an aggregate has been made more lenient with regard to the base class requirement.
An aggregate is an array or a class ([class]) with
[...]
(C++14) no base classes
(C++17 and C++20) no virtual, private, or protected base classes
Now, the Clang diagnostic was only a warning to begin with, and as of Clang 13 it seems to have (imo correctly) have been removed for braced-elided initalization of aggregates that have base classes. It's possible the warning was a remnant corner case from C++14 where B was not an aggregate, but where the program would be ill-formed due to an invalid form of initialization.
|
70,672,159 | 70,672,280 | I am working on a project and I am trying to create a folder and a file inside of the folder but it doesn't work | This is my function:
void Mail::send_mail(int id, std::string send_to, std::string subject, std::string message) {
int receiever_id = find_user(send_to);
std::fstream file("/mails/" + send_to + "/" + std::to_string(accounts.at(receiever_id).number_of_mails) + ".txt", std::ios::out);
email *mail = new email("From: " + accounts.at(id).username, "Subject: " + subject, "Content: " + message);
accounts.at(receiever_id).inbox.push_back(*mail);
file<<"From: "<<accounts.at(id).username<<std::endl;
file<<"Subject: "<<subject<<std::endl;
file<<"Content: "<<message;
accounts.at(receiever_id).number_of_mails++;
delete mail;
rewrite();
return;
}
I want to create a folder mails and a folder with the name of the receiver if it doesn't exist and then create a txt file inside, but for some reason It doesn't work. I can't use external libraries or system functions.
| as @Eugene mentioned in the comments, you cannot create a file inside a directory that doesn't exist. C++ will not create the directory for you first.
you can use boost to create the directory first, then proceed with your logic.
#include <boost/filesystem.hpp> boost::filesystem::create_directory("dirname");
the reason for using boost is for your code to be cross-platform and work on different operating systems. You can use system() and pass it the command for creating a directory on your OS.
for example, on Linux, this would something like this:
system(“mkdir user1”);
|
70,672,879 | 70,673,697 | Linking custom library with libcurl functions | I have a custom static library called "libcurlwrapper", which just wrapps the execution of libcurl functions, and a main app which calls the library's function.
Compiling the library works, but when it comes to linking the main app I get these errors:
/usr/bin/ld: .//libcurlwrapper.a(curl_wrapper.o): in function `http3_demo()':
curl_wrapper.cpp:(.text+0xd): undefined reference to `curl_easy_init'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x39): undefined reference to `curl_easy_setopt'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x54): undefined reference to `curl_easy_setopt'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x60): undefined reference to `curl_easy_perform'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x73): undefined reference to `curl_easy_strerror'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x9d): undefined reference to `curl_easy_cleanup'
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: all] Error 1
What exactly causes these linker errors?
Ideas how to get rid of them?
Any Help is appreciated!
Thanks
libcurlwrapper > curl_wrapper.h:
#pragma once
#include <curl/curl.h>
void http3_demo();
libcurlwrapper > curl_wrapper.cpp:
#include "curl_wrapper.h"
void http3_demo() {
// Source taken from here: https://curl.se/libcurl/c/http3.html
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_3);
// Perform the request, res will get the return code
res = curl_easy_perform(curl);
// Check for errors
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
// Always cleanup
curl_easy_cleanup(curl);
}
printf("http3_demo: endmarker");
}
libcurlwrapper > Makefile:
CXX = g++
CXXFLAGS = -lcurl
all:
@$(CXX) -c ./curl_wrapper.cpp $(CXXFLAGS)
@ar -rc libcurlwrapper.a ./curl_wrapper.o
main_app > main.cpp:
#include "curl_wrapper.h"
int main() {
http3_demo();
return 0;
}
main_app > Makefile:
CXX = g++
CXXFLAGS = -L ./ -lcurlwrapper
all:
@$(CXX) main.cpp $(CXXFLAGS) -o main_app
| A static library is compiled into the final executable. External functions used by a static library are just references. The main executable that uses the static library will need to resolve the references to all of the external libraries that the static library refers to. In this case, that means the main executable project needs to link to the libcurl library.
|
70,673,381 | 70,673,429 | OpenGL Project - objects not keeping filling color on movement | When I execute the code I get a hot air balloon formed of three elements. My issue is that when I move the objects from the keyboard, the objects loose color, and become more like wire than solid.
From what I discovered until now, my trouble comes from this function call:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
But I need it to make the ropes...
/*
This program shows a hot air balloon rotating around its own axe to the left and to the right
*/
#include "glos.h"
#include<math.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glaux.h>
void myinit(void);
void CALLBACK display(void);
void CALLBACK myReshape(GLsizei w, GLsizei h);
void CALLBACK rotateRight(void);
void CALLBACK rotateLeft(void);
static GLfloat x = 0;
static GLfloat y = 0;
static GLfloat z = 0;
static GLfloat alfa = 0;
double PI = 3.14159265;
void myinit (void) {
glClearColor(1.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
}
void CALLBACK rotateLeft(void) { y -= 5; }
void CALLBACK rotateRight(void) { y += 5; }
void CALLBACK display (void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(x, 1, 0, 0);
glRotatef(y, 0, 1, 0);
glTranslatef(0, -80, 0);
//cube = basket
glColor3f(1, 1, 0);
auxSolidCube(50);
//full sphere = baloon
glPushMatrix();
glColor3f(1.0, 0.0, 0.0);
glTranslatef(0,200,0);
glRotatef(-90, 1, 0, 0);
auxSolidSphere(130.0);
glPopMatrix();
//polygon cylinder = ropes
glPushMatrix();
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_QUAD_STRIP);
glColor3f(0.0, 1.0, 1.0);
for (alfa = 0; alfa <= 360; alfa+=30) {
glVertex3f(65 * sin((PI * alfa) / 180), 100, 65 * cos((PI * alfa) / 180));//top of the cylinder
glVertex3f(15 * sin((PI * alfa) / 180),0, 15 * cos((PI * alfa) / 180));//base of the cylinder
}
glEnd();
glPopMatrix();
glPopMatrix();
glFlush();
}
void CALLBACK myReshape(GLsizei w, GLsizei h)
{
if (!h) return;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho (-400,400, -400 *(GLfloat)h / (GLfloat)w, +400.0*(GLfloat)h/(GLfloat)w, -1000.0, 1000.0);
else
glOrtho (-400*(GLfloat)w / (GLfloat)h, 400.0*(GLfloat)w/(GLfloat)h, -400, 400.0, -1000.0, 1000.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv)
{
auxInitDisplayMode (AUX_SINGLE | AUX_RGB | AUX_DEPTH);
auxInitPosition (100, 0, 600, 400);
auxInitWindow ("Hot air balloon");
myinit ();
auxKeyFunc(AUX_RIGHT, rotateRight);
auxKeyFunc(AUX_LEFT, rotateLeft);
auxReshapeFunc (myReshape);
auxMainLoop(display);
return(0);
}
| OpenGL is a state engine. Once a state has been set, it is retained until it is changed again, even beyond frames. Therefore, you need to set the polygon mode GL_FILL before rendering the solid geometry:
void CALLBACK display (void)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// render solid geometry
// [...]
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// render wireframe geometry
// [...]
}
|
70,673,958 | 70,679,767 | Handling MF_E_TRANSFORM_STREAM_CHANGE from video decoder MFT | I am trying to decode even just a single H264 frame with the H264 Decoder MFT, but I've been having problems with ProcessOutput(). I've reduced the bad HRESULT's as much as I can, but I'm currently stuck on dealing with MF_E_TRANSFORM_STREAM_CHANGE. This occurs after I set the pSample equal to my allocated output_sample and call ProcessOutput(), since this decoder requires you allocate your own sample. I tried resetting the output type using SetOutputType() to what I had in my configure_decoder() function, but alas I get a bad HRESULT. Not sure what to do next.
| You just need to follow this at Handling Stream Changes:
The client calls IMFTransform::GetOutputAvailableType. This method returns an updated set of output types.
The client calls SetOutputType to set a new output type.
The client resumes calling ProcessInput/ProcessOutput.
In the question body above you are trying to do 3 without doing 2. Most likely your media type is somewhat different from MFT's so it is likely to reject it and it blocks the processing until this is resolved.
|
70,674,025 | 70,677,926 | QDoubleValidator and QLineEdit onEditFinished conflict? | I'm hoping to get some insight into a issue I'm facing using QDoubleValidator, I have created a widget to collect some information, and would like to have some fields validated as Double values, I have done so here:
orderform::orderform(QWidget *parent) :
QDialog(parent),
ui(new Ui::orderform)
{
ui->setupUi(this);
this->setWindowTitle("Order Entry / Edt");
ui->edtOrderDate->setDate(QDate::currentDate()); //Sets date box to current date
//----- Validator for float input in 'money' fields -----//
auto dv = new QDoubleValidator(0.0,5.0,2);
ui->edtSoldFor->setValidator(dv);
ui->edtItemSubtotal->setValidator(dv);
ui->edtShipping->setValidator(dv);
ui->edtSalesTaxPFC->setValidator(dv);
ui->edtDiscount->setValidator(dv);
ui->edtOrderTotal->setValidator(dv);
ui->edtTotalFee->setValidator(dv);
ui->edtVAT->setValidator(dv);
ui->edtFeeIncVAT->setValidator(dv);
ui->edtBoughtFor->setValidator(dv);
ui->edtSupSubTotal->setValidator(dv);
ui->edtSupShipping->setValidator(dv);
ui->edtSupTax->setValidator(dv);
ui->edtSupOrderTotal->setValidator(dv);
ui->edtAddExpense->setValidator(dv);
ui->edtAddDiscount->setValidator(dv);
//----- -----//
}
in addition each of these fields has a slot assigned to them to run a calculation when editing the field finishes, here is an example:
void orderform::on_edtSoldFor_editingFinished()
{
calcPltfrmOrderTotals();
}
and here is the function it calls:
void orderform::calcPltfrmOrderTotals() //This function is used to calculate all totals
{
//Var:
double valueAsDouble = 0;
QString valueAsString;
//Calc Order Sub Total
valueAsDouble = (ui->edtBoughtFor->text().toDouble() * ui->sbSupQty->value());
valueAsString = QString::number(valueAsDouble);
ui->edtSupSubTotal->setText(valueAsString);
//Calc Supplier Sub Total
valueAsDouble = (ui->edtSoldFor->text().toDouble() * ui->sbItemQty->value());
valueAsString = QString::number(valueAsDouble);
ui->edtItemSubtotal->setText(valueAsString);
//Calc Order Total on platform
valueAsDouble = ((ui->edtItemSubtotal->text().toDouble() + ui->edtShipping->text().toDouble() + ui->edtSalesTaxPFC->text().toDouble()) - ui->edtDiscount->text().toDouble());
valueAsString = QString::number(valueAsDouble);
ui->edtOrderTotal->setText(valueAsString);
//Calc fee total on platform
valueAsDouble = (ui->edtTotalFee->text().toDouble() + ui->edtVAT->text().toDouble());
valueAsString = QString::number(valueAsDouble);
ui->edtFeeIncVAT->setText(valueAsString);
//Calc Supplier Order Total
valueAsDouble = (ui->edtSupSubTotal->text().toDouble() + ui->edtSupShipping->text().toDouble() + ui->edtSupTax->text().toDouble());
valueAsString = QString::number(valueAsDouble);
ui->edtSupOrderTotal->setText(valueAsString);
//Calc PNL
valueAsDouble = (((ui->edtItemSubtotal->text().toDouble() - ui->edtFeeIncVAT->text().toDouble()) - ui->edtSupOrderTotal->text().toDouble())
- ui->edtAddExpense->text().toDouble()) + ui->edtAddDiscount->text().toDouble();
valueAsString = QString::number(valueAsDouble);
ui->lcdPNL->display(valueAsDouble);
};
the problem is before I added the validation to the fields, the calculations would run correctly and instantly after the edit finishes, but as soon as i add the validation the calculations on 'editfinish' is very hit and miss, sometime it works and other times it doesn't and i have no idea why.
| Maybe your validator range (0.0 to 5.0) is too narrow. If a newly calculated value falls outside the range, the validator state won't be QValidator::Acceptable anymore, and, as a side effect, the line edit will no longer emit the editingFinished signal.
You could try keeping the validator's top() to its default (infinity) value, maybe using the other constructor and using setters to set decimals and range bottom:
auto dv = new QDoubleValidator();
dv->setDecimals(2);
dv->setBottom(0.0);
|
70,674,194 | 70,674,327 | Why does my program enters into an infinite loop when my char variable reaches the [del] character (127) value? | Here's my code:
#include <iostream>
int main()
{
char x = 32;
while (x <= 126) {
std::cout << x << "\n";
x += 1;
}
}
Until here, all goes right, but if I change my code to:
#include <iostream>
int main()
{
char x = 32;
while (x <= 127 /* here the "bad" change */ ) {
std::cout << x << "\n";
x += 1;
}
}
to try to print the [del] character, my program goes into an infinite loop and starts to print a lot of other characters which I don't want. Why?
| When x reach 127 it's flipped to -128 in the next round [-128 to 127]
|
70,674,601 | 70,674,963 | How do I declare a member variable within the constructor that doesn't have a predefined type? | I'm trying to declare a member variable of a class with a type that isn't defined during compilation. I read this article where C++17 fixed template constructors by just redacting the type paramater for a template constructor call. (I probably read it wrong because i'm getting errors.)
class theClass {
template <typename UDEF> theClass(UDEF var) : memberVar(var) {}
auto memberVar{ NULL };
};
int main() {
int number = 3;
theClass the(number); // Something something C++17
}
Does anybody have any workarounds? Maybe the new operator? This confuses me a lot. I'm getting super generic errors:
Error (active) E0330 "theClass::theClass(UDEF var) [with UDEF=int]" (declared at line 4) is inaccessible ConsoleApplication1```
Error (active) E1598 'auto' is not allowed here ConsoleApplication1
EDIT: I tried putting the template at the initializer list as such:
template <typename UDEF> theClass(UDEF var) : UDEF memberVar(var) {}
And didn't get any IntelliSense errors, but i'm afraid it won't compile.. It's an initializer list after all, not a declaration list, right? And the odd constructor template call thingy still gives an error.
| The template should be on the class, to have a member use the template parameter:
template <typename UDEF>
class theClass {
UDEF memberVar {};
public:
theClass(UDEF var) : memberVar(var) {}
};
Now your main can create an object like that:
int main() {
int number = 3;
theClass the(number); // CTAD, C++17
}
|
70,674,723 | 70,675,458 | How to push back a vector onto a vector of vectors using an iterator | I have this code that creates an error:
#include <vector>
#include <iostream>
#include <string>
void read_string(std::string &str,
std::vector<std::string> &dir,
std::vector<std::vector<std::string> > &table,
std::vector<std::vector<std::string> > &result)
{
std::vector<std::vector<std::string> >::iterator it0;
std::vector<std::string>::iterator it1;
/*intent, iterate over each element (vector of strings) of the
vector of elements */
for(it0 = table.begin(); it0 != table.end(); it0++){
/*code to select specific vector of strings -added back to show intent*/
if((*it0)[0]==str){
/*selected vector of strings(element) are added to new table
called "result" */
for(it1 = (*it0).begin(); it1 != (*it0).end(); it1++){
result.push_back(*it1);
}
}
}
}
test.cc:18:28: error: no matching function for call to ‘std::vector<std::vector<std::__cxx11::basic_string<char> > >::push_back(std::__cxx11::basic_string<char>&)’
result.push_back(*it1);
The intent of this code is to copy table onto result. What is the proper solution for this? In other words, how would you copy a vector of vectors onto another vector of vectors?
| Oops, yes too many layers (I should have understood the first comment) - This is the desired code -
void read_string(std::string &str,
std::vector<std::string> &dir,
std::vector<std::vector<std::string> > &table,
std::vector<std::vector<std::string> > &result)
{
std::vector<std::vector<std::string> >::iterator it0;
std::vector<std::string>::iterator it1;
//std::copy_if(table, table.size(), [](std::string p_str) {return
for(it0 = table.begin(); it0 != table.end(); it0++){
if((*it0)[0]==str){
result.push_back(*it0);
}
}
}
|
70,675,511 | 70,683,424 | IddCX header results in errors for pure C compilation | I am trying to use pure C for a windows driver I am working on. Its a driver using IddCx (um/iddcx/iddcx.h). This header has a 'extern "c"` wrapper to allow for C compilation. The issue is the code within the 'extern "C"' block is not C. I get these two issues.
enum declarations like this:
enum IDDCX_MONITOR_MODE_ORIGIN : UINT
{
IDDCX_MONITOR_MODE_ORIGIN_UNINITIALIZED = 0,
/// <summary>
/// Indicates that the driver added this mode from directly processing the monitor description
/// </summary>
IDDCX_MONITOR_MODE_ORIGIN_MONITORDESCRIPTOR = 1,
/// <summary>
/// Indicates that the driver did not add this mode as a direct resolution of processing the modes
/// supported by the monitor but because of separate additional knowledge it has about the monitor
/// </summary>
IDDCX_MONITOR_MODE_ORIGIN_DRIVER = 2,
};
which results in errors like this (in C i dont think you can define a type for an Enum):
error C2059: syntax error: ':'
and function declarations like this:
typedef
_Function_class_(EVT_IDD_CX_PARSE_MONITOR_DESCRIPTION)
_IRQL_requires_same_
NTSTATUS
NTAPI
EVT_IDD_CX_PARSE_MONITOR_DESCRIPTION(
_In_
const IDARG_IN_PARSEMONITORDESCRIPTION* pInArgs,
_Out_
IDARG_OUT_PARSEMONITORDESCRIPTION* pOutArgs
);
which results in errors like this (due to structs not given a typedef, and therefore needing to be prefixed with "struct"):
error C2143: syntax error: missing ')' before '*'
error C2143: syntax error: missing '{' before '*'
error C2143: syntax error: missing ';' before '*'
warning C4218: nonstandard extension used: must specify at least a storage class or a type
error C2059: syntax error: ')'
warning C4218: nonstandard extension used: must specify at least a storage class or a type
If the header didnt have any extern C wrappers, I would assume its a Cpp only API and use Cpp instead. But it does have them, so it should compile just fine. Either there is some flag I need to set for this to work, or this is a mistake on microsoft's part. If its a mistake on their part ill report the bug and create my own header to use for now.
Also, is there a place where I should be reporting this to microsoft if it is a bug?
| IddCx seems to suppose to be C compliant, but its not. I have reported the issue to microsoft. I have created a temporary custom header file that is compliant. It compiles just fine now.
|
70,675,513 | 70,675,581 | C++ count() function displays 1's and 0's rather than a total count when reading from a text file | When counting a simple string, this works:
string x = "aabbcc";
int n = count (x.begin(), x.end(), 'a');
cout << n;
This outputs '2' which is correct.
However, when I read in the string from a text file:
ifstream myFile;
myFile.open(argv[1]);
string x;
if (myFile.is_open()) {
while (myFile) {
x = myFile.get();
int n = count(x.begin(), x.end(), 'a');
cout << n;
This outputs 0's and 1's, the 1's appearing where the 'a's would appear.
Instead, I want a total count of a's.
Thanks in advance.
| get() function is extracting a character at a time and passing it to variable X.
in every iteration of the while loop, X is of size 1.
Variable n contains the counts of 'a' character in the One character X has in it.
so, your output is instead number of a's in every single character of the file.
For the case when the character is actually 'a', You get to count that it found ONE count of a.
use this:
easy option:
change n to static
static int n = 0;
while (myFile) {
x = myFile.get();
n += count(x.begin(), x.end(), 'a');
}
cout<<n;
hard option
use a different get() function variation that gives you whole string. Pass that to string variable X
|
70,675,605 | 70,675,680 | Is there a better way to see which function caused a exception other than using catch | I'm having problems with locating the address from which a error occurred, my whole code is running inside of a "try" statement and sadly whenever something is wrong I need to find the error using the old try and fail method by deleting parts of my code. Is there a better way to do it?
My current code:
try
{
do
{
if (somefunction)
if (somefunction2)
if (somefunction3)
if (somefunction4)
}
while (false);
}
catch (...)
{
// todo: somehow get the address where the error occurred
Logger::Log("Exception\n");
}
| A simple solution to find out where an exception comes from is to use a unique message within each function. Catch the exception object and print the message. Or perhaps use even a different type of exception which will allow you to efficiently handle each case differently if that's what you want to do.
As for getting an "address", the trace of function calls that lead to the current point of execution is called a stacktrace (or backtrace). The stacktrace would contain information such as addresses. Theres no standard way to get a stacktrace yet, although it has been proposed for C++23.
However, once you've caught the exception, the stack will have been "unwound" such that you can't know where the exception came from. What you could do, is get the stack trace in the code that may be throwing (each of them since you don't know which one is the thrower) and store the trace in the exception. A central place to do that would be within the constructor of a custom exception type. This pattern is common in standard exception handling of modern languages.
Lastly, you don't necessarily need to make any changes to the program, if you instead run the program in a debugger and break on a throw, you can get all the information you can possibly get.
|
70,675,775 | 70,675,873 | How to calculate if a point is within a circle | I am given a constructor:
Circle::Circle(const Point& c, float r) {
x_ = c.getX();
y_ = c.getY();
r_ = r;
}
All values have been initialised as shown. In the parameter I have Point& - This just allows me to get the x and y coords using a function from a different class. Also, I have "r" which will take in the radius value.
Using this I want to check whether that: If o is a circle, it returns true if and only if p is on the inside or the boundary of the circle
For example,
I am given: Point p(1,2); & Circle c(p,3);
I want to check if Point(3.9,2) is on the inside or on the boundary of Circle c(p,3);
For extra reference, I will provide the Point Constructor:
Point::Point(float x, float y) {
x_ = x;
y_ = y;
}
Initialised constructor to allow me to create getter and setters for use in other classes.
In my function I have tried this :
bool Circle::contains(const Point& p) const {
bool results;
if( ( (getX()-p.getX() ) * ( getX()-p.getX() ) ) + ( ( (getY()-p.getY() ) * ( getY()-p.getY() ) ) <= (getR()*getR())))
{
results = true;
}
else {results = false;}
return results;
}
This did not work.
Test Case I am given:
Point p(1,2);
Circle c(p,3);
if (!c.contains(p)) errorOut_("c does not contain p?",1);
if (!c.contains(Point(3.9,2))) errorOut_("c does not contain (3.9,2)?",1);
if (!c.contains(Point(3.1,4.1))) errorOut_("c does not contain (3.1,4.1)?",1);
if (!c.contains(Point(-1.1,4.1))) errorOut_("c does not contain (-1.1,4.1)?",1);
if (!c.contains(Point(-1.1,-0.1))) errorOut_("c does not contain (-1.1,-0.1)?",1);
if (!c.contains(Point(3.1,-0.1))) errorOut_("c does not contain (3.1,-0.1)?",1);
if (c.contains(Point(3.2,4.2))) errorOut_("c contains (3.2,4.2)?",1);
if (c.contains(Point(-1.2,4.2))) errorOut_("c contains (-1.2,4.2)?",1);
if (c.contains(Point(-1.2,-0.2))) errorOut_("c contains (-1.2,-0.2)?",1);
if (c.contains(Point(3.2,-0.2))) errorOut_("c contains (3.2,-0.2)?",1);
The result:
fail1: c contains (-1.2,4.2)?
fail1: c contains (-1.2,-0.2)?
fail1: c contains (3.2,-0.2)?
| To check whether point lies inside circle, you need to implement this formula (strict < if you don't need points at circumerence):
(px-cx)*(px-cx) + (py-cy)*(py-cy) <= r*r
Squared distance from point to center should be less than squared radius (to avoid sqrt calculation)
For your example
(3.9-1)^2+(2-2)^2 = 8.41 < 3*3=9 - inside
Corrected your function:
bool Circle::contains(const Point& p) const {
return ( ( (getX()-p.getX() ) * ( getX()-p.getX() ) ) +
( ( (getY()-p.getY() ) * ( getY()-p.getY() ) ) <= (getR()*getR())))
}
|
70,676,083 | 70,679,095 | Returning the right number of islands using Union Find | I am solving a question on LeetCode.com called Number of Islands:
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
I know how to solve it with DFS, but I am learning union-find and came up with the below approach:
class Solution {
public:
vector<int> parent, sz;
int counter;
int find(int i) {
if(parent[i]==i) return i;
return parent[i]=find(parent[i]);
}
void unionf(int one, int two) {
int p1=find(one);
int p2=find(two);
if(p1==p2) return;
if(sz[one]<sz[two]) {
parent[one]=two;
sz[two]+=sz[one];
} else {
parent[two]=one;
sz[one]+=sz[two];
}
counter--;
}
int numIslands(vector<vector<char>>& grid) {
int m=grid.size(), n=grid[0].size();
parent.resize(m*n);
iota(begin(parent),end(parent),0);
sz.resize(m*n,1);
counter=0;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(grid[i][j]=='0') {
continue;
}
//grid[i][j]=='1'; an island
counter++;
int idx=i*n+j;
//traverse all 4 neighbors
if(i+1<m && grid[i+1][j]=='1') unionf(idx,(i+1)*n+j);
if(i-1>=0 && grid[i-1][j]=='1') unionf(idx, (i-1)*n+j);
if(j+1<n && grid[i][j+1]=='1') unionf(idx, i*n+j+1);
if(j-1>=0 && grid[i][j-1]=='1') unionf(idx, i*n+j-1);
}
}
return counter;
}
};
It produces right answers on the sample inputs, but wrong answer for [["1","1","1"],["0","1","0"],["1","1","1"]].
At a high level, my logic is that whenever I encounter an island (1), I increment the counter and call unionf() and try to unify it with its neighbors. If such a unification is possible, I decrement counter in unionf(), since it is linked to its parent island (a connected component) and not a new island.
Could someone please point out what I am missing in my logic? Thanks!
| Add some debug print shows some issues in union: Demo.
Changing to:
void unionf(int one, int two) {
int p1=find(one);
int p2=find(two);
if (p1 == p2) return;
if (sz[p1] < sz[p2]) {
parent[p1] = p2;
sz[p2] += sz[p1];
} else {
parent[p2] = p1;
sz[p1] += sz[p2];
}
std::cout << "union:" << one << " and " << two
<< "(p1: " << p1 << ", p2: " << p2 << ")" << std::endl;
counter--;
}
fix the issue (not sure about island size though).
Demo
|
70,676,092 | 70,679,213 | CodeLite IDE is not reading file | So I have a Test folder inside my workspace in CodeLite and inside Test folder I have:
main.cpp
test.txt
The problem is whenever I try to read from test.txt, the compiler deletes the file content and writes "Debug/main.cpp.o" inside my test.txt file. For example, if my txt file contains the following text:
Abcd ef
And my code inside main.cpp:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string data;
ifstream infile;
infile.open("text.txt");
cout << "Reading from the file" << endl;
infile >> data;
return 0;
}
When I run my code the output should be:
Reading from file
Abcd
ef
But instead, the output is:
Reading from file
And now my test.txt contains:
Debug/main.cpp.o
I am also inserting what my folder contains:
I don't know why it does this. Can anyone help?
| Codelite generates $(project).txt ($(project) is Test in your case) with all objects filename for compilation (as response file (to bypass limit of command line length when there are too many files)).
Either place project in another directory or rename the file or project to avoid the conflict with that file.
|
70,676,299 | 70,676,516 | "Unresolved external symbol" for global variables | I created a global file (Globals.h) to hold my global renderer (gRenderer) and my global window (gWindow). I declared them as extern as they'll be defined inside initWindow() & initRenderer() functions under InitChess.cpp.
Some reason the linker is complaining that I have "unresolved external symbols", even though I define them in functions under InitWindow.cpp.
Errors:
Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "struct SDL_Window * gWindow" (?gWindow@@3PEAUSDL_Window@@EA) Chess C:\Users\\source\repos\Chess\Chess\InitChess.obj
Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "struct SDL_Renderer * gRenderer" (?gRenderer@@3PEAUSDL_Renderer@@EA) Chess C:\Users\\source\repos\Chess\Chess\InitChess.obj
Chess.cpp:
#include "SDL.h"
#undef main
#include <iostream>
#include "../include/InitChess.h"
int main()
{
InitChess* e = new InitChess;
e->initWindow();
e->initRenderer();
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
return 3;
}
delete e;
return 0;
}
InitChess.h:
#pragma once
#include "SDL.h"
#include "../include/Globals.h"
class InitChess {
public:
void initWindow();
void initRenderer();
~InitChess();
private:
};
InitChess.cpp:
#include "../include/InitChess.h"
void InitChess::initWindow()
{
SDL_Window* createdWindow;
createdWindow = SDL_CreateWindow(
"An SDL2 window", // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
640, // width, in pixels
480, // height, in pixels
SDL_WINDOW_OPENGL // flags
);
// assign created window to global window variable in Globals.h
gWindow = createdWindow;
}
void InitChess::initRenderer()
{
SDL_Renderer* createdRenderer;
createdRenderer = SDL_CreateRenderer(gWindow, -1, 0);
// assign created render to global renderer variable in Globals.h
gRenderer = createdRenderer;
}
InitChess::~InitChess()
{
SDL_DestroyRenderer(gRenderer);
SDL_Quit();
}
Globals.h:
#pragma once
#include "SDL.h"
#ifndef GLOBALS_H
#define GLOBALS_H
extern SDL_Window* gWindow;
extern SDL_Renderer* gRenderer;
#endif
| There is a difference between a declaration and a definition.
Usually writing
SDL_Window* gWindow;
is a declaration and a definition of the variable gWindow.
Every (non-inline) variable that your program uses can have multiple declarations, but must have exactly one definition.
Putting extern before SDL_Window* gWindow; makes the declaration be not a definition.
Thus you still need to put a definition of gWindow somewhere. This must appear only once in the program and therefore you cannot put the definition in a header file which may be included in multiple .cpp files.
You need to choose one .cpp file and put the definition SDL_Window* gWindow; there. The definition must be at global scope, otherwise it is not referring to the same variable as the declaration extern SDL_Window* gWindow; in Globals.h.
In your code it seems that this file is supposed to be InitChess.cpp, but depending on your design it may be better to create a Globals.cpp and put the definitions there.
// assign created window to global window variable in Globals.h
gWindow = createdWindow;
This is not a definition and not even a declaration. It is just an assignment expression. A declaration for a variable starts with its type name. But as mentioned above, simply putting SDL_Window* in front of this line will not define the global variable declared in Globals.h. Instead it would declare and define a new local variable of the same name in the function.
|
70,676,313 | 70,680,207 | Why does this spinlock require memory_order_acquire_release instead of just acquire? | // spinlockAcquireRelease.cpp
#include <atomic>
#include <thread>
class Spinlock{
std::atomic_flag flag;
public:
Spinlock(): flag(ATOMIC_FLAG_INIT) {}
void lock(){
while(flag.test_and_set(std::memory_order_acquire) ); // line 12
}
void unlock(){
flag.clear(std::memory_order_release);
}
};
Spinlock spin;
void workOnResource(){
spin.lock();
// shared resource
spin.unlock();
}
int main(){
std::thread t(workOnResource);
std::thread t2(workOnResource);
t.join();
t2.join();
}
In the notes, it is said:
In case more than two threads use the spinlock, the acquire semantic of the lock method is not sufficient. Now the lock method is an acquire-release operation. So the memory model in line 12 [the call to flag.test_and_set(std::memory_order_acquire)] has to be changed to std::memory_order_acq_rel.
Why does this spinlock work with 2 threads but not with more than 2? What is an example code that cause this spinlock to become wrong?
Source: https://www.modernescpp.com/index.php/acquire-release-semantic
| std::memory_order_acq_rel is not required.
Mutex synchronization is between 2 threads.. one releasing the data and another acquiring it.
As such, it is irrelevant for other threads to perform a release or acquire operation.
Perhaps it is more intuitive (and efficient) if the acquire is handled by a standalone fence:
void lock(){
while(flag.test_and_set(std::memory_order_relaxed) )
;
std::atomic_thread_fence(std::memory_order_acquire);
}
void unlock(){
flag.clear(std::memory_order_release);
}
Multiple threads can spin on flag.test_and_set,
but one manages to read the updated value and set it again (in a single operation).. only that thread acquires the protected data after the while-loop.
|
70,676,414 | 70,679,691 | how to make a collision of an actor on a character in C++ UE4? | I’m looking to make items that contain powers on unreal engine in c++ like :
When the player steps on it, he wins the Mushroom effect:
It has a scale of 1.25x.
So I create my Actor Item which contains the beginoverlap and the power function :
Item.h
#pragma once
#include "CoreMinimal.h"
#include "Components/CapsuleComponent.h"
#include "Components/SphereComponent.h"
#include "GameFramework/Actor.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/PlayerController.h"
#include "Character/Projet2Character.h"
#include "Item.generated.h"
UCLASS()
class PROJET2_API AItem : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AItem();
protected:
UPROPERTY(EditAnywhere)
USphereComponent* Collider;
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
UFUNCTION()
void OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
UFUNCTION()
void OnEndOverlap(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
UFUNCTION()
void Power();
AProjet2Character* player;
// Called every frame
virtual void Tick(float DeltaTime) override;
};
Item.cpp
#include "Actor/Item.h"
// Sets default values
AItem::AItem()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(FName("Mesh"));
Mesh->SetupAttachment(RootComponent);
RootComponent = Mesh;
Collider = CreateDefaultSubobject<USphereComponent>(FName("Collider"));
Collider->SetupAttachment(Mesh);
}
// Called when the game starts or when spawned
void AItem::BeginPlay()
{
Super::BeginPlay();
Collider->OnComponentBeginOverlap.AddDynamic(this, &AItem::OnBeginOverlap);
Collider->OnComponentEndOverlap.AddDynamic(this, &AItem::OnEndOverlap);
}
void AItem::OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if(OtherActor->IsA(AProjet2Character::StaticClass()))
{
Power();
}
}
void AItem::OnEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex)
{
if(OtherActor->IsA(AProjet2Character::StaticClass()))
{
Power();
}
}
void AItem::Power()
{
player->GetMesh()->SetRelativeScale3D(FVector(1.5f,1.5f,1.5f));
}
// Called every frame
void AItem::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
When I launch the game at the moment I come into contact with the actor, unreal closes and the effect still does not apply to the character.
I want to know how to do it? :)
Thank you for your understanding
| I didnt quite understand. Do you want the player to step on the object and increase in size and then, when he leaves the object, return it to its original size (1) or keep the size (2)?
//.h
UFUNCTION()
void Power();
UFUNCTION()
void ResetPower();
bool bIsPower = false;
//.cpp
void AItem::ResetPower()
{
player->GetMesh()->SetRelativeScale3D(FVector(1.f,1.f,1.f));
}
1:
//.cpp
void AItem::OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if(OtherActor->IsA(AProjet2Character::StaticClass()) && !bIsPower)
{
player = Cast<AProjet2Character>(OtherActor);
bIsPower = true;
Power();
}
}
void AItem::OnEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex)
{
if(OtherActor->IsA(AProjet2Character::StaticClass()) && bIsPower)
{
player = Cast<AProjet2Character>(OtherActor);
bIsPower = false;
ResetPower();
}
}
2:
void AItem::OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if(OtherActor->IsA(AProjet2Character::StaticClass()) && !bIsPower)
{
player = Cast<AProjet2Character>(OtherActor);
bIsPower = true;
Power();
}
}
void AItem::OnEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex)
{
//Clear
}
|
70,676,905 | 70,677,168 | `int (*q)[m][n]=( int(*)[m][n] )p;` is this typecasting possible where p is normal integer pointer `int *p` which pointing to base address of matrix | Code
#include <iostream>
void display(int, int, void* );
int main()
{
int A[][2]= { 0, 2,
4, 2,
2, 2};
int m=3, n=2;
display(m, n, &A[0][0]);
}
void display(int m, int n, void *p)
{
int (*q)[m][n]=( int(*)[m][n] )p; // This causing error
for(int i=0; i<=m-1; i++)
{
for(int j=0; j<=n-1; j++)
{
std::cout<<q[i][j]<<" ";
}
std::cout<<"\n";
}
}
Output(Error)
Cannot initialize a variable of type 'int (*)[m][n]' with
an rvalue of type 'int (*)[m][n]'
https://stackoverflow.com/a/35657313/11862989 here user mention this but it's not working.
int (*q)[m][n]=( int(*)[m][n] )p; so why this typecasting is not happening.
| You don't have to use vectors for statically sized data you can still use "C" style arrays. AND you can do it in a typesafe (and memory access safe way) as shown here :
#include <iostream>
/*
This is an insecure way of doing things anyway since it depends on
- typeconversion from void* (you could put anything into this function and it would try to display it)
- n and m could differ from actual sizes of the array leading to out of bounds error
void display(int m, int n, void* p)
{
int(*q)[m][n] = (int(*)[m][n])p; // This causing error <== because it is incorrect syntax
for (int i = 0; i <= m - 1; i++)
{
for (int j = 0; j <= n - 1; j++) // dont compare with <= it just not standard practice
{
std::cout << q[i][j] << " ";
}
std::cout << "\n";
}
}
*/
// this would be the fixed size signature
// note it is typesafe (no void*) and carries the sizes
// within the datatype
void display(int (&values)[3][2])
{
for(int row=0; row < 3; ++row)
{
for(int col=0; col < 2; ++col)
{
std::cout << values[row][col] << " ";
}
std::cout << "\n";
}
}
// to make the previous function reusable for other array sizes
// you can make it a function template
// and notice I replaced the index based for loops with range
// based for loops for added safety
template<std::size_t N, std::size_t M>
void display_template(int (&values)[N][M])
{
std::cout << "\nfunction template version of display\n";
// need a reference to a row
// and the consts mean that display can only
// look at the rows and values not change them
for(const auto& row : values)
{
for(const auto value : row)
{
std::cout << value << " ";
}
std::cout << "\n";
}
}
int main()
{
// initialize 2d array in a 2d manner (nested {})
int values[3][2] {{0,2},{4,2},{2,2}};
display(values);
display_template(values);
return 0;
}
|
70,677,039 | 70,677,813 | While running my linked list code the compiler does not give any outputs after giving a print function too | I have given insert and a print function to insert data in a linked list and then print it.
But somehow it does not give any output and keeps running for a infinite time.
What is wrong?
Here is the code I have written. This is a simple program to create a linked list using loops and functions.
#include<iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* head;
void insert(int data){
struct node* temphead=head;
if (temphead == NULL)
{
node* temp = new node();
temp->data=data;
temp->next=NULL;
while (temphead == NULL){
head==temp;
}
}
else if (temphead != NULL)
{
node* temp = new node();
temp->data=data;
temp->next=NULL;
while (temphead != NULL)
{
temphead->next= temp;
temphead=temphead->next;
}
}
}
void print(){
struct node* tempptr = head;
while (tempptr->next != NULL)
{
cout<<tempptr->data<<"_";
tempptr=tempptr->next;
}
}
int main(){
head=NULL;
insert(2);
insert(4);
insert(8);
insert(6);
//list - 2_4_8_6
print();
return 0;
}
| There were few bugs in your code and also typos. Please read the comments marked with // CHANGE HERE for the description of the changes I did:
#include <iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* head;
void insert(int data){
struct node* temphead = head;
if (temphead == nullptr)
{
node* temp = new node();
temp->data = data;
temp->next = nullptr;
// CHANGE HERE: removed unnecessary while loop
// Directly assign temp to head
head = temp;
}
else
{
node* temp = new node();
temp->data=data;
temp->next=nullptr;
// CHANGE HERE: check for temphead->next instead of temphead
while (temphead->next != nullptr)
{
// CHANGE HERE: remove unnecessary line: temphead->next= temp;
temphead=temphead->next;
}
// CHANGE HERE: assign temp to temphead->next (i.e. to last node)
temphead->next = temp;
}
}
void print(){
struct node* tempptr = head;
// CHANGE HERE: check for tempptr instead of tempptr->next
while (tempptr != nullptr)
{
cout<<tempptr->data<<"_";
tempptr=tempptr->next;
}
}
int main(){
head=nullptr;
insert(2);
insert(4);
insert(8);
insert(6);
//list - 2_4_8_6
print();
return 0;
}
NOTE: Your code uses new for dynamic memory allocation but doesn't use delete to de-allocate the memory when not required. If you want to avoid using new/delete, you can explore about smart pointers.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.