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 |
|---|---|---|---|---|
72,718,155 | 72,718,374 | Bring to derived object the assignment operator from base (prior to C++11) | I have a code similar to this:
template <typename T>
struct B
{
B &operator =(const T &) { return *this; }
};
struct D : B<int> {};
int main()
{
D d;
d = 0;
return 0;
}
Which fails:
error: no viable overloaded '='
d = 0;
~ ^ ~
note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const D' for 1st argument
struct D : B<int> {};
^
note: candidate function (the implicit move assignment operator) not viable: no known conversion from 'int' to 'D' for 1st argument
struct D : B<int> {};
^
The error is easy to spot and understand: D lacks of assignment operator with int, even if its base class have it. From c++11 onwards we can solve this issue "lifting" to the derived object the assignment operator from the base object:
struct D : B<int> { using B::operator =; /* Easy fix! */ };
But I'm working on a c++98 project, so this fix isn't available. How was this solved prior to C++11?
| First things first, the program(with using declaration) works with C++98. Working Demo with C++98.
That is, a using declaration for the assignment operator of the base class inside the derived class is allowed by C++98. Here is the relevant text from the standard:
If an assignment operator brought from a base class into a derived class scope has the signature of a copy-assignment operator for the derived class (12.8), the using-declaration
does not by itself suppress the implicit declaration of the derived class copy-assignment operator; the
copy-assignment operator from the base class is hidden or overridden by the implicitly-declared copy-
assignment operator of the derived class, as described below.
(emphasis mine)
Note again that the important thing is that the using declaration for the assignment operator of base class is allowed.
Now, you can define an assignment operator= for the derived class that explicitly uses the base class as shown below:
struct D : B<int> {
D& operator=(const int& obj) {
B<int>::operator=(obj); //use base class assignment operator
return *this;
}
};
|
72,718,417 | 72,719,182 | Is declaring a friend which is forward-declared in an unnamed namespace an ODR-violation? | I've been using a dirty trick where I use unnamed namespaces to specify different behavior for each file (it is for unit-testing). It feels like it shouldn't be well-defined, but it works on every major compiler released in the past six years.
I first forward-declare a bunch of classes in an anonymouse namespace:
namespace {
class context_check;
class context_block;
class register_test;
} // namespace
Then I declare a class and make these classes friends:
struct test_case
{
// ...
};
class context {
// ...
private:
// TODO: this feels like ODR-violation...
friend class context_check;
friend class context_block;
friend class register_test;
private:
void add_test(test_case&& test)
{
// ...
}
// ...
};
And in each cpp file I have following declarations (for tha sake of simplicity I copy and pasted them here, but in reality I declare the content of unnamed namespace in a header):
// A.cpp
namespace {
extern context file_context;
class register_test {
public:
register_test(const char* test_name, test_case&& test)
{
file_context.add_test(std::move(test));
}
};
} // namespace
register_test register_test_1( test_case{"test1"} );
// B.cpp
namespace {
extern context file_context;
class register_test {
public:
register_test(const char* test_name, test_case&& test)
{
file_context.add_test(std::move(test));
}
};
} // namespace
register_test register_test_2( test_case{"test2"} );
So each TU has its own definitions of register_test, context_check etc.
Is this well-defined? Feels like it should be an UB...
| Seems to violate the following condition required by ODR, as stated on https://en.cppreference.com/w/cpp/language/definition:
There can be more than one definition in a program of each of the following: class type, [...], as long as all of the following is true:
[...]
name lookup from within each definition finds the same entities (after overload-resolution), except that [...]
None of the exceptions are relevant and lookup for e.g. context_check in friend class context_check;, which is part of the definition of context, finds an internal linkage entity, which cannot be the same if the definition is included in multiple translation units.
The actual corresponding rule of the standard can be found e.g. in [basic.def.odr]/13.9 of the post-C++20 draft.
|
72,718,956 | 72,719,150 | Create method that accepts method from any child class | I apologize for the vague question title, but I'm unfamiliar enough with C++ to be able to phrase it better.
I'm trying to create a method that takes a method on any child class as one of the parameters, but I'm getting a compiler error that I don't know how to fix. I'd also like to alias the type so it's not so verbose. I'm open to other approaches, but the code I'm working within is more or less setup this way.
Code:
#include <map>
#include <string>
using std::map;
using std::string;
struct ParentClass;
struct DataClass;
using my_handler_type = uint16_t (ParentClass::*)(DataClass&, DataClass&);
struct ParentClass {
void add_handler(string name, my_handler_type handler) {
handlers.emplace(name, handler);
}
private:
map<string, my_handler_type> handlers;
};
struct ChildClass : ParentClass {
private:
uint16_t some_handling_function(DataClass &, DataClass & );
void setup_handler() {
add_handler( "handler_one", &ChildClass::some_handling_function );
}
};
Error:
example.cpp: In member function ‘void ChildClass::setup_handler()’:
example.cpp:31:37: error: cannot convert ‘uint16_t (ChildClass::*)(DataClass&, DataClass&)’ {aka ‘short unsigned int (ChildClass::*)(DataClass&, DataClass&)’} to ‘my_handler_type’ {aka ‘short unsigned int (ParentClass::*)(DataClass&, DataClass&)’}
31 | add_handler( "handler_one", &ChildClass::some_handling_function );
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| |
| uint16_t (ChildClass::*)(DataClass&, DataClass&) {aka short unsigned int (ChildClass::*)(DataClass&, DataClass&) example.cpp:14:51: note: initializing argument 2 of ‘void ParentClass::add_handler(std::string, my_handler_type)’
14 | void add_handler(string name, my_handler_type handler) {
| ~~~~~~~~~~~~~~~~^~~~~~~
| You can cast the child class member function pointer to the type of a base class member function pointer.
static_cast<my_handler_type>(&ChildClass::some_handling_function));
So:
#include <iostream>
#include <map>
#include <string>
using std::map;
using std::string;
struct ParentClass;
struct DataClass {};
using my_handler_type = uint16_t (ParentClass::*)(DataClass &, DataClass &);
struct ParentClass {
void add_handler(string name, my_handler_type handler) {
handlers.emplace(name, handler);
}
void handle(const std::string &ev) {
if (auto it = handlers.find(ev); it != handlers.end()) {
DataClass d;
(this->*it->second)(d, d);
}
}
private:
map<string, my_handler_type> handlers;
};
struct ChildClass : ParentClass {
uint16_t some_handling_function(DataClass &, DataClass &) {
std::cout << "handling the stuff\n";
return 0;
}
public:
void setup_handler() {
// cast the member function pointer here:
add_handler("handler_one", static_cast<my_handler_type>(
&ChildClass::some_handling_function));
}
};
int main() {
ChildClass c;
c.setup_handler();
c.handle("handler_one");
}
Demo
|
72,719,009 | 72,719,185 | How can I test whether a type is a range from which I can move elements? | Assume that I have a function template that can accept a range of some type T. I want to check whether it's safe to move from that range.
For example, if a function accepts an rvalue reference to a certain value, it is safe to move from it. If, for example, that function may accept both rvalue and lvalue references, we can use std::forward to conditionally move it if necessary.
Now I want to achieve the same thing, but for ranges. Initially I tried using the following concept:
template <typename Range>
concept movable_source = std::ranges::range<Range> &&
!std::ranges::borrowed_range<Range> &&
(!std::is_lvalue_reference_v<Range>);
and it worked okay. It reported true for std::vector<T>&&, false for std::vector<T>& and true again for std::vector<T>.
Usage:
template <typename T>
auto print_movability(T&& t) -> void {
std::cout << movable_source<T> << ' ';
}
auto main() -> int {
auto vec = std::vector<int>();
print_movability(vec);
print_movability(std::move(vec));
print_movability(std::vector<int>());
}
This correctly prints 0 1 1.
However, the following snippet breaks this logic:
print_movability(vec | std::views::transform([](int& e) -> int& { return e; }));
This reports 1 since the resulting view is neither a borrowed range nor is it an lvalue reference.
I could of course simply add another check to make sure that the type isn't a view, but would that be enough? What would be the correct way to test whether a type is a range whose elements we can move?
| I would suggest making it up to the caller to tell you this by using a range adaptor that produces rvalue references (views::move in range-v3, views::as_rvalue proposed for C++23). That way you don't have to guess, since you'll get a range of rvalues:
algo(vec); // can't move
algo(vec | views::move); // can move
algo(vec | views::transform(f)); // can't move
algo(vec | views::transform(f) | views::move); // can move
Calling this "can move" isn't really meaningful, since we actually get is a range of rvalues, so of course you can move. That's just what you get.
As to guessing... that's pretty hard. Borrowed-ness isn't relevant, so we can skip that part. If the range is an lvalue, pretty sure we can't move. If the range is an rvalue but is a view, we probably can't move (we'll typically get views as rvalues) except for some specific views that we can. So an approximation could be:
template <class R>
inline constexpr bool move_safe_range = !view<R>;
template <class R>
inline constexpr bool move_safe_range<owning_view<R>> = true;
template <class T>
inline constexpr bool move_safe_range<single_view<T>> = true;
template <class R>
concept movable_source =
input_range<R>
&& (!is_lvalue_reference_v<R>)
&& move_safe_range<R>;
But I'm not sure this is a great approach, cause even an rvalue view could be move-safe, for instance if we're views::transform-ing an owning_view? The views::move/views::as_rvalue is more reliable (even as it requires more annotation).
|
72,719,181 | 72,720,263 | How to place my function using QSignalMapper and QObject::connect | I'm a beginner in c++.
i'm trying to pass an argument using QSignalMapper. I do something like this:
int main(int argc, char** argv)
{
...
QSignalMapper * mapper = new QSignalMapper(0);
QObject::connect(mapper,SIGNAL(mapped(int )), 0 ,SLOT(mySlot(int )));
int prova=11;
mapper->setMapping(but, prova);
QObject::connect(but, SIGNAL(clicked()),mapper,SLOT(map()));
//do stuff
}
Where i can put mySlot()? I need to pass the variable "prova"
Thanks to all.
| Forget about QSignalMapper and use lambdas:
QObject::connect(but, &QButton::clicked, myObject, [myObject,prova]() { myObject->mySlot(prova); });
In case mySlot is just a regular function:
QObject::connect(but, &QButton::clicked, [prova]() { mySlot(prova); });
|
72,719,193 | 72,719,309 | How to initialize static members of two various types of template class | I want to assign two different values to A<int> and A<char>,then each kind of instantialized classes have their own static member 'a',but the program compile failed.
Here's the code.
#include <iostream>
using namespace std;
template<class T>
class A {
private:
static int a;
public:
friend ostream& operator<<<T>(ostream& os, A<T>& p);
};
template<class T>
ostream& operator<<(ostream& os, A<T>& p){
cout << p.a;
return os;
}
template<class T>int A<T>::a = 5;
template<class T>char A<T>::a = 50;//error:the declaration is not compatible with the previous "int A<T>::A"declaration
int main()
{
A<int> v1, v2, v3;
A<char>v11, v22, v33;
cout << v1<<" "<<v2<<" "<<v3<<endl;
}
So what should I do?
| You need to do an explicit specialization which you do by writing an empty template declaration and replacing T in A<T> with the type you want.
template<> int A<int>::a = 5;
template<> int A<char>::a = 50;
|
72,719,605 | 72,720,127 | Segmentation fault on Eigen::SparseMatrix resize | I have a large set of codes (public on github), but it's way too much to put in a question, and I have no idea how to get a mwe (you'll see why), so I'd be happy with just some more suggestions on what could be going wrong.
We have a class, SC_class, in this file, with several derived classes. In the derived class Cylindrical : public SC_class, we define a few more member variables (sparse matrices from Eigen). In the constructor, we call a function (line 298 here) that resizes these matrices before we use them. The seg fault occurs on line 317, but that is exactly how I had resized the other matrices! (Lines 316-318 are 3 ways that I tried to do the same thing but I get the same error.) If I define them all the same way, and resize the last one the same way as the first one, why do I only get the seg fault on the last one? (I say last just since that's the order that I have them right now, but changing the order doesn't change the statement that it crashes on.) The only other thing I've noticed that might help is that sometimes, when I had lines 316-318 commented out, I would get a seg fault right at the end of the program, something after this line.
Here it was stated that sometimes the matrix might be too big for the stack or the heap, but when I tried .resize(1,1) (here), it still didn't work.
| Okay, strangest source of the error; I don't know if anyone else will have something like this, but just in case, I'll share.
I have a pointer in the main file, but I eventually turn it into an array. At the end of the program, I delete that pointer as if it was an array (since that's what I turned it into), but that was causing one of the seg faults. (Note: I had the line delete[] eta_BC here, but it will also throw an error if you say delete eta_BC; the problem was simply an improper use of pointers.) To solve it, I simply needed to change the array to an std::vector.
|
72,719,624 | 72,719,665 | Fixed-size array as function parameter: No matching function for call to 'begin' | I am passing a fixed size array to a function (the size is defined to a constant in the function's definition). However, I still get the error
No matching function for call to 'begin'
# define arr_size 2
void test(int arr0[2]){
int arr1[]={1,2,3};
int arr2[arr_size];
begin(arr0); // does not work -- how can I make this work?
begin(arr1); // works
begin(arr2); // works
}
There is a related discussion here, however, the array's size was clearly not constant in that case. I want to avoid using vectors (as suggested there) for efficiency reasons.
Does anyone know what the issues is?
| This function declaration
void test(int arr0[2]){
is equivalent to
void test(int *arr0){
because the compiler adjusts parameters having array types to pointers to array element types.
That is the both declarations declare the same one function.
You may even write for example
void test(int arr0[2]);
void test(int *arr0){
//,,,
}
So you are trying to call the function begin for a pointer
begin(arr0);
You could declare the parameter as a reference to the array type
void test(int ( &arr0 )[2]){
to suppress the implicit conversion from an array to a pointer.
|
72,720,101 | 72,720,351 | Deduce template parameter value from concept | I continue my C++20 concept(ual) jourrney... I would like to simplify the following code by deducing the template parameter T from the predicate argument, so that the client code does not have to precise the type of T if it can be deduced from P1.
I guess it is possible, I just don't know the syntax: I tried various forms of template template + requires clause, but without having a successful compilation.
Any lead?
#include<concepts>
#include<utility>
#include<string>
template<class T, std::predicate<T> P1>
struct Foo
{
P1 _f;
Foo(P1 &&f): _f(std::forward<P1>(f)) {}
};
template<class T, std::predicate<T> P1>
auto make_foo(P1 &&f)
{
return Foo<T, P1>(std::forward<P1>(f));
}
int main()
{
auto fun = [](const std::string &s){return s == "toto";};
// auto my_foo = make_foo(fun); // candidate template ignored: couldn't infer template argument 'T'
auto my_foo = make_foo<std::string>(fun);
return 0;
}
| std::function has good deduction guides to get the type of a callable:
// Replacement for `std::function<T(U)>::argument_type`
template<typename T> struct single_function_argument;
template<typename Ret, typename Arg> struct single_function_argument<std::function<Ret(Arg)>> { using type = Arg; };
// Deduction guide
template<class P1>
Foo(P1 &&) -> Foo<typename single_function_argument<decltype(std::function{std::declval<P1>()})>::type, P1>;
template<class P1>
auto make_foo(P1 &&f)
{
// Use CTAD
return Foo(std::forward<P1>(f));
}
// Can still specify type manually if you want
template<class T, std::predicate<T> P1>
auto make_foo(P1 &&f)
{
return Foo<T, P1>(std::forward<P1>(f));
}
int main() {
auto fun = [](const std::string &s){return s == "toto";};
auto my_foo1 = Foo(fun);
auto my_foo2 = make_foo(fun);
}
The reason you have to go this round-about way is that the type of fun satisfies all of std::predicate<const std::string&>, std::predicate<const char*>, std::predicate<TypeImplicitlyConveribleToString>, there's no unique way to get a type for T. This approach also fails with generic lambdas [](const auto& s) { return s == "toto"; }, so you would need to use make_foo<std::string>(fun).
|
72,720,175 | 72,720,353 | Is there some way to specify if template param of function is specific template class? | I will explain my question based on following example:
template <typename Param1, typename Param2>
class foo1
{
void lol();
};
template <typename Param1, typename Param2>
class foo2
{
void lol();
};
////////////////////////// FIRST OPTION //////////////////////////
template <typename Param1, typename Param2>
void func(foo1<Param1, Param2> a)
{
a.lol();
a.lol();
}
template <typename Param1, typename Param2>
void func(foo2<Param1, Param2> a)
{
a.lol();
}
////////////////////////// SECOND OPTION //////////////////////////
template <typename Foo_>
void func(Foo_ a)
{
a.lol();
a.lol();
}
///////////////////////////////////////////////////////////////////
int main()
{
return 0;
}
My goal is to write two overloads of func - for foo1 and foo2.
The FIRST OPTION works fine, but I don't like that I have to write template parameters for func that are not used in it.
Is there some way to avoid writing template parameters in signature of func?
I thought of writing something like this SECOND OPTION, but the problem is that overloads do different things.
| The template parameters are used. Without them, foo1 and foo2 are just class templates and not a classes.
A simple way to minimize the typing would be to use template parameter packs:
template<class... T>
void func(foo1<T...> a) {
a.lol();
a.lol();
}
template<class... T>
void func(foo2<T...> a) {
a.lol();
}
If you need this check a lot, you can create concepts (since C++20):
#include <type_traits>
// concept for foo1:
template <class T> struct is_foo1 : std::false_type {};
template <class P1, class P2> struct is_foo1<foo1<P1, P2>> : std::true_type {};
template <typename T> concept Foo1Type = is_foo1<T>::value;
// concept for foo2:
template <class T> struct is_foo2 : std::false_type {};
template <class P1, class P2> struct is_foo2<foo2<P1, P2>> : std::true_type {};
template <typename T> concept Foo2Type = is_foo2<T>::value;
Then the func overloads become simpler:
void func(Foo1Type auto a) {
a.lol();
a.lol();
}
void func(Foo2Type auto a) {
a.lol();
}
Demo
|
72,720,226 | 72,720,320 | Iterate through array denoted by unsigned short pointer | I have some code that existed in C which contains an array of uint16_t, which looks something like uint16_t *Fingerprints;. To iterate through it, I can pair it together with a uint32_t ArrayLength; value and directly access Fingerprints[i].
Now, I am writing more code in C++ and I have a std::vector<uint16_t> values that I want to iterate through the same datatype. Is it possible to get a uint16_t * from this and pair it with values.size() to iterate through?
| std::vector<uint16_t> has a .data() member function which will give you a uint16_t* pointer and which you could use together with .size() in the same way you were using it in C.
However, in C++ we usually use iterators instead of pointers if there is no specific reason to use the latter. Iterators are a generalization of the pointer concept which also applies to other kinds of containers. This has the benefit of being agnostic to the container type. If you replaced std::vector with std::list you wouldn't have to change anything in your code. E.g.:
std::vector<uint16_t> values;
// or e.g. `std::list<uint16_t> values`
for(auto it = values.begin(); it != values.end(); ++it) {
/* You can use `it` here similar to a pointer to the current element */
/* Meaning `it` is similar to `Fingerprints + i` */
}
This also has the benefit that you can't accidentally mismatch the index type. How are you making sure that uint32_t is the correct type to use for the index? What if you are on x64 and have an array/vector so large that the size can't fit in uint32_t. It should really usually be std::size_t (or maybe std::ptrdiff_t if signed is preferred) for arrays/vectors instead and for other containers it might vary further.
Furthermore there is the range-for loop syntactical sugar for this which you should prefer you if you just want a simple iteration through all of the container:
for(auto&& el : values) {
/* You can use `el` here as a reference to the current element in the iteration */
/* Meaning `el` is basically `Fingerprints[i]` */
}
|
72,720,251 | 72,720,345 | C++ Overwrite initializer list in unit test | I have some C++ code like this that I want to unit test:
class Example
{
private:
ExpensiveObject expensiveObject;
public:
Example() : expensiveObject() {
... constructor code
}
methodA() {
... some code
}
}
To write a unit test for methodA I need to create an instance of Example. The problem is that I don't want to initialize expensiveObject, I would want to set it to null in my unit test (I am using Google Test). Is there a way to do it?
| expensiveObject cannot be assigned null. What you might want is to have a smart pointer to ExpensiveObject, and have multiple constructors or better you want to inject your dependencies.
class Example
{
private:
std::shared_ptr<ExpensiveObject> expensiveObject;
public:
Example(std::shared_ptr<ExpensiveObject> ptr) : expensiveObject(ptr) {
//... constructor code
}
methodA() {
//... some code
}
}
Now you can test it for null scenarios as well
Example ex{nullptr};
ex.methodA();
|
72,720,684 | 72,720,880 | Check bitfield value in static assert? | I wrote a library that requires little endian and bitfields to be ordered from low to high
I run similar code at runtime to check it. I was wondering if I could do this at compile time?
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cstdint>
struct A {
uint64_t a : 4, b : 5, c:55;
A()=default;
//constexpr A(uint64_t value) { memcpy(this, &value, 8); }
A(uint64_t value) { memcpy(this, &value, 8); }
};
static_assert(sizeof(A) == 8);
int main() {
A test(0x3F3);
assert(test.a == 3);
assert(test.b == 0x1F);
assert(test.c == 1);
}
| You can replace the memcpy with bit_cast to make your constructor constexpr:
#include <bit>
#include <cstdint>
struct A {
uint64_t a : 4, b : 5, c:55;
A()=default;
constexpr A(uint64_t value) { *this = std::bit_cast<A>(value); }
};
static_assert(A(0x3F3).a == 3);
static_assert(A(0x3F3).b == 0x1F);
static_assert(A(0x3F3).c == 1);
It should optimize to the same thing as memcpy.
Note that older versions of some compilers don't support bit_cast to types
with bit fields. Probably the best solution for these is to keep the memcpy and use a build tool to check this before you compile.
|
72,720,891 | 72,721,201 | Losing messages when multiprocess logging with easylogging++ in C++ | I'm using easylogging++ in my app to log messages for control and I've noticed that in production env (which runs under Linux) some messages were disappearing or missing from the log files. I managed to simulate this problem with a simple example in the test environment (on Windows). I made an infinite thread that just keeps on logging a counter and then I executed two instances of my program, here is a resumed example of my code:
#include "Log/Log.h"
#include <chrono>
#include <thread>
INITIALIZE_EASYLOGGINGPP
void log_test() {
long int count = 0;
while (true) {
log_info("Logando..." + std::to_string(count)); // this is defined in Log.h
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
count++;
}
}
int main(){
std::thread t(log_test);
t.detach();
// rest of the code
}
and Log.h/Log.cpp are:
#pragma once
#include "easylogging++.h"
#include <mutex>
static std::mutex mtx;
void log_info(std::string s);
void log_error(std::string s);
Log.cpp:
#include "Log.h"
void log_info(std::string s)
{
mtx.lock();
LOG(INFO, ELPP_THREAD_SAFE) << s;
mtx.unlock();
}
void log_error(std::string s)
{
mtx.lock();
LOG(ERROR, ELPP_THREAD_SAFE) << s;
mtx.unlock();
}
and the both executable files are using the same .conf file with the following configurations:
* GLOBAL:
FORMAT = "%datetime %msg"
FILENAME = "C:/logs/%datetime{%Y-%M-%d}/msgs.log"
ENABLED = true
TO_FILE = true
TO_STANDARD_OUTPUT = false
SUBSECOND_PRECISION = 6
PERFORMANCE_TRACKING = true
MAX_LOG_FILE_SIZE = 2097152 ## 2MB - Comment starts with two hashes (##)
in the msgs.log file I've noticed this sample:
2022-06-22 18:51:24,886631 Logando...288
2022-06-22 18:51:24,901856 Logando...289
2022-06-22 18:51:24,917820 Logando...5
2022-06-22 18:51:24,932827 Logando...291
2022-06-22 18:51:24,948248 Logando...292
Where the log 290 is missing from the first process and there's just this blank line instead. I guess that one solution could be just using different log files for each process, however it doesn't happen in one single process with multiple threads (instantiating thread t1, t2,t3 as in the code example before). I can't just change one log file to each process in production at the moment since it will have a high impact, so how can I solve it to I don't lose any message at all? Thanks in advance!
|
I guess that one solution could be just using different log files for each process, however it doesn't happen in one single process with multiple threads (instantiating thread t1, t2,t3 as in the code example before)
Well, threads in a single process share an instance of std::mutex mtx, so they're properly synchronized. Perhaps more importantly, the thing being correctly synchronized is access to a single buffer, which is the only buffer writing to your file.
Two processes will have completely independent instances of std::mutex mtx, which doesn't matter if they're single-threaded, because only one thread is writing to each process's buffer. The problem is that the two buffers are not synchronized with each other when writing to the file, and as mentioned in comments, these writes are apparently not atomic appends.
Solutions are:
Just use threads, since this works already.
Use a shared mutex - this is generally platform specific, but Boost.Interprocess is a good place to start.
Use two files - have some other process tail them both and combine into a single file if you need that
Use two FIFOs for the output files, and have some other process reading them both and combining them into a single file. It avoids duplicating the file storage on disk, but is probably *NIX specific.
Use network sinks (see the easyloggingc++ documentation), and have a process listening to two ports on localhost ... and combining them into a single file. More portable than FIFOs, but also more coding.
|
72,721,110 | 72,721,180 | Casting int64_t * to uint64_t * | The signed integer pointer is the output of some_vector.data() of a std::vector<int64_t> some_vector, but I know all the values are positive and I want to cast that integer to an unsigned integer. How can I do that and "reinterpret" the vector values as unsigned?
| You can simply cast the pointer to the desired type and I think this will almost always work:
uint64_t * data = (uint64_t *)some_vector.data();
However I am not sure if this is allowed or safe according to the C++ standard. (Search for "strict aliasing" to learn about one type of pitfall.) And someone will probably tell you there is a better type of cast you can use.
It would be much safer to just leave the type of the pointer as it is, and then when you have an actual int64_t value you can implicitly convert it to a uint64_t or cast it.
int64_t * data = ...;
uint64_t x = data[1];
|
72,721,520 | 72,723,275 | How can you wrap a C++ function with SWIG that takes in a Python numpy array as input without explicitly giving a size? | I have a library of C++ classes that I am building a Python interface for using SWIG. Many of these classes have methods that take in a double* array or int* array parameter without inputting a size. For example, there are many methods that have a declaration like one of the following:
void func(double* array);
void func2(double* array, double unrelated_parameter, ...);
I would like to be able to use these functions in Python, with the user passing in a Python numpy array. The size of these arrays are never given as a parameter to the function. The size of the input array is given in the constructor of the objects of these C++ classes and it is assumed that every input array that is given as a parameter to these class methods will have the same size. All of the numpy examples I have seen require me to add an int array_size parameter to the C++ method/function being wrapped.
Is there a way to wrap these C++ functions without having change the API of my entire C++ library to include an int array_size parameter for every single function? Ideally, a user should pass in a Python numpy array and SWIG will automatically convert it to a double or int array on the C++ side.
I have already included numpy.i and followed the instructions here: https://numpy.org/doc/stable/reference/swig.interface-file.html but am getting errors like the following:
TypeError: in method 'func', argument 2 of type 'double *'
| One way I can think of is to suppress the "no size" version of the function and extend the class to have a version with a throw-away dimension variable that uses the actual parameter in the class.
Example:
test.i
%module test
%{
#define SWIG_FILE_WITH_INIT
class Test {
public:
int _dim; // needs to be public, or have a public accessor.
Test(int dim) : _dim(dim) {}
double func(double* array) {
double sum = 0.0;
for(int i = 0; i < _dim; ++i)
sum += array[i];
return sum;
}
};
%}
%include "numpy.i"
%init %{
import_array();
%}
%apply (double* IN_ARRAY1, int DIM1) {(double* array, int /*unused*/)};
%ignore Test::func; // so the one-parameter version isn't wrapped
class Test {
public:
Test(int dim);
double func(double* array);
};
%rename("%s") Test::func; // unignore so the two-parameter version will be used.
%extend Test {
double func(double* array, int /*unused*/) {
return $self->func(array);
}
}
Demo:
>>> import test
>>> t = test.Test(5)
>>> import numpy as np
>>> a = np.array([1.5,2.0,2.5,3.75,4.25])
>>> t.func(a)
14.0
|
72,721,710 | 72,722,494 | Integer initialization of enum outside of range | I am reading Bjarne Stroustrup's "Tour of C++" (2:nd edition). In chapter 2.5, he discusses enums with the following example:
enum class Color {red,blue,green};
In the same chapter, he says that it is allowed to initialize an enum with a value from its underlying type (int by default), and gives the following example:
Color x = Color{5}; //OK, but verbose
Color y {6}; //Also OK
I tested, and this certainly compiles. However, I am a bit confused about the meaning of initializing an enum with 5 or 6, which falls outside the "range" (0-2) of Color. What are actually the values of x and y in the above example? By testing, it does not appear to be either "red", "green" or "blue".
As a follow-up question, why is this "out-of-range" initialization of enums allowed? It does not seem very sensible.
Note that integer initialization of enums is not supported in C++11, but only in C++17 and forward.
| This comes from C: enumerated types are fancy integers. The names of the enumerations are handy, but they don't define every value that the type can represent.
Probably the most common use for an enumerated type is, though, as a simple list of constants:
enum state [
off,
starting,
running,
shutting_down,
out_of_service
};
The values of these enumerators are off == 0, starting == 1, running == 2, shutting_down == 3, and out_of_service == 4.
But, formally, you aren't restricted to those values. And sometimes there are interesting combinations of values:
enum color {
red = 0b0001,
green = 0b0010,
blue = 0b0100
};
The values of these enumerators have been carefully contrived so that each one uses a different bit; that lets us combine values easily.
For example, the color "purple" is a combination of red and blue. Combining the bits for red (0b0001) and blue (0b0100) gives us a value with two bits set: 0b0101. That's the value 5, and it's not one of the named values. But it's okay to store that value:
color x = red | blue; // x represents the value of purple
std::cout << x << '\n'; // displays 5
(I'm not compiling this, since I don't have a compiler on this laptop, so you might need a cast here)
Similarly,
color y = red | green; // y represents the value of yellow
std::cout << y << '\n'; // displays 3
The rule for what values can be stored is a bit complicated, but basically, if the bits are there, you can use them.
Doing this obviously lets you store values that represent multiple things, but it also lets you query those things:
bool has_blue(color c) { return c & blue; }
assert(has_blue(x));
assert(!has_blue(y));
So, basically, this lets you use a named type rather than a generic integer type when you need to store and query numeric fields. Sure, you could do all this with ordinary constants:
const int red = 0b0001;
const int green = 0b0010;
const int yellow = 0b0100;
and combine them as integer values:
int x = red | blue;
int y = red | green;
but now the type of each of these is just a plain old int, not nearly as descriptive as calling it color.
|
72,722,731 | 72,722,942 | JSON extract date from matching string | I am entirely new to JSON, and haven't got any familiarity with it at all. I'm tinkering around with some JSON data extracts to get a feel for it.
Currently, I have a chat export which has a large number of keys. Within these keys are a "date" key, and a "from_id" key.
I would like to search a JSON file for a matching value on the "from_id" key, and return all the values against the "date" keys with a matching "from_id" value.
For example:
{
"name": "FooBar Chat Group",
"type": "textchat",
"id": 123456789,
"messages": [
{
{
"id": 252930,
"type": "message",
"date": "2021-03-03T01:39:30",
"date_unixtime": "1614735570",
"from": "Person1",
"from_id": "user1234",
"text": "This is a message!"
},
{
"id": 252931,
"type": "message",
"date": "2021-03-03T01:41:03",
"date_unixtime": "1614735663",
"from": "Person2",
"from_id": "user9876",
"text": "This is a reply!"
},
{
"id": 252932,
"type": "message",
"date": "2021-03-03T01:42:01",
"date_unixtime": "1614735721",
"from": "Person2",
"from_id": "user9876",
"text": "This is some other text!"
},
{
"id": 252933,
"type": "message",
"date": "2021-03-03T01:42:44",
"date_unixtime": "1614735764",
"from": "Person1",
"from_id": "user1234",
"text": "Yeah, indeed it is!"
}
]
}
I want to search from_id "user1234", and for it to return the following:
2021-03-03T01:39:30
2021-03-03T01:42:44
These are the two dates that have a matching from_id.
How would I go about doing something like this, please?
I am entirely new to this, so a super basic explanation with resources would really be appreciated. Thanks!
| you can try this c# code. At first you have to parse your json strig to create an object from string. Then you can use LINQ to get the data you need
using Newtonsoft.Json;
JArray messages = (JArray) JObject.Parse(json)["messages"];
string from_id="user1234";
DateTime[] dates = messages
.Where(m=> (string) m["from_id"] ==from_id)
.Select(m => (DateTime) m["date"])
.ToArray();
|
72,723,099 | 72,723,161 | socket write in for loop mixes string buffers | I call a function multiple times using a for loop like this:
for ( int con=0; con < this->controller_info.size(); con++ ) {
try {
this->pi.home_axis( this->controller_info.at(con).addr );
}
catch( std::out_of_range &e ) { ... }
}
where the home_axis() function is defined as:
long ServoInterface::home_axis( int addr ) {
std::stringstream cmd;
if ( addr > 0 ) cmd << addr << " ";
cmd << "FRF";
cmd << "\n";
int bytes=this->controller.Write( cmd.str() );
return NO_ERROR;
}
and the controller.Write() function is just a wrapper for the standard write(2) which writes the characters in the string to a socket file descriptor.
You can see that each time home_axis() is called it should have its own, fresh, std::stringstream cmd buffer. But what is happening is that, for the first time the for loop executes, the host that is receiving the bytes written by home_axis, is receiving a single string, once:
1 FRF2 FRF
but if I print the bytes written then it prints 6, twice. So the writer is writing correctly, 6 bytes two different times, but the host is receiving it apparently as a single buffer.
If I execute that for loop again, then the host receives (properly),
1 FRF
and then
2 FRF
handling the two received buffers each as they come in.
How can the std::stringstream cmd buffers be getting mixed like this?
There are no threads involved here.
In an effort to pick this apart a bit, if I insert just 1µsec of delay in that for loop, i.e. usleep(1); then it works properly. Also, if I call the home_axis() function manually, but equally rapid succession, without using a for loop like this,
this->pi.home_axis( this->controller_info.at(0).addr );
this->pi.home_axis( this->controller_info.at(1).addr );
then that also works.
So I'm wondering if it's possible there is a compiler optimization going on?
| This has nothing to do with the compiler at all.
TCP is a byte stream. It has no concept of message boundaries. There is no 1:1 relationship between writes and reads. You can write 2 messages of 6 bytes each, and the receiver may receive all 12 bytes at a time, or 1 byte and then 11 bytes, or any combination in between. That is just the way TCP works. By default, it breaks up data packets as it sees fit to optimize transmissions.
What is important is that TCP guarantees the bytes will be delivered (unless the connection is lost), and it will deliver the bytes in the same order that they are written.
As such, the sender must indicate in the data itself where each message begins and ends. Either by sending a message's length before its content, or by separating each message with a unique delimiter (as you are).
On the receiving side, a single read may receive a partial message, or pieces of multiple messages, etc. It is the receiver's responsibility to buffer incoming bytes and extract only complete messages from that buffer as needed, regardless of however many reads it takes to complete them.
As you are delimiting your messages with a trailing \n, the receiver should buffer all bytes and extract only messages that have received their \n, leaving any incomplete message at the end of the buffer for subsequent reads to finish.
This way, message boundaries are preserved and handled correctly.
|
72,723,371 | 72,723,395 | c++20 why can't I "pipe" into views::reverse like the other views functions? | I am testing some of the fancy new c++ features, one of which is ranges and the associated views. I find it particularly interesting that you can chain what you wish to do with a container.
You can use the binary operator|() to chain things, which is really nice. I noticed that you can chain into std::views::take(int), std::views::transform() with a lambda or function pointer, std::views::filter() with a lambda or function pointer. The only thing you can't use is std::views::reverse. That one can only be used by putting a range into it's argument. Why it that? Is there an alternative?
#include <iostream>
#include <vector>
#include <string>
#include <ranges>
int main()
{
using std::string;
using std::cout, std::endl;
const std::vector<string> vec = { "A", "B", "a", "b", "b2", "a2", "a3", "b3", "b4" };
for (auto const& val : std::views::reverse(vec) // ok
| std::views::take_while([](const string& s) {return s.size() > 0 && s[0] == 'b'; })
// | std::views::reverse() // Error?!
)
{
cout << val << endl;
}
}
Compile with g++ -std=c++20 main.cpp -o main
How would I get b3, b4 in that situation using the syntax above?
| The syntax for piping into single-argument adaptors isn't:
| views::reverse()
It's
| views::reverse
No parentheses in this case. std::views::reverse(a) could be written as a | std::views::reverse to start with as well.
Similar for all the other single-argument range adaptors (join, keys, values, elements<N>, etc.).
|
72,723,704 | 72,724,206 | 'ld' Error while compiling a module (Ubuntu 22.04) | I am trying to compile a module https://github.com/In-line/grip
I have installed the below tools
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install -y gcc-multilib g++-multilib
sudo apt-get install -y build-essential
sudo apt-get install -y libc6-dev libc6-dev-i386
sudo apt-get install -y cmake
I am getting the below error
root@test:/home/ubuntu/grip# make
/usr/bin/cmake -S/home/ubuntu/grip -B/home/ubuntu/grip --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /home/ubuntu/grip/CMakeFiles /home/ubuntu/grip//CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make[1]: Entering directory '/home/ubuntu/grip'
make -f rust/CMakeFiles/grip-rust_target.dir/build.make rust/CMakeFiles/grip-rust_target.dir/depend
make[2]: Entering directory '/home/ubuntu/grip'
cd /home/ubuntu/grip && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /home/ubuntu/grip /home/ubuntu/grip/rust /home/ubuntu/grip /home/ubuntu/grip/rust /home/ubuntu/grip/rust/CMakeFiles/grip-rust_target.dir/DependInfo.cmake --color=
make[2]: Leaving directory '/home/ubuntu/grip'
make -f rust/CMakeFiles/grip-rust_target.dir/build.make rust/CMakeFiles/grip-rust_target.dir/build
make[2]: Entering directory '/home/ubuntu/grip'
make[2]: Nothing to be done for 'rust/CMakeFiles/grip-rust_target.dir/build'.
make[2]: Leaving directory '/home/ubuntu/grip'
[ 25%] Built target grip-rust_target
make -f CMakeFiles/grip.dir/build.make CMakeFiles/grip.dir/depend
make[2]: Entering directory '/home/ubuntu/grip'
cd /home/ubuntu/grip && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /home/ubuntu/grip /home/ubuntu/grip /home/ubuntu/grip /home/ubuntu/grip /home/ubuntu/grip/CMakeFiles/grip.dir/DependInfo.cmake --color=
make[2]: Leaving directory '/home/ubuntu/grip'
make -f CMakeFiles/grip.dir/build.make CMakeFiles/grip.dir/build
make[2]: Entering directory '/home/ubuntu/grip'
[ 50%] Linking CXX shared library grip_amxx_i386.so
/usr/bin/cmake -E cmake_link_script CMakeFiles/grip.dir/link.txt --verbose=1
/usr/bin/c++ -fPIC -Wall -Wextra -Wzero-as-null-pointer-constant -Wunknown-pragmas -m32 -O3 -mtune=generic -fvisibility=hidden -flto -fPIC -static-libgcc -static-libstdc++ -Wl,--gc-sections -Wl,--version-script=/home/ubuntu/grip/version_script.lds -fuse-ld=lld -shared -Wl,-soname,grip_amxx_i386.so -o grip_amxx_i386.so CMakeFiles/grip.dir/cpp/main.cpp.o CMakeFiles/grip.dir/third_party/amxmodx/public/sdk/amxxmodule.cpp.o rust/i686-unknown-linux-gnu/debug/libgrip_rust.a -lpthread
collect2: fatal error: cannot find ‘ld’
compilation terminated.
make[2]: *** [CMakeFiles/grip.dir/build.make:117: grip_amxx_i386.so] Error 1
make[2]: Leaving directory '/home/ubuntu/grip'
make[1]: *** [CMakeFiles/Makefile2:103: CMakeFiles/grip.dir/all] Error 2
make[1]: Leaving directory '/home/ubuntu/grip'
make: *** [Makefile:94: all] Error 2
root@test:/home/ubuntu/grip#
which ld output
root@test:/home/ubuntu/grip# which ld
/usr/bin/ld
echo $PATH output
/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin
Can someone please help to solve this. I tried searching the web but couldn't get anything relevant.
| One of my friend suggested to do
apt install lld
and the issue got resolved.
|
72,725,311 | 72,727,561 | Is this good practice for reading into a string in C++? | I have a function in C++ which reads the contents of a HTTP request body into a std::string.
I came up with the following code:
void handle_request_body(int connfd, HttpRequest &req) {
unsigned long size_to_read;
try {
size_to_read = std::stoul(req.headers().at("content-length"));
} catch (std::out_of_range const &) {
return;
}
char *buf = new char[size_to_read + 1];
memset(buf, 0, size_to_read + 1);
read(connfd, buf, size_to_read);
req._body.append(buf);
delete[] buf;
}
This is a little ugly to me as I have to use new since variable-sized arrays are not allowed.
I then tried to read directly to a string instead with the following code:
void handle_request_body(int connfd, HttpRequest &req) {
unsigned long size_to_read;
try {
size_to_read = std::stoul(req.headers().at("content-length"));
} catch (std::out_of_range const &) {
return;
}
std::string buf(size_to_read + 1, 0);
read(connfd, buf.data(), size_to_read);
req._body = buf;
}
I find the second method much cleaner, but I'm worried as to whether it is considered bad practice to read directly into a std::string using its data() method.
Is there a better way to do this?
Any insight is much appreciated!
| Really depends what your read function does under the hood.
If you have control over the read function, I strongly suggest you don't use a pointer, but rather a class reference to a std container.
The resizable std containers don't guarantee that the pointers will keep pointing at the same memory i.e. if it reallocates it's size, your pointer will no longer be valid. Which is fine in this example because no one else is touching it, but in a lot of other applications this would be extremely unsafe!
Something like:
void read(int id, std::string& dest, int readLength){
//whatever code gets the data stream
dest += data;
}
If it has to be a C-Style buffer for some OS API call probably best to use a unique pointer of chars, to let the memory clean up after itself.
std::unique_ptr<char[]> buffer = std::make_unique<char[]>(size + 1);
memset(&buffer[0], 0, size + 1);
I don't recommend reading from the OS char by char as this usually has a huge performance overhead for every call, compared to reading it all at once.
|
72,725,329 | 72,725,414 | In C++, why must class member functions be defined outside class for separate compilation? | The following is a simple example for separate compilation:
// mod.cpp
#include <cstdio>
class MyModule {
public:
void print_msg();
};
void MyModule::print_msg() {
printf("hello from module\n");
}
// main.cpp
class MyModule {
public:
void print_msg();
};
int main() {
MyModule a;
a.print_msg();
}
We can compile and run it with
g++ main.cpp -c -o main.o
g++ mod.cpp -c -o mod.o
g++ main.o mod.o -o main
./main
The above works fine, but if I move the definition of MyModule::print_msg inside the class:
// mod.cpp
#include <cstdio>
class MyModule {
public:
void print_msg() { printf("hello from module\n"); }
};
I get an 'undefined reference' error for compiling main:
g++ main.cpp -c -o main.o # OK
g++ mod.cpp -c -o mod.o # OK
g++ main.o mod.o -o main # undefined reference error
/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x23): undefined reference to `MyModule::print_msg()'
collect2: error: ld returned 1 exit status
I know that the former is the standard way and the class definition should go to a header file, but I wonder why the second method doesn't work.
| Functions defined inside the class are implicitly inline. C++ requires:
The definition of an inline function [or variable (since C++17)] must be reachable in the translation unit where it is accessed.
Since you only defined it in mod.cpp, no definition is reachable in main.cpp, and compilation fails.
Typically, you'd put the definition of the class, and the definition of all functions defined within it, in a header file to be included by all users of the class. The functions defined outside the class then go in a .cpp file. That way a single consistent definition of all the inline functions is available to all users of the class, and you're not repeating the definition of the class in each .cpp file manually.
|
72,725,762 | 72,725,849 | Why universal reference as an input parameter doesn't work | template<typename T>
constexpr auto log_value(T&& value) {
if constexpr (std::is_enum_v<T>) {
cout << "enum" << endl;
}
else {
cout << "normal" << endl;
}
}
I have a function to judge whether some value is an enum, and I test it by
enum class A {
a,
s,
d
};
int main() {
auto s = A::a;
const auto& s1 = s;
auto&& s2 = A::a;
log_value(s);
log_value(s1);
log_value(s2);
log_value(A::a);
But the result is
normal
normal
normal
enum
When I change it into:
template<typename T>
constexpr auto log_value_const_left(const T& value) {
if constexpr (std::is_enum_v<T>) {
cout << "enum" << endl;
}
else {
cout << "normal" << endl;
}
}
It works
enum
enum
enum
enum
Now I just wonder why log_value doesn't work? Isn't the input parameter T&& value in log_value called universal reference which could refer to either lvalue reference or rvalue reference?
And if std::is_enum_v<T> != true in log_value,what is it exactly? Why it's changed anyway?
| The way forwarding (aka universal) references work for lvalues is by deducing the referenced type (T in your case) to an lvalue reference (A & in your case). Then T && also becomes A & according to the reference collapsing rules (& + && = &).
For rvalues this is not needed, and T is deduced to a non-reference.
You want std::is_enum_v<std::remove_reference_t<T>>.
|
72,726,793 | 72,732,652 | Unexpected compilation errors when targeting ARM | I am trying to rebuild existing C++ code for the ARM64 platform using Visual Studio 2022. (The build works well for the x86 and x64 platforms.) Most of the compilation succeeds but for one file that uses some Win32 API calls. I am getting dozen messages like
Error C3861 '_InterlockedIncrement': identifier not found
Error C3861 '_InterlockedExchangeAdd': identifier not found
Error C3861 'WriteRelease8': identifier not found
Error C3861 'WriteNoFence8': identifier not found
...
I do use some of these functions (in particular InterlockedIncrement - no underscore), but not all of them. They are declared in WinNT.h, included via Windows.h.
To investigate, I have recreated a dummy project from scratch that includes Windows.h and references InterlockedIncrement. This compiles seamlessly. I have compared all build settings, including all paths (VC++ Directories), and could not find any significant difference.
I am also getting
1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppBuild.targets(514,5):
warning MSB8028: The intermediate directory (ARM64\Release\) contains files shared from another project (Formats.vcxproj). This can lead to incorrect clean and rebuild behavior.
1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(2301,5):
warning MSB3270: There was a mismatch between the processor architecture of the project being built "" and the processor architecture of the reference "System.Data", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.
but I can't find the reason. I am not sure that this is directly related to the above problem. Note that the project is unmanaged C++ and has no reference, so that "the processor architecture of the reference "System.Data", "AMD64"" seems irrelevant.
What am I missing ?
Update:
I discovered hidden references in the project (not appearing in the IDE) and cleaned that. This solves the second issue. (The first remains.)
| I finally found the cause. Here is how I proceeded:
I removed all files from the whole project, except the offending one (checked that the problem was still there);
I added that file to the dummy project (the problem was not showing there);
I compared the project files, but this told me nothing because they were too big and differ at numerous places;
I removed chunks from the file, each time recompiling, until the problem disappeared;
I understood that it was related to an #include <comdef.h> statement;
The original file (crippled with conditionals) was using an _ARM_ macro of mine to enable/disable some features for this platform.
After reducing the file to the single #include, I noticed that declaring the macro or not was enough to trigger the problem. Bingo !
It turns out that, though not documented, this macro is reserved by Microsoft and changes the behavior of the Windows includes.
The cure was just to use a non-conflicting macro.
|
72,727,086 | 72,728,832 | The P/A deducation when determining the partial order of C++ overloaded function templates | In cppreference.com, there is an example:
template<class T>
void f(T, T*); // #1
template<class T>
void f(T, int*); // #2
void m(int* p)
{
f(0, p); // deduction for #1: void f(T, T*) [T = int]
// deduction for #2: void f(T, int*) [T = int]
// partial ordering:
// #1 from #2: void(T,T*) from void(U1,int*): P1=T, A1=U1: T=U1
// P2=T*, A2=int*: T=int: fails
// #2 from #1: void(T,int*) from void(U1,U2*): P1=T A1=U1: T=U1
// P2=int* A2=U2*: fails
// neither is more specialized w.r.t T, the call is ambiguous
}
I think the deduction procedure "#1 from #2" is success because "P2=T*, A2=int*: T=int". But it fails, I don't know the reason.
|
For each type, non-type, and template parameter, including parameter packs, a unique fictitious type, value, or template is generated and substituted into function type of the template
U1 here is not a template type; it's a unique ficitious type and it's different from int, so the deduction fails.
|
72,727,268 | 72,727,368 | how to show a variable in MESSAGE_TEXT in signal query in c++ | I am using Signal query to catch errors in my c++ programming:
in the program user has to enter a database name and i check the database if it does not exists I have to return proper error message:
std::string database_name;
std::cin<<database_name;
if(!exists(database_name)){
query="SIGNAL SQLSTATE '42000' SET MYSQL_ERRNO='1049', MESSAGE_TEXT = 'Unknown database';";
}
how can I print the database_name variable after Unknown database?
| You can format the string using
query = std::format( "... MESSAGE_TEXT = 'Unknown database {}'", database_name );
This will replace {} with the first string argument (database_name)
Or you could use a string stream like
std::ostringstream ss;
ss << "... MESSAGE_TEXT = 'Unknown database '" << database_name << "'";
query = ss.str();
|
72,727,396 | 72,727,629 | Member function doesn't work when using pointer to class | Scenario: I have two classes, each contains a pointer to the other (when using them, being able to refer to the other is going to be important so I deemed this appropriate). When I try accessing a private variable from one class via using the pointer to the other and a getter function inside that, it works perfectly.
Problem: Using a setter (in this case, addPoints)/manipulating the variables however leads to no result.
I'm new so anything here might be "improper etiquette" and bad practice. Feel free to point them out! But please also try to provide a solution. This is also my first question on SO, so please be gentle!
Related code pieces:
Team.h
#include "Driver.h"
using namespace std;
class Team {
int Points = 0;
vector<Driver*> Drivers;
public:
void addPoints(int gained); //does not work
int getPoints(); //works perfectly
Driver getDriver(int nr);
void setInstance(vector<Driver*> drivers);
};
Team.cpp
#include "Team.h"
#include "Driver.h"
using namespace std;
void Team::addPoints(int gained) {
this->Points = this->Points + gained;
}
int Team::getPoints() {
return this->Points;
}
Driver Team::getDriver(int nr) {
return *Drivers[nr];
}
void Team::setInstance(vector<Driver*> drivers) {
this->Drivers = drivers;
}
Driver.h
using namespace std;
class Team;
class Driver {
int Points = 0;
Team* DriversTeam;
public:
void SetTeam(Team& team);
Team getTeam();
int getPoints(); //works
void addPoints(int gained); //doesn't work
};
Driver.cpp
#include "Driver.h"
#include "Team.h"
using namespace std;
void Driver::SetTeam(::Team& team) {
this->DriversTeam = &team;
}
Team Driver::getTeam() {
return *DriversTeam;
}
int Driver::getPoints() {
return this->Points;
}
void Driver::addPoints(int gained) {
this->Points = this->Points + gained;
}
Initializer.cpp (linking drivers to teams)
void InitializeData(vector<Team>& teams, vector<Driver> &drivers) {
//(...)
//reads each team in from data file to memory
//key part:
vector<Driver*> teamsDrivers;
for (auto& iter : drivers) { //this loop mainly determines which driver to link with which teams
if (iter.getName().compare(values[4]) == 0) { //values is csv line data in a string vector. I guess not the prettiest parsing method here but will be revised
teamsDrivers.push_back(&iter);
}else if(iter.getName().compare(values[5]) == 0) {
teamsDrivers.push_back(&iter);
}
}
tempTeam.setInstance(teamsDrivers);
teams.push_back(tempTeam);
}
(linking driver to team)
//drivers are linked to teams last, as they are declared first (so I cannot link them to the yet nonexisting teams)
void LinkTeam(vector<Driver>& drivers, vector<Team>& teams) {
for (auto& driverIter : drivers) { //iterate through drivers
for (auto& teamIter : teams) { // iterate through teams
bool found = 0;
for (size_t i = 0; i < teamIter.DriverAmount(); i++) {
if (driverIter.getName() == teamIter.getDriver(i).getName()) {
driverIter.SetTeam(teamIter);
found = 1;
break;
}
}
if (found) { //exit iterating if driver is found
break;
}
}
}
}
Example of use in main.cpp
teams[0].addPoints(10);
drivers[3].getTeam().addPoints(15); //driver 3 is linked to team 0
cout << teams[0].getPoints(); //15
cout << drivers[3].getTeam().getPoints(); //15
teams[0].getDriver(1).addPoints(20); //driver 1 of team 0=driver[3]
drivers[3].addPoints(25);
cout << drivers[3].getPoints(); //25
cout << teams[0].getDriver(1).getPoints(); //25
Thanks for the help in advance.
| This is quite simple:
Your getTeam() and getDriver() functions are returning copies of the objects, not references, so the addPoints() are performed on temporary copies and not the real ones.
To fix it, simply change the return types to references (add &):
Team& getTeam();
and
Driver& getDriver();
|
72,727,684 | 72,728,992 | make using namespace global from c++ module | I am trying to expose a c++ namespace to whatever includes that c++ module.
Usually in a header file I can just write using namespace x::y::z; and it'll work. I couldn't get it to work from a module.
I am using visual studio 2022 with MSVC v143, c++ latest.
| In the current standard draft § 10.2 [module.interface], we see:
export using namespace N; // error: does not declare a name
In the same section, there are also correct exports of non-namespace using declarations
export using T = S; // OK, exports name T denoting type S
and I believe that namespace aliases should also work
export namespace N = M;
The distinction is that the using namespace directive provides a tunnel for unqualified lookup to search outside its natural scope, but doesn't declare any new names. Both using declarations and namespace aliases do declare new names, and those names should be exportable.
Concretely, either of these should work:
export using float3 = linalg::aliases::float3; // for each type
export namespace la = linalg::aliases; // or just provide a short name
|
72,728,374 | 72,737,017 | Qt5.9.6 do not follow RPATH to search openssl |
I'm working on Qt based project on Linux based OS. We use Qt5.9.6.
When we launch our application, we've got this log from Qt
qt.network.ssl: Incompatible version of OpenSSL
After a few research I found that Qt loads the version 1.1 of openssl whereas Qt5.9.6 needs the 1.0.2k version. So I put the right version of openssl next to our application and I set the RPATH accordingly. But it does not works. I'll try with LD_LIBRARY_PATH and that works.
I used LD_DEBUG=libs to see where the program try to load the dynamic library and it appears that for Qt, the RPATH is use partially or not at all.
I've created a docker image named eaglejoe/qtopenssl-bug with a minimal example.
To compile the example launch
cmake --preset default
cmake --build build
and launch the program with build/testqt
Does someone kwow why the RPATH is not use completely here ?
(In the example it's the RUNPATH that is used but I have the same issue with a RPATH)
Thank you for your help
| So the thing is, Qt loads the OpenSSL library as a plugin, and the dynamic linker ld.so on Linux only takes into account the rpath of the executable and/or shared object that calls dlopen(). And because Qt itself doesn't have the rpath for your OpenSSL copy set, it won't load it.
The best way around that is (as long as you don't want to recompile Qt yourself with that rpath) to load OpenSSL manually before invoking any Qt function. So add the following to your code at the beginning of main():
void* crypto_handle = dlopen("libcrypto.so", RTLD_NOW | RTLD_GLOBAL);
if (!crypto_handle)
std::cerr << "error loading libcrypto.so: " << dlerror() << std::endl;
void* ssl_handle = dlopen("libssl.so", RTLD_NOW | RTLD_GLOBAL);
if (!ssl_handle)
std::cerr << "error loading libssl.so: " << dlerror() << std::endl;
Note that you must load libcrypto.so before libssl.so, otherwise libssl.so won't load, because libssl.so in your installation doesn't have an rpath set for itself, so it won't find the correct libcypto.so unless you load that yourself as well.
Further note: technically you could use the official SONAMEs libssl.so.1.0.0 and libcrypto.so.1.0.0 (yes, even for 1.0.2 those are the correct SONAMEs), but your Qt version is compiled against a weird version of OpenSSL that thinks its SONAME has 1.0.2k as the extension, not 1.0.0 as it should be, so it will only find the libraries by their generic names, and you have to load the libraries by their generic names (libssl.so, libcrypto.so) to make the dynamic linker aware that these are aliases.
If both of these are loaded, Qt will be able to work, because then the dynamic linker will see that the libraries in question have already been loaded into the program, and will hence reuse them, without looking for them in the filesystem.
Running your program will then give the following output:
build openssl: OpenSSL 1.0.2k-fips 26 Jan 2017
load openssl: OpenSSL 1.0.2k 26 Jan 2017
That all said: OpenSSL 1.0.2 has not been supported for 2.5 years. And the version you're using, 1.0.2k is even older, that's from 5.5 years (!) ago. There are several security issues that have been fixed in OpenSSL since, and it is a really bad idea to write new code that relies on such outdated software when it comes to network communication.
Please, please use OpenSSL 1.1, which is still supported until September of next year. Qt has support for that since 5.12. From my experience the upgrade from 5.9 to 5.12 was completely painless. Though ideally I'd suggest that new code should use Qt6.
(Unfortunately not even Qt6 appears to work with OpenSSL 3.0 yet, but hopefully that'll change soon.)
|
72,729,549 | 72,729,723 | OpenCV Mat::convertTo(type) does not convert the type | GIVEN:
The following code fragment:
#include <opencv2/core.hpp>
#include <iostream>
int
main(int argc, char** argv)
{
cv::Mat a = (cv::Mat_<double>(3,1) << 1, 2, 3);
cv::Mat b;
std::cout << "a(before): " << cv::typeToString(a.type()) << std::endl;
std::cout << "b(before): " << cv::typeToString(b.type()) << std::endl;
std::cout << std::endl;
std::cout << "Convert 'a' --> 'b' with type CV_64FC4" << std::endl;
std::cout << std::endl;
a.convertTo(b, CV_64FC4);
std::cout << "a(after): " << cv::typeToString(a.type()) << std::endl;
std::cout << "b(after): " << cv::typeToString(b.type()) << std::endl;
return 0;
}
EXPECTATION:
Should produce, in my understanding, the following output:
a(before): CV_64FC1
b(before): CV_8UC1
Convert 'a' --> 'b' with type CV_64FC4
a(after): CV_64FC1
b(after): CV_64FC4
OUTPUT:
Instead, the output is as follows:
a(before): CV_64FC1
b(before): CV_8UC1
Convert 'a' --> 'b' with type CV_64FC4
a(after): CV_64FC1
b(after): CV_64FC1
QUESTION:
What is going on here? How can I actually convert to the specified target type?
| Short answer:
cv::Mat::convertTo does not support changing the number of channels.
Longer answer:
As you can see in the documentation regarding the rtype paremeter of cv::Mat::convertTo (the one you pass CV_64FC4 to):
desired output matrix type or, rather, the depth since the number of
channels are the same as the input has; if rtype is negative, the
output matrix will have the same type as the input.
I.e. convertTo does not handle the case of changing the number of channels (only the bit depth of each channel).
Although it is not documented explicitly, I guess cv::Mat::convertTo extracts the bit depth from rtype and ignores the number of channels.
In your example: a has a single channels, and therefore so is b after the conversion.
In order to see the effect of convertTo, you can pass e.g. CV_32FC1 in order to convert 64 bit doubles to 32 bit floats.
Update:
According to the OP's request (in the comments below), here are examples of changing the number of channels using cv::mixChannels:
cv::Mat img1c = (cv::Mat_<double>(3, 1) << 1, 2, 3);
cv::Mat img4c(img1c.size(), CV_64FC4);
cv::Mat img1c_2(img1c.size(), CV_64FC1);
// Convert 1 channel into 4 (duplicate the channel):
std::vector<int> fromTo1{ 0,0, 0,1, 0,2, 0,3 }; // 0->0, 0->1, 0->2, 0->3
cv::mixChannels(img1c, img4c, fromTo1);
// Convert back to 1 channel (pick one of the channels - the 1st one in this case):
std::vector<int> fromTo2{ 0,0 }; // 0->0 (pick the 1st channel)
cv::mixChannels(img4c, img1c_2, fromTo2);
|
72,729,727 | 72,745,602 | Standard layout, taking address of member and indexing past it to next member | Suppose we have a standard-layout class, simplified to this:
struct X {
int num;
Object obj; // also standard layout
char buf[512];
};
As I understand it, if we have an instance of X, we can take its address and cast it to char* and look at the content of X as if it was an array of bytes.
However, it's a little less clear if we do the following, taking the address of a member and walking past it as if we were walking through X itself:
X x;
char* p = reinterpret_cast<char*>(&x.obj) + sizeof(Object);
*((int*)p) = 1234; // write an int into buf
Is this valid and well defined?
I was commenting to a colleague that if we take the address of obj we should limit ourselves to the memory of that object, and not assume that reading past its end is safely going into the next field of the containing struct (buf in this case). I have been asked to defend that statement. In looking for an answer only managed to confuse myself a bit by all the similar questions that don't seem to address this precisely. :)
Standard citations appreciated. Also, I'd prefer to stick to the question "is this is valid", and ignore the question of its sensibility.
|
As I understand it, if we have an instance of X, we can take its address and cast it to char* and look at the content of X as if it was an array of bytes.
The standard doesn't actually allow this currently. Casting to char* will not change the pointer value (per [expr.static.cast]/13) and as a result you will not be allowed to apply pointer arithmetic on it as it violates [expr.add]/4 and/or [expr.add]/6.
This is however often assumed to be allowed in practice and probably considered a defect in the standard. The paper P1839 by Timur Doumler and Krystian Stasiowski is trying to address that.
But even applying the proposed wording in this paper (revision P1839R5)
X x;
char* p = reinterpret_cast<char*>(&x.obj) + sizeof(Object);
*((int*)p) = 1234; // write an int into buf
will have undefined behavior, at least assuming I am interpreting its proposed wording and examples correctly. (I might not be though.)
First of all, there is no guarantee that buf will be correctly aligned for an int. If it isn't, then the cast (int*)p will produce an unspecified pointer value. But also, there is no guarantee in general that there is no padding between obj and buf.
Even if you assume correct alignment and no padding, because e.g. you have guarantees from your ABI or compiler, there are still problems.
First, the proposal would only allow unsigned char*, not char* or std::byte*, to access the object representation. See "Known issues" section.
Second, after fixing that, p would be a pointer one-past the object representation of obj, so it doesn't point to an object. As a consequence the cast (int*)p cannot point to any int object that might have been implicitly created in buf when X x;'s lifetime started. Instead [expr.static.cast]/13 will apply and the value of the pointer remains unchanged.
Trying to dereference the int* pointer pointing one-past-the-end of the object representation of obj will then cause undefined behavior (as it is not pointing to an object).
You also can't save this using std::launder on the pointer, because a pointer to an int nested inside buf would give you access to bytes which are not reachable through a pointer to the object representation of buf, violating std::launder's precondition, see [ptr.launder]/4.
In a broader picture, if you look at how e.g. std::launder is specified, it seems to me that the intention is definitively not to allow this. The way it is specified, it is impossible to use a pointer (in)to a member of a class (except the first if standard layout) to access memory of other (non-overlapping) members. This specifically seems to be intended to allow a compiler to do optimization by pointer analysis based on assuming that these other members are unreachable. (I don't know whether there is any compiler actually doing this though.)
|
72,729,861 | 72,732,725 | Enabling ANSI escape sequences on Windows let disable some Unicode sequences. How to Solve? | I recently enabled ANSI escape sequences on my Windows console using this functions defined in an header my_windows.h:
#ifndef WINDOWS_HPP
#define WINDOWS_HPP
namespace osm
{
extern void enableANSI();
extern void disableANSI();
}
and implemented in my_windows.cpp
#ifdef _WIN32
#include <windows.h>
#endif
#include "my_windows.hpp"
#include <iostream>
#include <stdexcept>
namespace osm
{
#ifdef _WIN32
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
#endif
#ifdef _WIN32
static HANDLE stdoutHandle;
static DWORD outModeInit;
#endif
void enableANSI()
{
#ifdef _WIN32
DWORD outMode = 0;
stdoutHandle = GetStdHandle( STD_OUTPUT_HANDLE );
if( stdoutHandle == INVALID_HANDLE_VALUE )
{
exit( GetLastError() );
}
if( ! GetConsoleMode( stdoutHandle, &outMode ) )
{
exit( GetLastError() );
}
outModeInit = outMode;
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if( ! SetConsoleMode( stdoutHandle, outMode ) )
{
exit( GetLastError() );
}
#endif
}
void disableANSI()
{
std::cout << "\033[0m";
#ifdef _WIN32
if( ! SetConsoleMode( stdoutHandle, outModeInit ) )
{
exit( GetLastError() );
}
#endif
}
}
They are used respectively to enable and disable ANSI escape sequences and work well. The problem is that it seems that the function to enable ANSI at the same time disable some Unicode characters, in particular: "\u250c", "\u2500", "\u2510", "\u2502", "\u2502", "\u2514", "\u2500", "\u2518" which if sent to the output stream show strange symbols instead of their corresponding characters. If I don't use the enableANSI function the unicode characters works well.
Sorry for the maybe trivial question, but it is the first time I deal with Windows cpp functions.
Thanks.
| Thanks to PanagiotisKanavos i solved the issue by using the chcp 65001 command. The problem is that if I am on MSYS2 I am unable to run this command from the shell: therefore I used the system() function to call it directly in my code, since my executables run directly on the Windows shell:
// code without using ANSI escape sequences...
enableANSI();
// code which uses ANSI escape sequences...
system( "chcp 65001" );
// code which uses ANSI escape sequences and Unicode characters...
|
72,729,926 | 72,730,820 | C++ - I want to show a set of random dice, but I can't find out how | I'm fairly new to this, been writing code for ~3 months and now I have to make a dice game for a group project.
So far, the console shows what I expect it to show (5 random dice values)
But what I want to do to improve it is to show an actual die instead of an individual number, like ⚀⚁⚂⚃⚄⚅
These are the functions I've written so far for this part (for a separate header):
///Lanza los dados
void cargarCubilete(int v[], int tam, int limite){
int i;
srand(time(NULL));
for( i=0; i<tam; i++ ){
v[i]=(rand()%limite)+1;
}
}
///MUESTRA EL CUBILETE
void mostrarCubilete(int v[], int tam){
int i;
for(i=0;i<tam;i++){
cout<<v[i]<<"\t";
}
}
Any tips on how to do it?
Thanks!
|
But what I want to do to improve it is to show an actual die instead
of an individual number, like ⚀⚁⚂⚃⚄⚅
Note those characters are non-ASCII. So to make it work you have to take care of encoding of characters (encoding) for each step (source, building, running on some specific system). At final step terminal used has to have locale set in such way this characters are covered (not all encodings have this characters) and also font used by this terminal program have to have those characters.
So there is a lot of places where something may went wrong, see some my SO answer if you need more details.
Most common encoding is UTF-8 so es a result this characters are not single byte, so the have to be kept in code as some form string.
For example this is working fine:
#include <array>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <random>
using namespace std::literals;
constexpr std::array DiceSides {
"⚀"sv, "⚁"sv, "⚂"sv, "⚃"sv, "⚄"sv, "⚅"sv
};
int main()
{
// std::locale::global(std::locale{"<locale used for exacutable>"});
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dice(1, 6);
std::cout.imbue(std::locale(""));
for (size_t i = 0; i < 20; ++i) {
auto x = dice(gen);
std::cout << i + 1 << ": " << x << " = " << DiceSides[x - 1] << '\n';
}
return 0;
}
https://godbolt.org/z/WaMYeKoM6
|
72,729,944 | 72,752,985 | Search String Highlight in qt or qml | I have use case where in text entered in TextField (Qml Component) should highlight all the texts which matches in the list view content.
I have explored many blogs, in every blog I can just see the snippet code. But not the complete usage, so I couldn't find any proper solution. Can anyone help me out with sample working example.
I have attached sample output how I am expecting
| The simple example using Text as a delegate:
ColumnLayout
{
anchors.fill: parent
spacing: 5
TextField {
id: input
Layout.preferredHeight: 30
Layout.fillWidth: true
}
ListView {
id: list
Layout.fillHeight: true
Layout.fillWidth: true
model: ["aaaa bbbb cccc","dddd aaaa bbbb","cccc bbbb eeee"]
delegate: Text {
property string origText: modelData
text: list.hightlightText(origText)
}
function hightlightText(txt)
{
var str = input.text;
var pos = txt.indexOf(str);
if(pos !== (-1))
{
return txt.replace(str,"<font color='#FF0000'>" + str + "</font>")
}
return txt;
}
}
}
You can style the selection using supported subset of HTML tags.
|
72,730,020 | 72,732,772 | Is there a compilation flag to detect duplicate lamda parameter-lambda member? | This code compiles with g++, no collision is detected, although s is the parameter captured by lambda and the lambda parameter. My compiler is g++.
gcc Version is
gcc (Debian 4.9.2-10+deb8u2) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
and I am using these compilation flags :
-W
-Wall
-ansi
-pedantic
-s
-march=native
-flto
-fwhole-program
-Wfatal-errors
-Wextra
-std=c++1y
-frename-registers
-fipa-pta
-Ofast
-pedantic-errors
-fira-loop-pressure
-fomit-frame-pointer
-fforce-addr
-falign-functions
-fno-cprop-registers
-fstrength-reduce
Code is
#include <vector>
#include <algorithm>
#include <iostream>
int main (int argc, char* argv []) {
int s (0);
std::vector<int> vec ({3, 5, 13, 1});
std::for_each (vec.begin (), vec.end (), [&s] (const int& s) {
s = s>s?s:s;
});
std::cout << "max ox v is " << s << std::endl;
}
Is there a compilation option to detect this kind of error ?
| Upgrade your compilers.
Based on https://godbolt.org/z/h3Y7dW1dP that warning is missing for gcc 8.5 (with -std=c++17) and clang 7.1.0.
You should upgrade to gcc 9.1 and clang 8.0.0 or later. (Preferably a lot later.)
|
72,730,038 | 72,731,043 | Creating object on stack, from a class with dynamic members | Assume we create an object on stack as
class Test{
Test(int i) {i_=i;}
Test(std::vector<int> v) {v_=v;}
int i_;
std::vector<int> v_;
};
int main() {
Test a;
// how much memory is occupied/reserved now for a?
.
.
.
return 0;
}
How compiler determines the required size for "a", when it is not yet known which constructor is going to be called? I mean, how much memory is reserved on stack? what about if i used "new" for object creation?
My example is very simplified in order to transfer my point. The aim of my question is to understand better the meaning of object creation/initialization on stack/heap.
|
How compiler determines the required size for "a", when it is not yet known which constructor is going to be called?
This question hinges on two misunderstandings:
First, Test a; does call the default constructor. Next, the size of objects to be allocated on the stack is a constant: sizeof(Test). This size does not change when more elements are added to the vector member, because those elements to not contribute to the size of a Test, they are allocated dynamically on the heap.
what about if i used "new" for object creation?
No difference concerning the size of the object. sizeof(Test) is a compile time constant and does not change depending on how you create the object. Though with Test* p = new Test; you'll have only p on the stack and its size is sizeof(Test*), while the object is on the heap.
PS: Actually "heap" and "stack" are not terms used by the standard, but as they are so common I think its ok to use them here. More formally correct would be to talk about automatic and dynamic storage duration (https://en.cppreference.com/w/cpp/language/storage_duration).
|
72,730,133 | 72,735,454 | unordered_map: Lookup pair of std::string with a pair of std::string_view | Given a hashmap that is keyed on a pair of strings, e.g:
std::unordered_map<std::pair<String, String>, int> myMap;
How could one do a lookup with a pair of std::string_view, e.g:
std::string s = "I'm a string";
std::string s2 = "I'm also a string";
std::string_view sv(s);
std::string_view sv2(s2);
myMap.find(std::make_pair(sv, sv2));
I guess that I need to define my own comparator somewhere, but I'm not sure where to begin.
| With C++20's heterogeneous lookups this can be done (see documentation of unordered_map::find()). For this to work a hash functor and a equality functor have to be defined, e.g.:
struct hash {
template <typename T>
auto operator()(const std::pair<T, T>& pair) const {
return std::hash<T>{}(pair.first) ^ std::hash<T>{}(pair.second); // not to be used in production (combining hashes using XOR is bad practice)
}
using is_transparent = void; // required to make find() work with different type than key_type
};
struct equal {
template <typename A, typename B>
auto operator()(const std::pair<A, A>& a,
const std::pair<B, B>& b) const {
return a.first == b.first && a.second == b.second;
}
using is_transparent = void; // required to make find() work with different type than key_type
};
The type of the map then has to be changed to std::unordered_map<std::pair<std::string, std::string>, int, hash, equal> in order to use the defined functors.
find() now works as intended:
using namespace std::literals;
std::unordered_map<std::pair<std::string, std::string>, int, hash, equal> map{};
map.insert({std::pair{"a"s, "b"s}, 42});
if (auto it = map.find(std::pair{"a"sv, "b"sv}); it != map.end())
std::cout << it->second << std::endl;
if (auto it = map.find(std::pair{"x"s, "y"s}); it != map.end())
std::cout << it->second << std::endl;
// prints 42
The implementation can be played with here
|
72,731,302 | 72,731,379 | How to directly input RGB(A) values in textures in C++/OpenGL? | I want to dabble in some procedural textures in an OpenGL project, but nothing seems to work. All I need is to input the RGB and maybe A values into an empty texture, instead of loading it from a file. How do I do this, in actual, practical code?
Edit: There is no main code yet, because I have found nothing that works. The current best guess is this:
void GenerateTexture()
{
unsigned char image_data[16] = {0, 0, 150, 255, 125, 0, 0, 255, 0, 0, 150, 255, 125, 0, 0, 255};
glGenTextures(1, &tex_obj);
glBindTexture(GL_TEXTURE_2D, tex_obj);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
}
... implemented like this:
glBegin (GL_QUADS);
if (*irrelevant for question*){
glTexCoord2f(0.0,1.0);
glVertex3f (-0.45-cam.pos.val[0], 0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
glTexCoord2f(0.0,0.0);
glVertex3f (-0.45-cam.pos.val[0], -0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
glTexCoord2f(1.0,0.0);
glVertex3f (0.45-cam.pos.val[0], -0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
glTexCoord2f(1.0,1.0);
glVertex3f (0.45-cam.pos.val[0], 0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
}
glEnd ();
... but as soon as it is run with more than a 1x1 texture, it just goes clean white.
| Create an array of data and load it into a texture image:
uint8_t image_data[4] = {255, 0, 0, 255}; // red
GLuint tex_obj;
glGenTextures(1, &tex_obj);
glBindTexture(GL_TEXTURE_2D, tex_obj);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
|
72,731,594 | 72,732,080 | Reserve 2D Vector in C++ and copy data from array | I hope to use vector to process the 2d array data obtained by calling a third-party library.
Although I can simply use the loop to assign values one by one, But I prefer to use methods such as insert and copy to deal with this.
I found that reserve doesn't seem to work here. So I used resize instead.
double **a = new double *[1024];
for (int i = 0; i < 1024; ++i) {
a[i] = new double[512];
}
std::vector<std::vector<double>> a_v;
a_v.resize(1024, std::vector<double>(512));
// Copy a -> a_v
I made these attempts:
// Not Working, just 0 in vector
for (int i = 0; i < 1024; ++i){
a_v[i].insert(a_v[i].end(), a[i], a[i] + 512);
}
Is there any good way to solve this problem.
For a 1D array I write like this:
double *b = new double[1024];
std::vector<double> b_v;
b_v.reserve(1024);
b_v.insert(b_v.end(), b, b + 1024);
| If the size of the source array is fixed, it is strongly recommended to use std::array instead of std::vector. std::array has continuous memory layout for multidimensional structures, thus std::memcpy can be used for copy if the source array is also continuous in memory.
Look back to the original question. If you want to construct a std::vector<std::vector<double>> from the source array, use a single loop to construct 1D vectors from the source:
std::vector<std::vector<double>> a_v;
a_v.reserve(1024);
for (int i = 0; i < 1024; ++i) {
a_v.emplace_back(std::vector<double>(&(a[i][0]), &(a[i][512])));
}
If there is already a std::vector<std::vector<double>> with the proper size, and you literally just want to do a copy from the source, use the assign member function:
for (int i = 0; i < 1024; ++i) {
a_v[i].assign(&(a[i][0]), &(a[i][512]));
}
|
72,731,652 | 72,738,165 | Delete elements of vector from other vector | I want to delete all elements of a vector v which are contained by v2;
Is this solution good or should I use something else ?
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
std::vector<int> v = {1,2,3,4,5,1,2};
std::vector<int> v2 = {1,2,3};
v.erase(std::remove_if(v.begin(), v.end(), [v2](int x)
{
auto it = std::find(v2.begin(), v2.end(), x);
return it != v2.end();
}), v.end());
for (auto i : v)
{
std::cout<<i<< " ";
}
return 0;
}
Output:
4 5
| It's quite good for small filtering v2. It is a bit better if you pass v2 by reference.
v.erase(std::remove_if(v.begin(), v.end(), [&v2](int x)
{
std::find(v2.begin(), v2.end(), x) != v2.end();
}), v.end());
If v2 is large it is better to replace it with std::unordered_set<int> s. It also removed duplicates in v2.
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_set>
using namespace std;
int main()
{
std::vector<int> v = {1,2,3,4,5,1,2};
std::vector<int> v2 = {1,2,3};
std::unordered_set<int> s(v2.begin(), v2.end());
v.erase(std::remove_if(v.begin(), v.end(), [&s](int x) { return s.count(x); }),
v.end());
for (auto i : v)
{
std::cout<<i<< " ";
}
return 0;
}
|
72,732,371 | 72,732,838 | Make a common function for a "type" and the vector of "type" using templates in C++ | I was writing functions and came across this situation:
void doSomeThing(std::vector<someType> vec)
{
for(element : vec)
{
// do Something different if it is in vector
}
}
void doSomeThing(someType element)
{
// do Something else if it was not a vector
}
I need them to be separate like above stated. I was wondering if there was a way using templates to deduce the type and do the processing accordingly?
| Well, yes, it is possible.
For example, you could do;
template<class someType>
void doSomeThing( const someType &obj )
{
// do something assuming someType is not a vector of something
}
template<class someType>
void doSomeThing( const std::vector<someType> &obj )
{
// do something different if a vector<someType> is passed
}
int main()
{
int x = 24;
std::vector<int> a{1,2,3}; // assuming C++11 and later
doSomeThing(x); // will call a specialisation of the first form above
doSomething(a); // will call a specialisation of the second form above
}
Personally, I'd do it slightly differently though - instead of overloading for a vector, I'd overload for a pair of iterators. For example, assuming doSomething() is just function that prints to std::cout
template<class someType>
void doSomeThing( const someType &obj )
{
std::cout << obj;
}
template<class Iter>
void doSomeThing( Iter begin, Iter end)
{
while(begin != end)
{
std::cout << *begin << ' ';
++begin;
}
std::cout << '\n';
}
which will work with iterators from any standard container (e.g. specialisations of std::vector, std::list) or anything else that can provide a pair of valid iterators.
int main()
{
int x = 24;
std::vector<int> a{1,2,3}; // assuming C++11 and later
std::list<double> b {42.0, 45.0};
doSomeThing(x);
doSomething(std::begin(a), std::end(a));
doSomething(std::begin(b), std::end(b));
}
|
72,733,063 | 72,754,601 | V8 lib and C++ inlining behavior differs from expectations and reproducing in separate project | I'm getting an error trying to construct a v8::ScriptOrigin object. Confirming the compiler error, my IDE only resolves the implicit copy and move constructors.
v8_api.cc: error: no matching constructor for initialization of 'v8::ScriptOrigin'
v8::ScriptOrigin::ScriptOrigin is marked with V8_INLINE macro which specifies inline and always_inline for the constructor.
I'm building my project with CMake and Apple clang version 13.1.6 and using an embedded v8 with args.gn:
v8_static_library=true
v8_monolithic=true
v8_use_external_startup_data=false
is_component_build=false
use_custom_libcxx=false
If I change v8config.h to define V8_INLINE as an empty string, I still can't resolve v8::ScriptOrigin::ScriptOrigin(...).
When I run nm I get:
libv8_monolith.a:v8-inspector-impl.o: 0000000000001070 0000000000000000 T v8::ScriptOrigin::ScriptOrigin(v8::Isolate*, v8::Local<v8::Value>, int, int, bool, int, v8::Local<v8::Value>, bool, bool, bool, v8::Local<v8::Data>)
libv8_monolith.a:v8-inspector-impl.o: 00000000000070a0 0000000000000000 T v8::ScriptOrigin::ScriptOrigin(v8::Isolate*, v8::Local<v8::Value>, int, int, bool, int, v8::Local<v8::Value>, bool, bool, bool, v8::Local<v8::Data>)
It looks like it's exporting a symbol twice for each object that uses it.
I get the same nm result when I build libv8_monolith.a with args.gn v8_no_inline=true, or without it or if I replace the #define V8_INLINE blocks with #define V8_INLINE inline or #define V8_INLINE /*not inlining*/ or delete V8_INLINE from ScriptOrigin.
I'm stumped. Why is it being exported as a symbol whether I build with v8_no_inline or not and why is it being exported twice for each comp unit that uses it?
I should be able to modify the v8-message.h header file to not be inline and then I could resolve the constructor from my codebase. However, I'm guessing it wouldn't link against it because there's duplicate symbols in the lib.
Because I've never used inline I created a sandbox project and (consistent with the docs I've read) confirmed that inlining prevents an external symbol and linking from another object. Although, I'm only seeing that with always_inline attribute and finding that the compiler chooses not to inline when I only use the inline keyword. However, the v8 lib differs from the sample project because the v8 lib exports two symbols for each object that references v8::ScriptOrigin.
How does this API work within the v8 codebase, or from other embedders like node.js or sample v8 code I've seen demoing the ScriptOrigin?
#include "v8/include/libplatform/libplatform.h"
#include "v8/include/v8-initialization.h"
#include "v8/include/v8-message.h"
int main([[maybe_unused]] int argc, char *argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate *isolate = v8::Isolate::New(create_params);
// this ctor does not resolve
auto script_origin = new v8::ScriptOrigin(isolate, v8::String::NewFromUtf8(isolate, "main.mjs"));
}
| Trying to compile this snippet tells you exactly what's going on:
$ clang++ -std=c++17 test.cc -o test.bin -Iv8/include
test.cc:18:30: error: no matching constructor for initialization of 'v8::ScriptOrigin'
auto script_origin = new v8::ScriptOrigin(isolate, v8::String::NewFromUtf8(isolate, "main.mjs"));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./v8/include/v8-message.h:64:13: note: candidate constructor not viable: no known conversion from 'MaybeLocal<v8::String>' to 'Local<v8::Value>' for 2nd argument
V8_INLINE ScriptOrigin(Isolate* isolate, Local<Value> resource_name,
^
./v8/include/v8-message.h:62:17: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
class V8_EXPORT ScriptOrigin {
^
./v8/include/v8-message.h:62:17: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
1 error generated.
Note in particular the snippet
no known conversion from 'MaybeLocal<v8::String>' to 'Local<v8::Value>' for 2nd argument.
You're trying to call a constructor that doesn't exist. Your IDE and the compiler are correct in reporting this.
Creating a new string can fail, in particular when the requested string is too large, so NewStringFromUtf8 returns a MaybeLocal, forcing calling code to check for errors and handle them appropriately. If the string is as short as "main.mjs", you can trust that allocating it won't fail, and simply use the .ToLocalChecked() conversion (which will crash your process if there was an error, so in general it's better to use the bool-returning .ToLocal(...) and handle errors gracefully).
So if you change the last line to:
auto script_origin = new v8::ScriptOrigin(
isolate,
v8::String::NewFromUtf8(isolate, "main.mjs").ToLocalChecked());
then this snippet will compile.
Inlining has nothing to do with this, neither does the V8_INLINE macro, or the output of nm, or symbol export or other linker-related issues. It should go without saying that editing V8's header files is also not necessary for embedding V8.
In general, when working with C++ it makes sense to distinguish clearly between compiler errors and linker errors. When the compiler is complaining, then looking into possible linking issues is "barking up the wrong tree".
|
72,733,405 | 72,733,776 | Inserting iterable containers into map for keys and values | I have two arrays like the following. The arrays are always the same size.
std::array<int, 5> keys;
std::array<int, 5> values;
I want to load them into a map for the keys and values, respectively.
std::unordered_map<int, int> map;
for (int i = 0; i < keys.size(); i++) {
map.emplace(keys[i], values[i]);
}
Is there no built-in insert method or function for inserting pairs like the following?
map.insert(keys.begin(), keys.end(), values.begin(), values.end());
map.insert(keys, values);
Thanks
Note: Normally, I would be fine with iterating over the arrays to build the map but I have to do this several times.
| Yes, you can achieve the goal using STL std::transform with the help of std::inserter.
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main() {
std::array<int, 5> keys{1,2,3,4,5};
std::array<int, 5> values{10,20,30,40,50};
std::unordered_map<int, int> map;
transform(keys.begin(), keys.end(), values.begin(), inserter(map, map.end()), [](const int &a, const int &b) {return make_pair(a, b);});
for (const auto &[key, val] : map) {
cout << key << ":" << val << endl;
}
}
Output:
5:50
4:40
3:30
1:10
2:20
|
72,734,098 | 72,734,164 | libcpr not working properly when using it for HTTP request | I am using libcpr for http requests in Visual Studio 2019 IDE. I downloaded it using vcpkg from microsoft. The sample code below is from cpr github page https://github.com/libcpr/cpr#:~:text=%23include%20%3C,return%200%3B%0A%7D
#include <cpr/cpr.h>
int main(int argc, char** argv) {
cpr::Response r =
cpr::Get(cpr::Url{"https://api.github.com/repos/whoshuu/cpr/contributors"},
cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC},
cpr::Parameters{{"anon", "true"}, {"key", "value"}});
r.status_code; // 200
r.header["content-type"]; // application/json; charset=utf-8
r.text; // JSON text string
return 0;
}
This doesn't work! It is giving error "namespace "cpr" has no member "AuthMode". This problem is not with this only. There was some other stuff that gives similar error e.g. https://docs.libcpr.org/advanced-usage.html#https-options:~:text=cpr%3A%3ASslOptions%20sslOpts%20%3D%20cpr%3A%3ASsl(ssl%3A%3ACaBuffer%7B%22%2D%2D%2D%2D%2DBEGIN%20CERTIFICATE%2D%2D%2D%2D%2D%5B...%5D%22%7D)%3B%0Acpr%3A%3AResponse%20r%20%3D%20cpr%3A%3AGet(cpr%3A%3AUrl%7B%22https%3A//www.httpbin.org/get%22%7D%2C%20sslOpts)%3B in this case "CaBuffer" has same issue.
Any help would be appreciated!!
Thanks
| Looks to me like a versioning issue. AuthMode exists in the latest header file, but does not exist in the version 1.8 header file, which is presumably what you have.
So, either downgrade your code, or upgrade your installation.
Sample code from version 1.8 is here
|
72,734,253 | 72,734,310 | Why does this code report that -31 is greater than 6? | I have a function double max(int count, ...) in my program. This function should return the highest number, but it reports that -31 > 6. Where is my mistake? I'm trying to learn va_. How can I fix this?
double max(int count, ...)
{
double max = INT_MIN, test;
int i;
va_list values;
va_start(values, count);
for (i = 0; i < count; ++i)
{
test = va_arg(values, double);
if (test > max)
{
max = test;
}
}
va_end(values);
return max;
}
int main()
{
printf("%ld", max(5, 1, 6, -31, 23, 24));
return 0;
}
| You are invoking undefined behavior. You are not passing in double values to max(), you are passing in int values instead. int and double are different sizes in memory, and va_arg() can't read an int parameter as if it were a double, and vice versa. You need to match the types correctly.
In this example, change all of the doubles to ints, eg:
int max(int count, ...)
{
int max = INT_MIN, test;
va_list values;
va_start(values, count);
for(int i = 0; i < count; ++i)
{
test = va_arg(values, int);
if(test > max)
{
max = test;
}
}
va_end(values);
return max;
}
int main()
{
printf("%d", max(5,1,6,-31,23,24));
return 0;
}
Online Demo
Otherwise, change the ints to doubles instead, eg:
double max(int count, ...)
{
double max = -DBL_MAX, test;
va_list values;
va_start(values, count);
for(int i = 0; i < count; ++i)
{
test = va_arg(values, double);
if(test > max)
{
max = test;
}
}
va_end(values);
return max;
}
int main()
{
printf("%lf", max(5,1.0,6.0,-31.0,23.0,24.0));
return 0;
}
Online Demo
Either way, you might consider a slight change in logic in how you are handling the max value. You should initialize it to the 1st value that is passed in, eg:
<type> max(int count, ...)
{
if (count <= 0)
return <default value>;
va_list values;
va_start(values, count);
<type> max = va_arg(values, <type>), test;
for(int i = 1; i < count; ++i)
{
test = va_arg(values, <type>);
if (test > max)
{
max = test;
}
}
va_end(values);
return max;
}
Also, note that all of the above is the C way of handling things. But you also tagged your question as C++, and the C++ way to handle this would be to use a variadic template instead of ellipses (ie, no va_arg() needed), or else take a std::initializer_list or at least a pair of iterators so that you can then make use of the standard std::max_element() algorithm.
|
72,734,558 | 72,734,728 | is `auto ua = unsigned int {};` legit C++? | This code compiles with MSVC, but not with GCC or Clang.
auto a = int{};
auto ua = unsigned int {};
See demo on compiler explorer
I strongly suspect it might be legit C++, but that the mix between the ancient "C style / types with spaces" and the 50 differents ways of doing initialization in C++ make this a very hard job for compilers.
| According to the C++ 20 Standard (7.6.1.4 Explicit type conversion (functional notation)):
1 A simple-type-specifier (9.2.9.3) or typename-specifier (13.8) followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer. If the type is a placeholder for a deduced class type, it is replaced by the return type of the function selected by overload resolution for class template deduction (12.4.2.9) for the remainder of this subclause.
So you need to write
auto ua = unsigned {};
|
72,735,034 | 72,735,215 | Calling member function before object usage | A few days ago, I was asking about operator overloading to my Logger project. Now I have another problem which I'm not able to solve - probably due to my low experience.
First - my Logger object (which is designed as a Singleton object) should write to a file created in the same directory as the source code. Desired use looks this way:
logger << "log message text";
So I have created a singleton object logger, but I need to make some controls before the first logger use, e.g. if the file already exists, if it is empty, etc. All the member functions which provide that I've already created or I will.
What's the point? I need somehow to check all these things before the first and every use of the logger. And I want them to be made automatically, so the possible user won't have to do that manually.
So, let´s summarize... let's say I want to use it for the first time, so I put this line to my code:
logger << "Log something";
Before it will make the log itself, I need the Logger class to check if:
the log file already exists
if no, create one
if yes, find the end and continue on the next line.
| Where does your Logger open the file to begin with? Why aren't you doing these checks at the point where the file is being opened?
This sounds like something you should be handling in your Logger's constructor, for instance.
And, rather than defining a global logger object, consider defining a static method in your Logger class instead, eg:
class Logger {
private:
Logger() {
// perform checks here...
// open/create log file as needed...
}
public:
~Logger() {
// close log file...
}
static Logger& GetLogger() {
static Logger logger;
return logger;
}
// other methods/operators as needed...
};
...
Logger::GetLogger() << "Log something";
Then the Logger constructor won't run until the first time GetLogger() is called.
|
72,735,082 | 72,735,232 | Why does "if (char a = f())" compile whereas "if ((char a = f()))" does not? | #include <iostream>
char f()
{
return 0;
}
int main()
{
// Compiles
if (char a = f())
std::cout << a;
// Does not compile (causes a compilation error)
// if ((char a = f()))
// std::cout << a;
return 0;
}
One can declare a local variable and assign a value to it inside an if statement as such:
if (char a = f())
However, adding an additional pair of parentheses, leading to if ((char a = f())), causes the following compilation error:
error: expected primary-expression before ‘char’
Why is that? What is the difference between both? Why is the additional pair of parentheses not just considered redundant?
| To put it simply, C++ syntax allows the condition inside an if statement to be either an expression or a declaration.
So, char a = f() is a declaration (of the variable named a).
But (char a = f()) is not a declaration (and is also not an expression convertible to bool).
|
72,735,235 | 72,735,517 | c++ how to delete thread once it has been terminated | I'm working on a project that uses uses a thread to connect to a server. Whenever the login button is pressed, it initialized a thread to log in with the given IP and port provided by the user.
ServerPage.h
class ServerPage {
public:
static std::thread serverThread;
static void login();
}
ServerPage.cpp
#include "ServerPage.h"
std::thread ServerPage::serverThread;
void ServerPage::login() {
while (/*server is not connected*/) {
if (/*button is clicked and thread is not running*/)
serverThread = std::thread(Client::init, ip, port);
}
}
This works well until the button is clicked more than once. I'm able to use the Client class to see the status of the server (connected, not connected, or failure) Is there a way to delete or re initialize so that it can be run until the client is connected?
| First of all: threads cannot be restarted. There is no such concept in programming. Unless by "restart" you mean "kill and spawn again".
It is not possible to kill a thread in a cross-platform way. For posix (I don't know about other OS) you can use pthreads (instead of std::thread) and send kill signal to it and spawn it again. But this is a ninja way, not necessarily what you should do. For example if you kill a thread that currently holds a lock, you will end up in a deadlock. This method should be avoided. However, if you can't modify Client::init method, then there might be no other choice without weakening your requirements.
A better solution is to pass around "cancellation tokens": small objects that you can register cancel handlers on it. Then you implement Client::init to cancel itself (and do any necessary cleanup, like releasing locks) whenever cancellation is triggered. Which you trigger on click.
|
72,736,095 | 72,802,162 | Cannot compile when I include the Windows.Devices.Enumeration.h file | I have a Visual Studio 2017 C++17 MFC project on Windows 10 using Windows SDK 10.0.18362.0.
I need to add code to enumerate and connect to a Bluetooth LE device.
To start off, the first thing I need to do is to
#include <winrt/Windows.Devices.Enumeration.h>
The winrt/ header files are in
C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\cppwinrt\winrt
If I wanted to go with the ABI:: headers then I would
#include <Windows.Devices.Enumeration.h>
Those header files are in
C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\winrt
Here is the problem. If I comment out this include, I have no compile errors but if I add either one I get compile errors.
Regardless of which include I use I get a mountain of errors such as
Error C2059 syntax error: 'constant'
which points to DirectXMathVector.inl (a MS C++ Math Library) the line pointed to is
XMVECTOR A = XMVectorSelect(g_XMSelect1110.v, V, g_XMSelect1110.v);
Or, if I use the 2nd ABI include mentioned above I get a ton of compile errors such as
Error C2027 use of undefined type 'ABI::Windows::Foundation::Internal::GetAbiType'
which is in the windows.foundation.collections.h file and the line pointed to is
typedef typename Windows::Foundation::Internal::GetAbiType<T>::type _abi_type;
So what's the deal? How can VS2017 with C++2017 and a recent SDK not be able to compile MS's own files? Does this compile with VS2019? I don't have that to test.
TIA,
Ed
| As a follow up. The thing that I found that worked was a Project Properties setting. Properties > C/C++ > General node in the left pane. Set the Consume Windows Runtime Extension property to Yes
|
72,736,631 | 72,736,840 | Logical operations in OpenCV | Assume two Mat CV_8UC1 images, mask, and label, how to do the following operation in OpenCV (C++):
mask(label==5) = 255; // this is allowed in Matlab
// or
mask[label==5] = 255; // this is allowed in Python
| You could use inrange() with lowerb and upperb both set to 5,
or you could use compare() with src2 set to 5 and cmpop set to cv::CMP_EQ.
Both will set the output mask to be 255 where the values match.
|
72,736,764 | 72,738,542 | How to allow uiAccess in UWP application | I am invoking C++ UIautomation modules in my UWP application. The application is not able to extract control elements since it is not running in an elevated environment. How should I set up the manifest file or set my UWP app to be able to get access to ui elements of other applications.
| I'd suggest that you could put the UIautomation modules into a console app and then launch the console as elevated from your UWP app using desktop bridge. You will also need to add the allowElevation capability into the manifest file.
For detailed steps, you could take a look at Stefan wick's blog- App Elevation Samples.
|
72,737,039 | 72,737,215 | Why does Clang add extra FMA instructions? | #include <immintrin.h>
__m256 mult(__m256 num) {
return 278*num/(num+1400);
}
.LCPI0_0:
.long 0x438b0000 # float 278
.LCPI0_1:
.long 0x44af0000 # float 1400
mult(float __vector(8)): # @mult(float __vector(8))
vbroadcastss ymm1, dword ptr [rip + .LCPI0_0] # ymm1 = [2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2,2.78E+2]
vmulps ymm1, ymm0, ymm1
vbroadcastss ymm2, dword ptr [rip + .LCPI0_1] # ymm2 = [1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3,1.4E+3]
vaddps ymm0, ymm0, ymm2
vrcpps ymm2, ymm0
vmulps ymm3, ymm1, ymm2
vfmsub213ps ymm0, ymm3, ymm1 # ymm0 = (ymm3 * ymm0) - ymm1
vfnmadd213ps ymm0, ymm2, ymm3 # ymm0 = -(ymm2 * ymm0) + ymm3
ret
Why does Clang add the two extra FMA instructions to the code? The result should already be computed with vmulps ymm3, ymm1, ymm2. Don't the extra instructions increase the latency beyond just using vdivps like with -O3?
Godbolt
| The extra FMAs compensate for the reduced precision of vrcpps. ymm3 is an estimate of the result, but at about half the usual precision.
For simplicity let's say the division was q = a / b.
The first FMA, vfmsub213ps, computes the difference (a * b⁻¹) * b - a, which is an estimate of how much the division was "off" by (in the original scale, before dividing by b). The second FMA approximately divides that difference by b (by multiplying by b⁻¹) so it becomes a difference in the scale of the q, and subtracts it from q to bring it closer to a / b.
If you're OK with reduced precision, you could explicitly use _mm256_rcp_ps and multiply by that, then there will not be extra FMAs to compensate.
Don't the extra instructions increase the latency beyond just using vdivps
Yes, this 4-instruction sequence would take 16 cycles on Ice Lake, while vdivps would take 11 cycles. However, throughput is approximately doubled compared to vdivps. Depending on the context, latency or throughput could be more important .. more often it's throughput. Compilers aren't necessarily very good at deciding which is more important, though in this case I can't blame it (there is no context).
|
72,737,316 | 72,740,574 | Is std::move of shared_ptr thread safe? | The following snippet runs fine:
#include <memory>
#include <cassert>
int main()
{
auto ptr1 = std::make_shared<int>(10);
assert(ptr1.use_count() == 1);
auto ptr2 = std::move(ptr1);
assert(ptr1 == nullptr);
auto ptr3 = static_cast<std::shared_ptr<int>&&>(ptr2);
assert(ptr2 == nullptr);
assert(ptr3.use_count() == 1);
}
It looks std::move does several operations, one of them is reseting the moved shared pointer somehow, so is this thread safe? For instance if i have something like:
void ThreadLogic()
{
if (sharedPtr != nullptr)
{
DoSomething(std::move(sharedPtr));
}
else
{
DoSomethingElse();
}
}
Is that std::move(sharedPtr) atomic or should I protect the check (the critical section) there by some other means?
| You have a misconception about what std::move does. In fact std::move does nothing. It's just a compile time mechanism with the meaning: I no longer need this named value.
This then causes the compiler to use the value in different ways, like call a move constructor/assignment instead of copy constructor/assignment. But the std::move itself generates no code so nothing to be affected by threads.
The real question you should be asking is whether the move constructor of shared_ptr is thread safe and the answer is: No.
But the point of the shared_ptr is not to share the shared_ptr but to share what it points too. Do not pass a shared_ptr by reference to threads, instead pass it by value so each thread gets it own shared_ptr. Then it is free to move that around at will without problems.
The shared_ptr protects the lifetime of the thing it points to. The reference count the shared_ptr uses is thread safe but nothing else. It only manages the lifetime of the pointed to objects in a thread safe way so it doesn't get destroyed as long as any shared_ptr has hold of the object.
|
72,737,601 | 72,737,660 | Nothing execute when using Vector in C++ with VSCode | The problem
I have a problem with Vector in C++.
When I try to do basic things with them, my program "doesn't works" anymore.
What I tried
Searching on Stack Overflow but didn't find something relevant.
But I don't know a lot on this topic so I'm kind of stuck with it.
Some code:
Example:
#include <iostream>
#include <vector>
int main(int argc, char ** argv){
std::cout << "Hello world\n";
std::vector< int > arr;
}
This program will outputs "Hello world" because I don't interact with the vector.
But if I do:
#include <iostream>
#include <vector>
int main(int argc, char ** argv){
std::cout << "Hello world\n";
std::vector< int > arr;
arr.push_back(1);
}
for example, there is no STDOUT. Hello world is never "printed". And there are no errors.
I'm on Visual Studio code and I compile my program with
g++ -o progam -Wall main.cpp
When I run this on the "Terminal" of Visual Studio Code it doesn't works. But when I rut it on another shell it works.
| The command g++ -o -Wall main.cpp will create an executable file called -Wall. Unless that's the program you're trying to run, it's not going to work.
Instead you would need something like g++ -o program -Wall main.cpp and then run program. Both of your examples do the right thing in that case.
|
72,737,873 | 72,759,302 | Include and access multiple .so files and headers in one project using cmake | I have a simple foobar project which has a directory layout as follows:
.
├── CMakeLists.txt
└── src
├── CMakeLists.txt
├── Foo
│ ├── CMakeLists.txt
│ ├── foo.cpp
│ └── foo.h
└── Bar
├── CMakeLists.txt
├── bar.cpp
└── bar.h
Where Foo is standalone but Bar depends on Foo and should be able to #include <Foo/foo.h>.
My top level CMakeLists.txt file is:
# Specify cmake version
cmake_minimum_required(VERSION 3.10)
# Set the project name
project(foobar VERSION 0.1.0)
# Specify the C++ standard
set(CMAKE_CXX_COMPILER /usr/bin/g++)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -O3")
# Set location for .so files
set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}")
# Set location for executables
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
# Add libraries
add_subdirectory(src)
# Install library
install(TARGETS Foo Bar LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
my src level is:
add_subdirectory(Foo)
add_subdirectory(Bar)
my Foo level is:
add_library(Foo SHARED foo.cpp)
and finally my Bar level is:
add_library(Bar SHARED bar.cpp)
add_dependencies(Bar Foo)
target_link_libraries(Bar Foo)
Invoking cmake goes OK, but upon make I get the following:
Scanning dependencies of target Foo
[ 25%] Building CXX object src/Foo/CMakeFiles/Foo.dir/foo.cpp.o
[ 50%] Linking CXX shared library libFoo.so
[ 50%] Built target Foo
Scanning dependencies of target Bar
[ 75%] Building CXX object src/Bar/CMakeFiles/Bar.dir/bar.cpp.o
In file included from /home/drjrm3/code/cmake_app/src/Bar/bar.cpp:1:
/home/drjrm3/code/cmake_app/src/Bar/bar.h:3:10: fatal error: Foo/foo.h: No such file or directory
3 | #include <Foo/foo.h>
| ^~~~~~~~~~~
compilation terminated.
make[2]: *** [src/Bar/CMakeFiles/Bar.dir/build.make:63: src/Bar/CMakeFiles/Bar.dir/bar.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:160: src/Bar/CMakeFiles/Bar.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
which shows me that I am not properly making Foo visible to Bar in the way that I'm hoping to.
What needs to change so that these can each be built into isolated shared object libraries but Bar depends upon Foo and can <Foo/foo.h> can be visible from within that subcomponent?
Note that my choices for making these shared objects is because this is just a minimal example of a bigger project where I have multiple components and multiple apps but wanted to make a minimal example for this question. In fact I have this example up on Github is anyone is interested.
| The key concept here is property visibility. There are two types in CMake:
PRIVATE: the property affects the target being built.
INTERFACE: the property affects targets that link to this one directly, or transitively through target_link_libraries(... INTERFACE ...).
The PUBLIC visibility is simply a shorthand for both.
Therefore. the build for Bar should look like so:
add_library(Bar SHARED bar.cpp)
target_link_libraries(Bar PUBLIC Foo)
We use PUBLIC visibility here because Bar's headers include Foo's headers. That is, libraries linking to Bar need to know about Foo as well.
Now we build Foo like so:
add_library(Foo SHARED foo.cpp)
target_include_directories(Foo PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>")
The main bit of magic here is the $<BUILD_INTERFACE:...> generator expression. This prevents the include directory (which is an absolute path to somewhere on your build machine) from being exported when you eventually use install(EXPORT) to create a find_package-compatible CMake package for these libraries.
Otherwise, we're just relying on the fact that ${CMAKE_CURRENT_SOURCE_DIR}/.. will be propagated from Foo to Bar (and anything that links to Bar) because this path is in the INTERFACE of Foo.
|
72,737,998 | 72,738,038 | Int and Float arrays give wrong results after adding numbers using loops | Doing some simple exercies with C++ and I'm stuck...
When my sum[t] array is declared as integer or float it sometimes outputs at the end some crazy values like for example 4239023 or -3.17802e+30 (despite the fact that I add only small numbers from range <-100; 300>). When I change it for double it works correctly. Why int and float don't work here?
#include <iostream>
using namespace std;
int main()
{
int t=0;
int n=0;
int x=0;
cout<<"Amount of sums: ";
cin>>t;
int sum[t];
for (int i=0; i<t; i++)
{
cout<<"Sum no. "<<i+1<<". How many numbers you wish to add: ";
cin>>n;
for (int j=0; j<n; j++)
{
cout<<"Insert number "<<j+1<<" : ";
cin>>x;
sum[i]+=x;
}
}
for (int i=0; i<t; i++)
{
cout<<sum[i]<<endl;
}
return 0;
}
| You should initialize your array of sums to zeroes after you receive the value of t. You could do it like this:
for (int i=0; i<t; i++)
{
sum[i] = 0;
}
|
72,738,434 | 72,741,371 | How to develop ue4 plugins to simulate the viewpoint in unity 3D? | Unity 3d has two viewpoints, one is game and another isscene. when you move objects in scene you can see changes happened in game in the same time. while the reverse is true. But UE4 doesn't have this function. So I wonder if I can develop a plugin for UE4 to achieve that? does anyone have a clue?
enter image description here
| Unreal 4: Go to Window -> Viewport 2. Drag the window somewhere and you will have 2 viewports:
Press play, only one viewport will display the "gameview" and the other remains as "sceneview" - Moving stuff in the 2nd Viewport will not update the game!
But I found this plugin:
https://github.com/jackknobel/GameViewportSync
You can see if that works for you or use it as a reference to get started developing your own plugin.
|
72,738,517 | 72,738,787 | List initialization rules | I want to initialize std::vector<char> with count and value.
This works:
int n = 100;
std::vector<char> v(n, 0);
However, list initialization std::vector<char> v{n, char(0)}; gives me:
warning: narrowing conversion of ‘n’ from ‘int’ to ‘char’.
Is there a way to use list initialization syntax but avoid initializer_list constructor called?
| Unfortunately, no.
When you're to list-initialize a std::vector, it'll first try to use the constructor with the std::initializer_list parameter. Other constructors will be considered only if there's no suitable match.
Quoted from cppref
All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list
If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).
In your case, since type conversion between char and int is allowed, the constructor with std::initializer_list is used.
My suggestion for initialization a std::vector(and other containers) is don't use list-initialization unless you're initialized with a std::initializer_list and use copy-list-initialization only.
struct A {};
std::vector<A> v1{100}; // ok, the size of v1 is 100
std::vector<A> v2(100); // better, the size of v2 is 100
std::vector<A> v3 = {100}; // compiles error
|
72,738,654 | 72,738,723 | C++ issue with conversion of std::string to std::wstring - Windows vs Linux | I'm trying to convert the string "pokémon" from std::string to std::wstring using
std::wstring wsTmp(str.begin(), str.end());
This works on Windows, but on Linux it returns "pok\xffffffc3\xffffffa9mon"
How can I make it work on Linux?
| This worked for me on POSIX.
#include <codecvt>
#include <string>
#include <locale>
int main() {
std::string a = "pokémon";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cv;
std::wstring wide = cv.from_bytes(a);
return 0;
}
The wstring holds the correct string at the end.
Important note by @NathanOliver: std::codecvt_utf8_utf16 was deprecated in C++17 and may be removed from the standard in a future version.
|
72,738,824 | 72,738,993 | Error trying to remove duplicate element from sorted Linked List | Why is my code giving a segmentation fault?
The code runs perfectly for some test cases, but after a few it starts giving a segmentation fault
Node *remove(Node *curr){
Node *temp=curr;
while(curr->data==curr->next->data){
curr=curr->next;
}
temp->next=curr->next;
delete(curr);
return temp->next;
}
//Function to remove duplicates from sorted linked list.
Node *removeDuplicates(Node *head)
{
// your code goes here
Node *curr=head;
while(curr->next!=NULL){
if(curr->data == curr->next->data){
curr=remove(curr);
}
else{
curr=curr->next;
}
}
return head;
}
| You seem to be crossing purpose with these functions, and you're note retaining your proper target for your potentially updated duplicate consolidation.
I'm gonna change the name to removeNode for several reasons, one of which is to avoid confusing it with std::remove that wouldn't be a problem if you hadn't inadvisably pulled the entire std namespace into play) The function should delete a (singular) node and return the node after (if there is one). It isn't a particularly helpful function to be honest, since all it should do is this:
Node *removeNode(Node *curr)
{
if (curr)
{
Node *tmp = curr;
curr = curr->next;
delete tmp;
}
return curr;
}
Pretty boring, but it gets the job done. Now, we can use that to remove duplicates by way of an efficient pointer-to-pointer approach:
Node *removeDuplicates(Node *head)
{
Node **pp = &head;
while (*pp && (*pp)->next)
{
if ((*pp)->data == (*pp)->next->data)
{
*pp = removeNode(*pp);
}
else
{
pp = &(*pp)->next;
}
}
return head;
}
And that's it. A test jig that exhibits how this works is below:
#include <iostream>
#include <random>
struct Node
{
int data;
Node *next;
};
void print(const Node *p, std::ostream& outp = std::cout)
{
if (p)
{
for (; p; p=p->next)
{
outp << p->data << ' ';
}
outp << '\n';
}
}
Node *insertSorted(Node *head, int value)
{
Node **pp = &head;
while (*pp && (*pp)->data < value)
pp = &(*pp)->next;
Node *p = new Node;
p->data = value;
p->next = *pp;
*pp = p;
return head;
}
Node *removeNode(Node *curr)
{
if (curr)
{
Node *tmp = curr;
curr = curr->next;
delete tmp;
}
return curr;
}
Node *removeDuplicates(Node *head)
{
Node **pp = &head;
while (*pp && (*pp)->next)
{
if ((*pp)->data == (*pp)->next->data)
{
*pp = removeNode(*pp);
}
else
{
pp = &(*pp)->next;
}
}
return head;
}
void removeAll(Node *head)
{
while (head)
{
Node *tmp = head;
head = head->next;
delete tmp;
}
}
int main()
{
std::mt19937 rng{ std::random_device{}() };
std::uniform_int_distribution<> dist(1,50);
Node *head = nullptr;
for (int i=0; i<30; ++i)
head = insertSorted(head, dist(rng));
print(head);
head = removeDuplicates(head);
print(head);
removeAll(head);
}
Output (varies)
2 4 4 4 6 7 7 8 18 18 19 23 26 27 29 31 32 33 34 34 36 36 37 37 38 40 43 44 46 49
2 4 6 7 8 18 19 23 26 27 29 31 32 33 34 36 37 38 40 43 44 46 49
|
72,738,831 | 72,739,386 | how to change editcontrol with function? | hello guys I was plc programmer just trying to start C++ programmer
I am trying to convert to this code to function
m_file.Open(posText[7], CStdioFile::modeRead);
m_file.ReadString(posValue[7]);
UpdateData(TRUE);
dlg.s_PostionZ2 = posValue[7];
UpdateData(FALSE);
m_file.Close();
and this my function but it didn't work
void mainDial::opeFile(CString path, CString value, CString location)
{
slaveDialog dlg;
m_file.Open(path, CStdioFile::modeRead);
m_file.ReadString(value);
AfxMessageBox(location);
UpdateData(TRUE);
location = value;
UpdateData(FALSE);
m_file.Close();
}
what I am trying to do is just open a file and save to value and change location value
the problem is the location is in the other dialog (SlaveDialog dlg;)
it is ok by just simply enter dlg.S_position
but if I want it to do with using a function to pass the location like this
opeFile(posText[0], posValue[0], _T("dlg.s_PostionX1"));
or
opeFile(posText[0], posValue[0], dlg.s_PostionX1);
it didn't work both way so how can I change to my function work
thank you for reading
|
what I am trying to do is just open a file and save to value and change location value
You are passing in the function's output parameters by value, so they make copies of the caller's values. Any changes the function makes to the parameters is done to the copies and not reflected back to the caller.
To do what you want, you need to pass in the output parameters by reference instead, eg:
void mainDial::opeFile(CString path, CString& value, CString& location)
|
72,740,042 | 72,743,941 | exception error in vio_ssl_write(Vio*, const uchar*, size_t) in openssl | I have a decryption method which decrypts data using private key:
auto decrypt_private(const unsigned char* data,size_t data_len,
unsigned char* decrypted_data)-> int
{
std::string pr_key_name="mykey.pem";
std::string keypass = "pass";
char * keypass_byte= const_cast<char*>( keypass.c_str() );
//open the private key file
FILE *fp = fopen(pr_key_name.c_str(), "r");
RSA *rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, keypass_byte);
if(rsa==NULL)
ERR_print_errors_fp(stderr);
fclose(fp);
int rsa_outlen = RSA_private_decrypt(data_len, data, decrypted_data,rsa,
RSA_PKCS1_PADDING);
RSA_free(rsa);
return rsa_outlen;
}
In main I have:
int main(){
std::string encrypted_data;
// encrypted data is in hex encoding
cin>>encrypted_data;
// I know the exact length of decrypted data
unsigned char* decrypted_data = new unsigned char[DATA_SIZE];
unsigned char* encrypted_data_byte= new unsigned char[encrypted_data.length()/2];
int decrypted_data_size= decrypt_private(encrypted_data_byte,
encrypted_data.length()/2, decrypted_data);
// catch error if decryption faild
if(decrypted_data_size==-1){
delete[] decrypted_data;
delete[] encrypted_data_byte;
std::cout<<"decryption faild";
return 1;
}
delete[] decrypted_data;
delete[] encrypted_data_byte;
return 0;
}
but as I add the if condition and the result of the decryption method is -1 I get error from viossl.cc :
../vio/viossl.cc:315: size_t vio_ssl_write(Vio*, const uchar*, size_t): Assertion `ERR_peek_error() == 0' failed.
and throw an exception and the program crashes. Does any body knows the reason? By the way I also removed the if condition and again I get the same error.
| Adding ERR_clear_error() solved the problem:
if(decrypted_data_size==-1){
ERR_clear_error();
delete[] decrypted_data;
delete[] encrypted_data_byte;
std::cout<<"decryption faild";
return 1;
}
|
72,740,077 | 72,740,250 | How to store text in wchar_t pointer parameter | I want to dll export some functions from cpp to dart and in order to do this I need to create a function with a pointer parameter where I will send text.
But after many searches I found no solution that works.
My question is: How to create a function with a wchar_t* parameter, and fill that variable with text? I have no knowledge of cpp pointers, I usually dont code in cpp.
Here is my code, it gives errors:
//extern "C" __declspec(dllexport)
void getAudioDevices(wchar_t* output, int outSize)
{
std::vector<DeviceProps> result = EnumAudioDevices(eRender);
std::wstring listOutput(L"");
if (!result.empty())
{
for (const auto& device : result)
{
std::wstring info(L"");
info += device.name; //PCWSTR
info += L"\n";
info += device.iconInfo; //PCWSTR
info += L"\n";
info += device.id; //LPWSTR
info += L"\n";
info += device.isActive ? L"true" : L"false";
info += L"\n[][][][]\n";
listOutput += info.c_str();
}
}
wcscpy_s(output, outSize, listOutput.c_str());
}
int wmain(int argc, WCHAR* argv[])
{
WCHAR output[1000];
getAudioDevices(output, sizeof(output));
cout << output << endl;
}
| sizeof(output) will return the number of bytes the array is. On Windows this will be 2000 instead of 1000 since each wchar_t is 2 bytes long.
But the the value passed to the wcscpy_s is the number of wide characters that your array can hold. Your array can hold 1000 wchar_t's. But your are actually telling wcscpy_s that it can hold more than that.
Change this:
getAudioDevices(output, sizeof(output));
To this:
getAudioDevices(output, sizeof(output)/sizeof(output[0]) );
Declare outSize to be of type size_t as well instead of int
|
72,740,619 | 72,740,837 | gcc problem with std::optional and packed struct member | I need to use a packed struct for parsing incoming data. I also have an std::optional value that I want to assign the value of one of the struct members. However, it fails. I think I understand the problem, basically making a reference to a variable that is not aligned with the memory width can be a bad thing.
The code example compiles with clang 14, but not with gcc 12. Is it a bug or a "feature"?
#include <cstdint>
#include <optional>
struct Data {
uint8_t a{};
uint32_t b{};
} __attribute__((packed));
int main() {
Data t;
std::optional<uint32_t> val{};
val = t.b; // <<< this failes
val = (decltype(t.b)) t.b;
}
clang: https://godbolt.org/z/eWfaqb3a3
gcc: https://godbolt.org/z/or1W5MbdG
I know of the general problems with packed structs. As my target is an embedded device with a x86-64 and the data being parsed comes from an industrial standard bus, I believe I'm safe from that.
| This is a problem of how clang and gcc assume the ARM cpu is configured.
ARM cpus have a bit that says whether unaligned access should cause a processor trap or be handled by the cpu using slower access methods transparently. Clang defaults to the CPU allowing unaligned access while gcc defaults to the cpu trapping unaligned access.
So for clang it is perfectly fine to create a int& for the unaligned t.b because the CPU will handle the unaligned access that might cause transparently.
For gcc on the other hand creating an int& from t.b risk code accessing it and causing a trap. The contract for functions taking an int& says the int must be aligned. So the compiler fails because the contract can't be satisfied.
But if you write (decltype(t.b)) t.b; you create a copy of t.b to be used which then avoids the unaligned problem because the compiler knows how to copy an unaligned uint32_t.
You can specify compiler flags to change the default assumption about unaligned access. Allowing it for gcc should make the code compile but assumes your ARM cpu will be configure to allow said unaligned access.
|
72,740,626 | 72,741,155 | 64 bit equivalent of "GetModuleHandleA" need | I need to extent the compatibility of my application to 64 bit exe.
__int64 GetGameFunctionAddress(std::string GameFileExe, std::string Address)
{
// Get integer value address of the original function hook
#if defined(_WIN64)
/// code to emulate GetModuleHandleA on 64 executible
#else
return (__int64)GetModuleHandleA(GameFileExe.c_str()) + std::strtoul(Address.c_str(), NULL, 16);
#end if
}
this function get Address to pass to IDA for hook a function of a game.
I call this function with this line:
Output.MainFunctHookAddressInt = GetGameFunctionAddress(Output.ExeFile, GameInfo.MainFunctHookAddressInt);
AddressOfHookSoundFunction = Output.MainFunctHookAddressInt;
and in a second time I pass it to detours:
DetourAttach(&(LPVOID&)AddressOfHookSoundFunction, HookMainFunction);
Unfortunately "GetModuleHandleA" work only on 32 bit games, but I need to extend the compatibility to 64 bit games too.
So I need to fix my 'GetGameFunctionAddress' function to add 64 bit compatibility.
Can you help me please ?
Update:
One user tell me:
According to this GetModuleHandleA does not work to get the base address if the process is 64bit.
Why does getting the base address using GetModuleHandle work?
| GetModuleHandleW returns a value of type HMODULE (which is the same as HINSTANCE, aka HANDLE, aka PVOID, aka void*). In other words: It returns a pointer sized value.
Pointer sized values are 32 bits wide in 32-bit processes, and 64 bits wide in 64-bit processes. Either way you get the address of the module base address, irrespective of the bitness of the process.
Now obviously, since you are interacting with filesystem objects that aren't under your control, you do not want to call the ANSI version of the API (GetModuleHandleA) but the Unicode version: GetModuleHandleW. And while you're doing pretty low-level stuff here, you probably don't want to use types from the C++ Standard Library either (if you insist, use std::wstring/std::wstring_view).
|
72,740,880 | 72,741,020 | How to copy all the shared conan libraries into the build folder? | I have custom conan packages that output c++ shared libraries. (dylib or dll)
Whenever I build my CMake project I would like all these shared libraries to be copied to the directory where the executable is.
How can I achieve this?
| You need to use the imports method of a conanfile.txt or conanfile.py that you use in your CMake project.
Here the documentation: https://docs.conan.io/en/latest/reference/conanfile/methods.html#imports
With aconanfile.py it look like this
def imports(self):
self.copy("*.dll", "", "bin")
self.copy("*.dylib", "", "lib")
and with a conanfile.txt (https://docs.conan.io/en/latest/reference/conanfile_txt.html?highlight=imports#imports)
[imports]
bin, *.dll -> ./bin # Copies all dll files from packages bin folder to my local "bin" folder
lib, *.dylib* -> ./bin # Copies all dylib files from packages lib folder to my local "bin" folder
With that you should be able to have your binaries inside your build folder.
After that you only need to use the file function in CMake to copy your lib where you want to. Documenation for file function
You will certainly use something like this
file(COPY_FILE ${CMAKE_BINARY_DIR}/bin/lib.dll <path_to_exe>)
|
72,741,650 | 72,741,931 | C++ Errors C2672 and C2893 when I use mutex in C++ | When I use mutual parameter,'some mutex',in demo of shared data in multi-threading of C++,the two errors occur,and their codes are
C2672:
'invoke': no matching overloaded function found shared_data
C2893:
Failed to specialize function template 'unknown-type std::invoke(_Callable &&) noexcept(<expr>)'
Then I looked the error codes in Microsoft VS Doc,it reads:"To fix this issue, make the template parameter member accessible where it is evaluated.",So what does the sentence mean?Finally,I guess there must be some wrong with the function invoke .
Here's the code:
#include <list>
#include <mutex>
#include <algorithm>
#include<thread>
std::list<int> some_list;
std::mutex some_mutex;
void add_to_list(int new_value)
{
std::lock_guard<std::mutex> guard(some_mutex);
some_list.push_back(new_value);
}
bool list_contains(int value_to_find)
{
std::lock_guard<std::mutex> guard(some_mutex);
return std::find(some_list.begin(), some_list.end(), value_to_find) != some_list.end();
}
int main() {
using std::thread;
thread t1(add_to_list);
thread t2(list_contains);
t1.join();
t2.join();
return 0;
}
So confused that I want to ask for help.
| My comment written out as a program :
#include <cassert>
#include <list>
#include <mutex>
#include <algorithm>
#include <future>
// avoid global variable, group related functions in a class
//std::list<int> some_list;
//std::mutex some_mutex;
class my_async_list final
{
public:
void add(const int new_value) // new_value should not change so const
{
// scoped_lock instead of lock_guard https://stackoverflow.com/questions/43019598/stdlock-guard-or-stdscoped-lock
std::scoped_lock<std::mutex> lock{ m_mtx };
m_list.push_back(new_value);
}
bool contains(int value_to_find) const // contains should not change datastructure so it is a const function
{
std::scoped_lock<std::mutex> lock{ m_mtx };
return std::find(m_list.begin(), m_list.end(), value_to_find) != m_list.end();
}
private:
mutable std::mutex m_mtx; // so it can be used in const functions
std::list<int> m_list;
};
int main()
{
my_async_list my_list;
// use lambda functions to launch async function call
auto add_future = std::async(std::launch::async, [&my_list]
{
my_list.add(1);
});
auto contains_future = std::async(std::launch::async, [&my_list]
{
return my_list.contains(1);
});
add_future.get(); // wait until add is done.
bool contains_one = contains_future.get();
assert(contains_one);
return 0;
}
|
72,741,750 | 72,741,811 | Why is shared_ptr returning an empty list? | I am working with Xerces-c (version 3.2) and I have this function that wraps around the XMLString::transcode method.
XMLCh* class_name::transcode(const std::string text) {
auto returned = std::shared_ptr<XMLCh>(XMLString::transcode(text.c_str()), class_name::releaseXMLCh);
return returned.get();
}
(XMLCh is a char16_t)
The point of this is to have a shared pointer that will call releaseXMLCh() when it is no longer needed. Here is the implementation of releaseXMLCh():
void class_name::releaseXMLCh(XMLCh* text) {
XMLString::release(&text);
}
According to the Xerces-c documentation, XMLString::release needs to be called after calling XMLString::transcode to avoid a memory leak.
However, this function only ever returns "", regardless of what the input string is. I suspect that I am doing something wrong with the shared_ptr, as calling XML::transcode on its own works perfectly fine.
Does anyone know why this is happening?
| Think about it:
you create a local std::shared_ptr.
You get the (raw) pointer to the internal object.
The local std::shared_ptr goes out of scope and is destructed.
How many std::shared_ptrs will there be pointing to the internal object?
None. So it's also destructed. Thus, this will not work this way.
You are returning a pointer to a destroyed object, which causes Undefined Behavior.
You need a persisting smart pointer object (could likely even be a unique_ptr) or just use the old-fashioned new-delete.
|
72,741,755 | 72,742,071 | insert element at bottom of stack | I am doing the Insert at Bottom of the stack question.
This code is perfectly working in the CodeStudio but it is not giving the correct expected output in Visual studio code. why it is not displaying all the elements of the stack
# include <iostream>
# include <stack>
# include <vector>
# include <string>
using namespace std;
void Helper(stack<int>& myStack, int x){
if(myStack.empty()){
myStack.push(x);
return ;
}
int temp=myStack.top();
myStack.pop();
Helper(myStack, x);
myStack.push(temp);
}
stack<int> pushAtBottom(stack<int>& myStack, int x)
{
Helper(myStack,x);
return myStack;
}
int main(){
stack<int> s,ans;
int n,a;
cout<<"How many element : ";
cin>>n;
for(int i=0; i<n; i++){
cin>>a;
s.push(a);
}
cout<<"New element : ";
cin>>a;
ans=pushAtBottom(s,a);
cout<<"After inserting : ";
for(int i=0; i<ans.size(); i++){
cout<<ans.top()<<" ";
ans.pop();
}
cout<<endl;
return 0;
}
Input
6
1 2 3 4 5
Expected Output
5 4 3 2 1 6
Output
After inserting : 5 4 3
| The problem is how you print the elements:
for(int i=0; i<ans.size(); i++){
cout<<ans.top()<<" ";
ans.pop();
}
Due to calling ans.pop() ans.size() will decrease by one every iteration. At the same time i will increase by one every iteration. Basically you iterate twice as fast as intended.
A better loop would be this:
while(ans.size() > 0) {
cout << ans.top() << " ";
ans.pop();
}
|
72,742,121 | 72,742,394 | Why is the return value incorrect with optimisation flags on? | I am (for myself only) practicing c++ and trying to "re-code" c# properties into it.
I do know it is useless (I mean, I will not use it) however, I just wanted to try to see if this was possible.
For some reasons, with the following code, under the latest clang / gcc version, it does not yeld the correct result under every single optimisation flags other than -O0 (which disables optimisation as far as I am aware of.)
#include <functional>
#include <iostream>
template<typename T>
class Property
{
private:
using getType = std::function<const T&(void)>;
using setType = std::function<void(const T&)>;
T internal;
getType get;
setType set;
public:
Property(const T &value) : internal{value}, get{[this] () { return internal; }}, set{[this](const T& value) { internal = value; }} {}
Property(getType fnc) : get(fnc) { }
Property(getType fncGet, setType fncSet) : get(fncGet), set(fncSet) { }
Property(setType fnc) : set(fnc) { }
Property(setType fncSet, getType fncGet) : get(fncGet), set(fncSet) { }
Property<T> &operator=(T& value) { set(value); return *this; }
operator const T&() const { return get(); }
};
int main(void)
{
Property<int> hey(12);
std::cout << hey << std::endl;
return hey;
}
It seems to behave correctly under visual studio compiler but i'm unsure.
Have I missed a part of the standard? Is my code incorrect? is there a bug in clang / gcc / the STL?
I placed my code on the website called Godbolt to switch easily between compilers and I had the same incoherent results.
Here is what it prints me for c++14 / clang 14:
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
624203080
The last number changes between runs, but not the first one making me think it just takes uninitialized data.
| Your problem is this part: using getType = std::function<const T&(void)>; in combination with get{[this] () { return internal; }}.
The lambda does not return the internal as a reference here, so a copy of internal is returned, and - here I don't know how std::function is implemented - std::function has to hold a copy of internal but returns it as a reference to that copy which is than dangling.
Changing it to get{[this] () -> T& { return internal; }} seems to solve the problem.
|
72,742,159 | 72,773,062 | BGFX shader compilation using shaderc | I'm trying to compile the following shader from this tutorial:
$input a_position, a_color0
$output v_color0
#include <bgfx_shader.sh>
void main()
{
gl_Position = mul(u_modelViewProj, vec4(a_position, 1.0) );
v_color0 = a_color0;
}
I am working on windows so I modified the command from the tutorial to target the windows platform:
"../../bgfx/.build/win64_vs2017/bin/shadercDebug.exe" -f v_simple.sc -o v_simple.bin --platform windows --type vertex --verbose -i "../../bgfx/src"
This fails to compile and I get the following output:
C:\Users\REDACTED\VisualStudioCode\bgfxTutorial\src\shaders>"../../bgfx/.build/win64_vs2017/bin/shadercDebug.exe" -f v_simple.sc -o v_simple.bin --platform windows --type vertex --verbose -i "../../bgfx/src"
Code:
---
76: uniform mat4 u_proj;
77: uniform mat4 u_invProj;
78: uniform mat4 u_viewProj;
79: uniform mat4 u_invViewProj;
80: uniform mat4 u_model[32];
81: uniform mat4 u_modelView;
82: uniform mat4 u_modelViewProj;
83: uniform vec4 u_alphaRef4;
84: void main()
85: {
>>> 86: gl_Position = ( (u_modelViewProj) * (vec4(a_position, 1.0) ) );
>>> 43: ^
87: v_color0 = a_color0;
88: }
---
Error: (86,43): error: `a_position' undeclared
(86,38): error: cannot construct `vec4' from a non-numeric data type
(86,17): error: operands to arithmetic operators must be numeric
(87,1): error: `v_color0' undeclared
(87,1): error: value of type vec4 cannot be assigned to variable of type error
Failed to build shader.
I have the varying.def.sc file which would be necessary to compile:
// outputs
vec4 v_color0 : COLOR0;
// inputs
vec3 a_position : POSITION;
vec4 a_color0 : COLOR0;
I've also tried to use the makefile from the tutorials:
BGFX_DIR=../../bgfx
include $(BGFX_DIR)/scripts/shader.mk
(I've modifieds it to point to my bgfx dir)
When I try to run it, it results in empty directories regardless of the supplied TARGET
variable.
| Comments in varying.def.sc aren't parsed by shaderc correctly, you'll unfortunately have to remove them.
|
72,742,207 | 72,745,933 | insert dtype in std::map | I want to do a map that takes a pair of pybind11::dtype and int and maps it into an OpenCV format:
static std::map<std::pair<pybind11::dtype, int>, int> ocv_types;
So I inserted all combinations but there seems to be a problem when adding int32_t and float_t:
ocv_types.insert(std::make_pair(std::make_pair(pybind11::dtype::of<std::int32_t>() , 3), CV_32SC3));
ocv_types.insert(std::make_pair(std::make_pair(pybind11::dtype::of<std::float_t>() , 3), CV_32FC3));
When I do this, only the CV_32SC3 is really inserted , my guess that somewhere the program "thinks" that both elements are equal and therefore is not going to insert the second one.
How can I actually add these 2?
P.S. I did this check just to "prove" that the types are not equal:
if(pybind11::dtype::of<std::int32_t>() == pybind11::dtype::of<std::float_t>())
{
std::cout << "std::int32_t == std::float_t" << std::endl;
}
else
{
std::cout << "std::int32_t != std::float_t" << std::endl;
}
... And of course they are not.
EDIT
I added the < function for dtype and used it in the compare function for the map, but not all elements are present in the map:
int getVal(pybind11::dtype type)
{
if(type.is(pybind11::dtype::of<std::uint8_t>()))
return 1;
if(type.is(pybind11::dtype::of<std::uint16_t>()))
return 2;
if(type.is(pybind11::dtype::of<std::int16_t>()))
return 3;
if(type.is(pybind11::dtype::of<std::int32_t>()))
return 4;
if(type.is(pybind11::dtype::of<std::float_t>()))
return 5;
if(type.is(pybind11::dtype::of<std::double_t>()))
return 6;
}
inline bool operator <(const pybind11::dtype a, const pybind11::dtype b) //friend claim has to be here
{
return getVal(a) < getVal(b);
}
auto comp = [](const std::pair<pybind11::dtype, int> a, const std::pair<pybind11::dtype, int> b)
{
return a < b;
};
static std::map<std::pair<pybind11::dtype, int>, int, decltype(comp)> ocv_types(comp);
| As you noted pybind11::dtype do not have any particular order.
So IMO best approach is to use std::unordered_map and provide respective hashes. pybind11 already has some hash function, so it is needed to adopt it for std::hash.
Here is test I've wrote (using Catch2) and it passes on my machine:
main.cpp:
#include "catch2/catch_all.hpp"
#include <pybind11/embed.h>
#include <pybind11/numpy.h>
#include <unordered_map>
template<>
struct std::hash<pybind11::dtype>
{
size_t operator()(const pybind11::dtype &t) const
{
return pybind11::hash(t);
}
};
template<>
struct std::hash<std::pair<pybind11::dtype, int>>
{
size_t operator()(const std::pair<pybind11::dtype, int> &t) const
{
return std::hash<pybind11::dtype>{}(t.first) ^ static_cast<size_t>(t.second);
}
};
TEST_CASE("map_with_dtype") {
constexpr auto CV_32SC3 = 1;
constexpr auto CV_32FC3 = 2;
pybind11::scoped_interpreter guard{};
std::unordered_map<std::pair<pybind11::dtype, int>, int> ocv_types;
REQUIRE(ocv_types.empty());
auto a = ocv_types.insert(std::make_pair(std::make_pair(pybind11::dtype::of<std::int32_t>() , 3), CV_32SC3));
REQUIRE(a.second);
auto b = ocv_types.insert(std::make_pair(std::make_pair(pybind11::dtype::of<std::float_t>() , 3), CV_32FC3));
REQUIRE(b.second);
CHECK(b.first->second == CV_32FC3);
CHECK(ocv_types.size() == 2);
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16)
# set the project name
project(MapOfPyBind11)
find_package(Catch2 REQUIRED)
find_package(pybind11 REQUIRED)
# add the executable
add_executable(MapOfPyBind11Test main.cpp)
target_link_libraries(MapOfPyBind11Test PRIVATE Catch2::Catch2 pybind11::module pybind11::embed)
include(CTest)
include(Catch)
catch_discover_tests(MapOfPyBind11Test)
|
72,742,242 | 72,756,878 | How does atomic seq_cst memory order actually work? | For example, there are shared variables.
int val;
Cls obj;
An atomic bool variable acts as a data indicator.
std::atomic_bool flag = false;
Thread 1 only set these variables.
while (flag == true) { /* Sleep */ }
val = ...;
obj = ...;
flag = true; /* Set flag to true after setting shared variables. */
Thread 2 only get these variables.
while (flag != true) { /* Sleep */ }
int local_val = val;
Cls local_obj = obj;
flag = false; /* Set flag to false after using shared variables. */
My questions are:
For std::memory_order_seq_cst, which is default for std::atomic_bool, is it safe to set or get shared variables after while (...) {}?
Using bool instead of std::atomic_bool is correct or not?
|
Yes, the code is fine, and as ALX23z says, it would still be fine if all the loads of flag were std::memory_order_acquire and all the stores were std::memory_order_release. The extra semantics that std::memory_order_seq_cst provides are only relevant to observing the ordering between loads and stores to two or more different atomic variables. When your whole program only has one atomic variable, it has no useful effect.
Roughly, the idea is that acquire/release suffice to ensure that the accesses to your non-atomic variables really do happen in between the load/store of the atomic flag, and do not "leak out". More formally, you could use the C++11 memory model axioms to prove that given any read of the objects in thread 1, and any write of the objects in thread 2, one of them happens before the other. The details are a little tedious, but the key idea is that an acquire load and a release store is exactly what you need to get synchronization, which is how you get a happens-before relation between operations in two different threads.
No, if you replace the atomic_bool with a plain bool then your code has undefined behavior. You would then be reading and writing all your variables in different threads, with no mutexes or atomic variables that could possibly create synchronization, and that is the definition of a data race.
|
72,744,346 | 72,744,451 | Are 'const foo**' and 'foo** const' the same thing? | I know that for a type foo, the function declaration for bar
void bar(const foo*) and void bar(foo* const)
are the same thing. But that about double indirection? That is, are
void bar(const foo**) and void bar(foo** const)
also the same thing? If not, then what do I need to do to void bar(foo** const) to put the const first?
| Case 1
Here we consider
void bar(const foo*); #1
void bar(foo* const) #2
In #1 we've a pointer to a const foo while in #2 we've a const pointer to a nonconst foo.
You could use std::is_same to confirm that they're different:
std::cout << std::is_same<const foo*, foo* const>::value << ' '; //false
Case 2
Here we consider
void bar(const foo**); #3
void bar(foo** const); #4
In #3 we've a pointer to a pointer to a const foo while in #4 we've a const pointer to a nonconst pointer to a nonconst foo.
std::cout << std::is_same<const foo**, foo** const>::value << ' '; //false
Moreover, note that const foo * is the same as foo const * but this case you don't have in your given examples.
std::cout << std::is_same<const foo *, foo const *>::value << ' '; //true
|
72,744,558 | 72,744,957 | c++11 promise object gets invalid, but its future object neither returns value nor throw exception | I've got this test code to see, if a promise object is out of lifecycle, what happen to its future object:
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
using namespace std;
void getValue(future<int>& future) {
cout << "sub process 1 \n";
try {
cout << "sub process 2 \n";
int value = future.get();
cout << "sub process 3\n";
cout << value << endl;
} catch (future_error &e) {
cerr << e.code() << '\n' << e.what() << endl;
} catch (exception e) {
cerr << e.what() << endl;
}
cout << "sub process 4\n";
}
int main() {
thread t;
{
promise<int> plocal;
future<int> flocal = plocal.get_future();
t = thread(getValue, ref(flocal));
}
t.join();
return 0;
}
I expect that in getValue function, it either prints future::get result, or throws out runtime exception and prints exception info, because plocal has been destructed in "main".
Acturally, this program prints:
sub process 1
sub process 2
and ends.
| Your problem is not about std::promise or std::future behavior.
You simply cause a data race (and consequently undefined behavior) by passing the flocal object by-reference to the thread, accessing it in the thread, but also destroying it in the main thread without any synchronization.
This doesn't work no matter what type or kind of object flocal is.
Pass the std::future by-value via std::move:
void getValue(future<int> future)
/*...*/
t = thread(getValue, std::move(flocal));
With this change the destructor of std::promise will store a std::future_error exception in the shared state and get on the future in the thread will receive and throw it.
If you pass something with std::ref to a thread you always have to make sure that the referenced object outlives the thread or you need to make sure that there is some synchronization mechanism to determine when the main thread may destroy the object.
|
72,745,018 | 72,745,251 | Problem with memoization for recursive algorithm | I am calculating the least amounts of 3s and 5s that sum up to N. I used memoization and recursive algorithm.
The problem is, when I run the program and input 11, temp3 = calculate(8) returns 1, when it should clearly return 2.
I have checked that before calculate(8) is called, arr[8] = 2 already.
#include <iostream>
using namespace std;
int init, N, temp3, temp5;
int arr[5001];
int calculate(int N) {
if(arr[N]==0){
temp3 = calculate(N-3);
temp5 = calculate(N-5);
if (temp3!=-1 && temp5!=-1){
if (temp3<=temp5) {
arr[N] = temp3 + 1;
}
else {
arr[N] = temp5 + 1;
}
}
else if (temp5!=-1) {
arr[N] = temp5 + 1;
}
else if (temp3 != -1) {
arr[N] = temp3 + 1;
}
else {
arr[N] = -1;
}
}
return arr[N];
}
int main()
{
arr[1]=-1;arr[2]=-1;arr[3]=1;arr[4]=-1;arr[5]=1;
cin >> init;
cout << calculate(init);
return 0;
}
| You are operating on global variables! Several recursive calls use the same variables and it happens that the call temp5 = calculate(N-5); overwrites the temp3 value that has previously been set by the call temp3 = calculate(N-3);!
Solution: Do not use global variables!
int temp3 = calculate(N-3);
int temp5 = calculate(N-5);
This way every recursive call has its own set of variables and won't overwrite the values stored in another recursive call.
Generally: Consider always if you really, really need a global variable at all. While sometimes they cannot be avoided (without unreasonable effort) they usually are only a source of evil!
|
72,745,318 | 72,748,767 | Cmake using git-submodule inside a shared library | I try to add the library spdlog to a dll (.so file). The spdlog is just a git submodule from the spdlog library. Looking at the documentation, it's recommended to use it as a static library. So i think i have a problem trying to compile it inside a .so file.
To get a clear view of what i'm doing, here is a pic of my system:
My root CMakeLists.txt is :
cmake_minimum_required(VERSION 3.23)
# set the project name
project(Test VERSION "0.1.0" LANGUAGES CXX)
configure_file(config/config.h.in config.h)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -O3")
# Set location for .so files
set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}")
# Set location for executables
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
add_subdirectory(Engine)
list(APPEND EXTRA_LIBS Engine)
add_subdirectory(Game)
target_link_libraries(Test PUBLIC ${EXTRA_LIBS})
target_include_directories(Test PUBLIC
"${PROJECT_BINARY_DIR}"
)
And inside the Engine folder:
message(STATUS "BUILD Engine shared library File")
add_subdirectory(spdlog)
add_library(Engine SHARED Log.cpp Log.h)
target_include_directories(Engine
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries(Engine
spdlog
)
target_include_directories(Engine
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/spdlog/include
)
Inside the Game (not relevant at my opinion)
message(STATUS "BUILD .exe File")
# add the executable
add_executable(Test main.cpp)
But currently, if i try to use the spdlog inside my Log file, i have this cryptic error:
[build] /usr/bin/ld: spdlog/libspdlogd.a(spdlog.cpp.o): relocation R_X86_64_TPOFF32 against `_ZGVZN6spdlog7details2os9thread_idEvE3tid' can not be used when making a shared object; recompile with -fPIC
Does anyone have an idea?
| Thanks to fabian in the comments, I add
set(CMAKE_POSITION_INDEPENDENT_CODE 1)
Just before adding the spdlog subdirectory and it just works fine.
|
72,745,386 | 72,771,141 | Potential memory leak if a tuple of a unique pointer is captured in lambda | clang-tidy and scan-build warn about a potential memory leak in this code:
#include <tuple>
#include <memory>
int main()
{
auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {};
}
$ clang-tidy main.cpp -checks="clang*"
1 warning generated.
/foo/main.cpp:7:1: warning: Potential leak of memory pointed to by field '_M_head_impl' [clang-analyzer-cplusplus.NewDeleteLeaks]
}
^
/foo/main.cpp:6:44: note: Calling 'make_unique<int, int>'
auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {};
^~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-redhat-linux/11/../../../../include/c++/11/bits/unique_ptr.h:962:30: note: Memory is allocated
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/foo/main.cpp:6:44: note: Returned allocated memory
auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {};
^~~~~~~~~~~~~~~~~~~~~~~~~
/foo/main.cpp:7:1: note: Potential leak of memory pointed to by field '_M_head_impl'
}
^
Is there anything I do not see, or is it a false positive?
Environment: clang 13.0.0, gcc 11.3.1.
Compile commands:
[
{
"directory": "/foo",
"command": "/usr/bin/g++ -std=c++17 /foo/main.cpp",
"file": "/foo/main.cpp"
}
]
Notes: the issue is reproducible with -std=c++17 and -std=c++20, but not with -std=c++14.
| An unsolved bug in clang-tidy:
https://github.com/llvm/llvm-project/issues/55219
It doesn't have anything to do with tuples or smart pointers as seen in the simplified reproduction in this comment.
|
72,746,726 | 72,747,076 | Function which takes different enum classes types as input, how? | I am facing the following problem. Supposing I have two (or more) enum classes like these:
enum class CURSOR { ON, OFF };
enum class ANSI { ON, OFF };
I am trying to implement a (template) function called OPTION able to do something like this:
OPTION( CURSOR::ON );
OPTION( ANSI::ON );
I tried implementing it in this way:
template <typename T>
inline void OPTION( const T& opt )
{
if( opt == CURSOR::ON ) //do something...;
else if( opt == CURSOR::OFF ) //do something...;
else if( opt == ANSI::ON ) //do something...;
else if( opt == ANSI::OFF ) //do something...;
}
But it gives me the following error if I try to compile the two previously defined lines of code:
examples/../include/manipulators/csmanip.hpp: In instantiation of 'void osm::OPTION(const T&) [with T = CURSOR]':
examples/manipulators.cpp:190:14: required from here
examples/../include/manipulators/csmanip.hpp:88:18: error: no match for 'operator==' (operand types are 'const osm::CURSOR' and 'osm::ANSI')
88 | else if( opt == ANSI::ON ) enableANSI();
| ~~~~^~~~~~~~~~~
examples/../include/manipulators/csmanip.hpp:88:18: note: candidate: 'operator==(osm::ANSI, osm::ANSI)' (built-in)
examples/../include/manipulators/csmanip.hpp:88:18: note: no known conversion for argument 1 from 'const osm::CURSOR' to 'osm::ANSI'
examples/../include/manipulators/csmanip.hpp:88:18: note: candidate: 'operator==(osm::CURSOR, osm::CURSOR)' (built-in)
examples/../include/manipulators/csmanip.hpp:88:18: note: no known conversion for argument 2 from 'osm::ANSI' to 'osm::CURSOR'
examples/../include/manipulators/csmanip.hpp:89:18: error: no match for 'operator==' (operand types are 'const osm::CURSOR' and 'osm::ANSI')
89 | else if( opt == ANSI::OFF ) disableANSI();
Please ignore the fact that I defined them in a namespace osm in my code.
Do you know what is the problem and if you know how to build a function which works for this task? Thanks.
| I agree with 273K and templatetypedef about using overloads instead.
However, if you have your heart set on having a template with the case handling logic all in one place, you can do it this way:
#include <iostream>
#include <type_traits>
using std::cout;
enum class CURSOR { ON, OFF };
enum class ANSI { ON, OFF };
template <typename T>
void OPTION(T opt) {
if constexpr (std::is_same_v<T, CURSOR>) {
if (opt == CURSOR::ON) cout << "cursor is on\n";
else if (opt == CURSOR::OFF) cout << "cursor is off\n";
} else if constexpr (std::is_same_v<T, ANSI>) {
if (opt == ANSI::ON) cout << "ANSI is on\n";
else if (opt == ANSI::OFF) cout << "ANSI is off\n";
}
}
int main() {
OPTION( CURSOR::ON );
OPTION( ANSI::ON );
}
|
72,747,487 | 72,861,795 | How do I make the `std::ios_base::copyfmt_event` happen in my tests? | I wrote a set of functions to print out an address in my libaddr library (see addr.h header).
I am easily able to test the erase_event by changing one of my format flags:
std::cout << addr::setaddrsep("\n") << addresses;
I do not care about the imbue_event (the locale has no effect on IP addresses).
What I'm wondering is how to generate a copyfmt_event. When does that happen? Since it is expected to duplicate my structure, I need to make sure that part works as expected (no double delete, no leaks, proper copy).
Reference: https://en.cppreference.com/w/cpp/io/ios_base/event
| From https://en.cppreference.com/w/cpp/io/basic_ios/copyfmt :
#include <iostream>
#include <fstream>
int main()
{
std::ofstream out;
out.copyfmt(std::cout); // copy everything except rdstate and rdbuf
out.clear(std::cout.rdstate()); // copy rdstate
out.basic_ios<char>::rdbuf(std::cout.rdbuf()); // share the buffer
out << "Hello, world\n";
}
|
72,747,807 | 72,747,979 | How to CRC check a whole structure (without padding) | I have a structure which contains memory for an EEPROM:
#pragma pack(push,1)
struct EEPROM_Memory
{
char Device_ID[8];
uint8_t Version_No;
otherRandomVariables...
};
#pragma pack(pop)
I then create an instance, populate the struct and calculate it's CRC using:
CRC32::calculate(reinterpret_cast<uint8_t*>(&(memory)), sizeof(EEPROM_Memory));
I have been going crazy trying to figure out why the CRC check returns different values.
My best guess is pragma pack is not working therefore there is still some padding. This padding is volatile thus resulting in different CRC values.
What would be a nice solution (i.e not manually checking each value in the struct for their CRC)?
Any suggestions much appreciated!
P.S. I have looked at this question but sadly it does not give many suggestions on what to do. Surely this is a common problem!
P.P.S I am using an ESP32 microcontroller, unsure which compiler. The CRC library I am using is CRC32 by Christopher Baker.
| Pretty sure the pack is working as it should and you are using it wrong.
Note that pack is not recursive. So if your any of your otherRandomVariables is a struct then that struct may contain padding.
What you should do is static_assert the size of the struct. Then you know if it has the expected size or some padding. If it contains any structs assert the size of those structs first.
|
72,747,867 | 72,748,094 | using namespace std causes boost pointer cast to trigger ADL in c++17 standard | I have a simple code with inheritance and shared_ptr from boost library. With standard c++20, the code compiles fine. The function calls to static_pointer_cast and dynamic_pointer_cast compiles without prepended boost:: namespacing -- these function calls work because of ADL (Argument Dependent Lookup).
But with standard c++17, the code will not compile. I would assume that ADL wasn't implemented, or implemented differently, then. But then, if I add using namespace std, the code compiles fine. My question is: what does std have to do with boost library's function call?
Here is the online compiler so you can play around by commenting in and out the using namespace std; line: https://godbolt.org/z/cz8Md5Ezf
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
// using namespace std;
class Animal {
public:
Animal()
{}
virtual ~Animal()
{}
void speak()
{
std::cout << "I am an animal\n";
}
};
class Dog : public Animal {
public:
Dog()
{}
void bark()
{
std::cout << "Gheu --> ";
}
void speak()
{
bark();
Animal::speak();
}
};
typedef boost::shared_ptr<Animal> AnimalPtr;
typedef boost::shared_ptr<Dog> DogPtr;
int main()
{
AnimalPtr ap = boost::make_shared<Animal>();
DogPtr dp = boost::make_shared<Dog>();
AnimalPtr ap1 = static_pointer_cast<Animal>(dp);
DogPtr dp1 = dynamic_pointer_cast<Dog>(ap1);
return 0;
}
And if you are thinking, "Well, if using namespace std removes the errors, then those pointer casting calls must be from the std library." I thought so too. But looking through gdb, I saw that no, with using namespace std, those functions are definitely called from boost library.
| When the compiler sees a < after an identifier in an expression (such as in static_pointer_cast<Animal>(dp)) it needs to figure out whether < refers to the relational less operator or whether it is the start of a template argument list.
If a template is found by usual unqualified name lookup (not ADL), then the latter is assumed to be the case. But what if no template is found?
Before C++20, if the lookup did not find a template, it was assumed that the name does not refer to a template and that the following < is therefore the less operator.
In your original case that wouldn't make sense. For example there is nothing that static_pointer_cast can refer to as operand to <. So it will fail with a more or less clear error message depending on the compiler.
With using namespace std; it may be possible that the compiler implicitly included std::static_pointer_cast (from <memory>) with one of the headers you included explicitly (there is no guarantee) or it may be that the boost headers include <memory>. If that happened, then the unqualified lookup for static_pointer_cast will find it and because it is a template, < after it will be considered to start a template argument list instead of being the relation operator. Then it is clear that the whole expression is an unqualified function call with template argument list.
Since C++20, if the lookup does not find anything or finds any function at all, then it is also assumed that a < following the name introduces a template argument list.
With the interpretation as template argument list and therefore function call, normal unqualified name lookup and ADL for unqualified function calls will be done, which finds both boost::shared_pointer_cast (via ADL) and std::shared_pointer_cast if you are using using namespace std;, but because you are passing a boost::shared_ptr the std version, which requires a std::shared_ptr argument, will not be viable and the boost version will always be chosen by overload resolution. This part is unchanged with C++20.
Note that this is a breaking change in C++20. In some unusual situations you might have wanted < after a function name to actually refer to the relational operator which would now require parenthesizing the function name. See [diff.cpp17.temp] for an example.
|
72,749,196 | 72,749,536 | What is the best way to use printf in output? | This is code for a project I have recently almost completed. The code takes a gross value and then does some math to get a bunch of new values. My final instruction is to output the console output into a file. I need both a console output and a file output. My issue is I have been trying for almost a day to figure out how to output into a file with printf. If anyone has a solution it would be much appreciated.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string FirstName; // declaring variables
string LastName;
double gross;
double federalTax;
double stateTax; // each variable will be holding the total taxed amount for each category
double ssTax; // example if stateTax is 3.5%, then the stateTax variable will be 3.5% of gross
double mmTax;
double pensionPlan;
double healthIns;
double netDeduct;
double netPay;
cout << "Please enter your first name: "; // prompting for user input and storing in variables
cin >> FirstName;
cout << "\nPlease enter your last name: ";
cin >> LastName;
cout << "\nPlease enter your gross paycheck amount: ";
cin >> gross;
federalTax = gross * .15; // the math of the taxing
stateTax = gross * .035;
ssTax = gross * .0575;
mmTax = gross * .0275;
pensionPlan = gross * .05;
healthIns = 75;
netDeduct = federalTax + stateTax + ssTax + mmTax + pensionPlan + healthIns;
netPay = gross - netDeduct;
cout << endl,cout << FirstName + " " + LastName; cout << endl; // printing of the results
printf("Gross Amount: %............ $%7.2f ", gross); cout << endl;
printf("Federal Tax: %............. $%7.2f ", federalTax); cout << endl;
printf("State Tax: %............... $%7.2f ", stateTax); cout << endl;
printf("Social Security Tax: %..... $%7.2f ", ssTax); cout << endl;
printf("Medicare/Medicaid Tax: %... $%7.2f ", mmTax); cout << endl;
printf("Pension Plan: %............ $%7.2f ", pensionPlan); cout << endl;
printf("Health Insurance: %........ $%7.2f ", healthIns); cout << endl;
printf("Net Pay: %................. $%7.2f ", netPay); cout << endl;
}
| Side note: If you are coding in C++ then you should use the newer functionalities such as cout or fstream instead of printf of fprintf
Now, coming to your question: What you are probably looking for is fprintf()
Here's a snippet using the function that I just mentioned above:
FILE * fp = fopen ("file.txt", "w+");
fprintf(fp, "%s %f", "Your net pay is: ", netPay);
As you can see, it's quite similar to printf and that's why I think it should be self explanatory to you. The only big difference is passing a FILE pointer to it
Check these links out to learn more about fprintf() and fopen()
|
72,749,220 | 72,749,634 | create a class in C++ | In C++ suppose I defined a class named Player without a default constructor.
When I creating a class instance in the main function:
Player John;
The class will be created and I can see it in the debugger but the Player Adam() the class will not be created
Why the class will not be created in Player Adam();
isn't Adam() will trigger the default constructor which have no arugments ?
what is the difference between using () and not using them when there is not default constructor.
#include<iostream>
class Player{
private:
std::string name{"Jeff"};
double balance{};
public:
};
int main()
{
Player John; // the class will be created I can see it in the debugger
Player Adam();//the class will not be created
std::cout<<"Hello world"<<std::endl;
return 0;
}
| I think your problem is that you are not really creating the second object. I put your code on compiler explorer here, where you can see the compilation warnings:
<source>: In function 'int main()':
<source>:16:17: warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
16 | Player Adam();//the class will not be created
| ^~
<source>:16:17: note: remove parentheses to default-initialize a variable
16 | Player Adam();//the class will not be created
| ^~
| --
<source>:16:17: note: or replace parentheses with braces to value-initialize a variable
Compiler returned: 0
It looks like the compiler is interpreting Player adam(); as a function declaration and not as an object instantiation. If you change the declaration to Player adam{};, or remove the parentheses completely, the compiler will interpret this "correctly", and the problem should be solved.
Indeed, in the assembly code you can see that the object constructor, Player::Player is only called once (you need to change the optimization to -O0 to see it, otherwise it will get inlined):
main:
push rbp
mov rbp, rsp
push rbx
sub rsp, 56
lea rax, [rbp-64]
mov rdi, rax
call Player::Player() [complete object constructor]
<printing code begins here>
|
72,749,665 | 72,752,706 | C++ abstract method, different parameters in different inheritances | I have a base class from which several classes should inherit.
The base class is supposed to be a simple interface, which one inherits for a easy implementation/ for passing data into a library.
However, the parameters of the overridden method vary depending on the implementation (inheritance).
In my concrete case, a class, which should parse a file and the number of the used file paths (and their names) varies depending on the implementation.
Example
This is a boiled-down example to the bare minimum because first I'm not allowed to share my code, and secondly to better illustrates my problem.
class Base
{
public:
Base() = default;
virtual ~Base() = default;
// this should be the interface method
virtual void fn() = 0;
};
class Child1: Base
{
public:
Child1() = default;
virtual ~Child1() = default;
// in this implementation three parameters are needed
virtual void fn(const std::string& file_path_1,
const std::string& file_path_2,
const std::string& file_path_3) override;
};
class Child2: Base
{
public:
Child2() = default;
virtual ~Child2() = default;
// in this implementation only two parameters are needed
virtual void fn(const std::string& file_path_1,
const std::string& file_path_2) override;
};
What I have already tried
I already tried to use Variadic arguments, which could theoretically work.
Only the readability suffers and it can't be guaranteed at compile time that the required number of arguments was given.
class Base
{
public:
Base() = default;
virtual ~Base() = default;
// this should be the interface method
virtual void fn(const std::string& file_pats, ...) = 0;
};
I also thought about Variadic Templates, but quickly abandoned this approach due to its complexity/ implementation effort in order to find a more simple solution (but if this is the only viable approach, please tell me).
The Question
Is there a way to have an abstract base class, with a pure virtual method, whose parameters may differ between different implementations?
| C-style variadic functions should be avoided in C++. Better would be to use variadic template functions, but unfortunately that doesn't really work for virtual functions, see this post for an explanation why.
@AdrianMole and @user17732522 hinted at the right answer: try to find a way to pass a list of things as a single parameter, be that an initializer list or some container like a std::vector (or a view of a container, for example using C++20's std::span).
Finally, if the number of arguments really depends on the derived type, then perhaps fn() should not be a virtual function at all.
|
72,749,832 | 72,749,903 | In the example of std::atomic<T>::exchange, why the count of times is not 25? | The example I talked about is this one on cppreference.com.
The code snippet is pasted below.
int main(){
const std::size_t ThreadNumber = 5;
const int Sum = 5;
std::atomic<int> atom{0};
std::atomic<int> counter{0};
// lambda as thread proc
auto lambda = [&](const int id){
for (int next = 0; next < Sum;){
// each thread is writing a value from its own knowledge
const int current = atom.exchange(next);
counter++;
// sync writing to prevent from interrupting by other threads
std::osyncstream(std::cout)
<< '#' << id << " (" << std::this_thread::get_id()
<< ") wrote " << next << " replacing the old value "
<< current << '\n';
next = std::max(current, next) + 1;
}
};
std::vector<std::thread> v;
for (std::size_t i = 0; i < ThreadNumber; ++i){
v.emplace_back(lambda, i);
}
for (auto& tr : v){
tr.join();
}
std::cout << ThreadNumber << " threads adding 0 to "
<< Sum << " takes total "
<< counter << " times\n";
}
To me, the value of counter is 25 because 5 threads and each thread loops 5 times. However, the shown output is 16. I also ran it myself, the possible value varies, but it never gets to be 25.
Why the printed value of counter is actually smaller?
| Consider one of the possible executions:
Lets say one of the threads finishes the loop before other threads start.
This gives you atom == 4. The next thread to enter the loop will get current == 4 and will exit the loop after the first iteration.
This way the second thread increments current once instead of 5 times like you expect it to.
|
72,749,955 | 72,753,193 | Unable to compile the example for Eigen SVD | I am trying to compile the example provided for Eigen::JacobiSVD and I am getting the following error,
/usr/local/include/eigen3/Eigen/src/SVD/JacobiSVD.h: In instantiation of ‘Eigen::JacobiSVD<MatrixType, QRPreconditioner>& Eigen::JacobiSVD<MatrixType, QRPreconditioner>::compute(const MatrixType&, unsigned int) [with _MatrixType = Eigen::Matrix<float, -1, -1>; int QRPreconditioner = 40; Eigen::JacobiSVD<MatrixType, QRPreconditioner>::MatrixType = Eigen::Matrix<float, -1, -1>]’:
/usr/local/include/eigen3/Eigen/src/SVD/JacobiSVD.h:549:14: required from ‘Eigen::JacobiSVD<MatrixType, QRPreconditioner>::JacobiSVD(const MatrixType&, unsigned int) [with _MatrixType = Eigen::Matrix<float, -1, -1>; int QRPreconditioner = 40; Eigen::JacobiSVD<MatrixType, QRPreconditioner>::MatrixType = Eigen::Matrix<float, -1, -1>]’
demo.cpp:9:55: required from here
/usr/local/include/eigen3/Eigen/src/SVD/JacobiSVD.h:692:27: error: ‘struct Eigen::internal::qr_preconditioner_impl<Eigen::Matrix<float, -1, -1>, 40, 0, true>’ has no member named ‘run’
m_qr_precond_morecols.run(*this, m_scaledMatrix);
~~~~~~~~~~~~~~~~~~~~~~^~~
/usr/local/include/eigen3/Eigen/src/SVD/JacobiSVD.h:693:27: error: ‘struct Eigen::internal::qr_preconditioner_impl<Eigen::Matrix<float, -1, -1>, 40, 1, true>’ has no member named ‘run’
m_qr_precond_morerows.run(*this, m_scaledMatrix);
Could you please help me with this? Thanks
Code :
#include <Eigen/Core>
#include <Eigen/SVD>
#include <iostream>
using namespace std;
using namespace Eigen;
int main () {
MatrixXf m = MatrixXf::Random(3,2);
cout << "Here is the matrix m:" << endl << m << endl;
JacobiSVD<MatrixXf, ComputeThinU | ComputeThinV> svd(m);
cout << "Its singular values are:" << endl << svd.singularValues() << endl;
cout << "Its left singular vectors are the columns of the thin U matrix:" << endl << svd.matrixU() << endl;
cout << "Its right singular vectors are the columns of the thin V matrix:" << endl << svd.matrixV() << endl;
Vector3f rhs(1, 0, 0);
cout << "Now consider this rhs vector:" << endl << rhs << endl;
cout << "A least-squares solution of m*x = rhs is:" << endl << svd.solve(rhs) << endl;
}
g++ : 7.5
Eigen : 3.4.0
| This looks very much like a bug. I looked at the code and there is no way it can work. I'll file a bug report.
As a workaround, this should work even though it is marked as deprecated:
JacobiSVD<MatrixXf> svd;
svd.compute(m, ComputeThinU | ComputeThinV);
The underlying issue is that during template-specialization, the code does not separate the Compute options from the QR preconditioner options. So it doesn't find a suitable implementation.
EDIT
The issue is with a disparity between the online documentation and the current release. The documentation is for 3.4.90 but the last released version is 3.4.0.
In 3.4.90 the compute parameters must be declared in either the template or the runtime parameters, but not both.
In 3.4.0 and earlier, the compute options must be declared in the runtime parameters.
// works in all versions but deprecation warning in 3.4.90
Eigen::JacobiSVD<Eigen::MatrixXf> svd;
svd.compute(m, Eigen::ComputeThinV | Eigen::ComputeThinU);
// or
Eigen::JacobiSVD<Eigen::MatrixXf> svd(m, Eigen::ComputeThinV | Eigen::ComputeThinU);
// works in 3.4.90
Eigen::JacobiSVD<Eigen::MatrixXf, Eigen::ComputeThinV | Eigen::ComputeThinU> svd;
svd.compute(m);
|
72,750,175 | 72,750,255 | ARM64 64 bit load/store data race | According to this, a 64 bit load/store is considered to be an atomic access on arm64. Given this, is the following program still considered to have a data race (and thus can exhibit UB) when compiled for arm64 (ignore ordering with respect to other memory accesses)
uint64_t x;
// Thread 1
void f()
{
uint64_t a = x;
}
// Thread 2
void g()
{
x = 1;
}
If instead I switch this to using
std::atomic<uint64_t> x{};
// Thread 1
void f()
{
uint64_t a = x.load(std::memory_order_relaxed);
}
// Thread 2
void g()
{
x.store(1, std::memory_order_relaxed);
}
Is the second program considered data race free?
On arm64, it looks like the compiler ends up generating the same instruction for a normal 64 bit load/store and a load/store of an atomic with memory_order_relaxed, so what's the difference?
| Whether or not an access is a data race in the sense of the C++ language standard is independent of the underlying hardware. The language has its own memory model and even if a straight-forward compilation to the target architecture would be free of problems, the compiler may still optimize based on the assumption that the program is free of data races in the sense of the C++ memory model.
Accessing a non-atomic in two threads without synchronization with one of them being a write is always a data race in the C++ model. So yes, the first program has a data race and therefore undefined behavior.
In the second program the object is an atomic, so there cannot be a data race.
|
72,750,692 | 72,750,706 | Why is the value of the variable not increasing after sizeof(++)? | The value i is 1, but why is i still 1 after sizeof(i++)? I only know sizeof is an operator.
int main() {
int i = 1;
sizeof(i++);
std::cout << i << std::endl; // 1
}
| sizeof does not evaluate its operand. It determines the operand's type and returns its size. It is not necessary to evaluate the operand in order to determine it's size. This is actually one of the fundamental core principles of C++: the types of all objects -- and by consequence of all expressions -- is known at compile time.
And since the operand does not get evaluated there are no side effects from its evaluation. If you sizeof() something that makes a function call the function does not actually get called: sizeof(hello_world()) won't call this function, but just determines the size of whatever it returns.
|
72,751,128 | 72,758,206 | Using SFINAE to check if member exists in class based on a template | The example here shows how we can use TMP to have the compiler elide functions based on whether a member exists for a given type. I want to write a metafunction that works for classes based on templates. Compilation should succeed if a class based on a template is provided in the function call that has the desired member.
The class:
template <typename KeyType>
struct RawBytesEntry
{
bool used = false;
size_t psl = 0;
KeyType key;
...
}
I tried a whole slew of different suggestions and syntax permutations but I couldn't get it to work. Does anyone have any suggestions? Here is what I think is the "closest" I got:
template <template <typename> typename EntryType, typename = void>
struct has_psl : std::false_type
{
};
template <template <typename KeyType> typename EntryType>
struct has_psl<EntryType<KeyType>, std::void_t<decltype(EntryType<KeyType>::psl)>> : std::true_type
{
};
template <template <typename KeyType> typename EntryType, std::enable_if<has_psl<EntryType>::value>>
bool f(EntryType<KeyType> *buffer, size_t offset, EntryType<KeyType> *new_entry)
| The template parameters of the template template parameter can not be used in the body.
template <typename T, typename = void>
struct has_psl : std::false_type
{};
template <template <typename> typename EntryType, typename KeyType>
struct has_psl<EntryType<KeyType>, std::void_t<decltype(EntryType<KeyType>::psl)>> : std::true_type
{};
template <template <typename> typename EntryType, typename KeyType, std::enable_if<has_psl<EntryType<KeyType>>::value>>
bool f(EntryType<KeyType> *buffer, size_t offset, EntryType<KeyType> *new_entry) {
return true;
}
And then,
static_assert(has_psl<int>::value == false);
static_assert(has_psl<RawBytesEntry<int>>::value == true);
Online Demo
|
72,752,046 | 72,752,574 | Runtime polymorphism in C++ using data members | I was studying OOP from here.
It says that runtime polymorphism is possible in C++ using data members.
Now,consider this code:-
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
Animal d1 = Animal();
cout<<d.color<<endl;
cout<<d1.color<<endl;
}
In both the cases above the color "black" is printed. So, how is this example of runtime polymorphism ?
| If this was runtime polymorphism you could write a function:
void foo(Animal& a) {
std::cout << a.color << "\n";
}
And it would print the respective color of the object based on the dynamic type of the parameter. However, there is no such thing as "Runtime-polymorphism based on member variables" in C++. The tutorial is wrong and misleading.
If compile and execute this:
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
void foo(Animal& a) {
std::cout << a.color << "\n";
}
int main(void) {
Dog d= Dog();
Animal d1 = Animal();
foo(d);
foo(d1);
}
The output will be
Black
Black
There is no such thing as virtual member variables. Only for virtual member functions use virtual dispatch:
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
virtual std::string color() const { return "Black"; }
};
class Dog: public Animal // inheriting Animal class.
{
public:
std::string color() const override { return "Grey"; }
};
void foo(Animal& a) {
std::cout << a.color() << "\n";
}
int main(void) {
Dog d= Dog();
Animal d1 = Animal();
foo(d);
foo(d1);
}
Output:
Grey
Black
The turial is wrong and misleading when it says that there would be runtime polymorphis with member variables. Moreover the example they present has object slicing. See here: What is object slicing?.
|
72,752,156 | 72,752,175 | c++11 is it safe to return an initializer_list value? | I've this simple function:
initializer_list<int> f(){return {1,2,3};}
g++ gives a warning saying:
warning: returning temporary initializer_list does not extend the lifetime of the underlying array [-Winit-list-lifetime]
Is there any risk to return an {1, 2, 3}?
Thanks for explanations!
| An initializer_list behaves like a reference extending lifetime of a temporary (the temporary being the array).
Lifetime extension doesn't apply when returning references, so it doesn't apply here too. The compiler is right, the returned list is always dangling.
|
72,752,296 | 72,752,455 | SDL_SetWindowHitTest - callback & callback_data? (SDL 2.0.5) | Could someone please help me to understand what these two parameters are, and how to interact with/utilize them? The Wiki says that callback is a function - itself - what should the call of it be like and what should it be returning/doing?
Current Purpose: to Move a Borderless Window (via mouse click and drag)
Alternative: SDL_SetWindowPosition (it's incredibly jittery for manual moving)
I'm on Windows 10, if there is something I can (even more) directly interface with... I've never done that, but if it's a feasible solution I'd also be willing to try that!
| Here's how SDL_HitTest (the callback type) is defined:
/**
* Callback used for hit-testing.
*
* \param win the SDL_Window where hit-testing was set on
* \param area an SDL_Point which should be hit-tested
* \param data what was passed as `callback_data` to SDL_SetWindowHitTest()
* \return an SDL_HitTestResult value.
*
* \sa SDL_SetWindowHitTest
*/
typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win,
const SDL_Point *area,
void *data);
So you need to provide a function with arguments (SDL_Window *win, const SDL_Point *area, void *data), returning SDL_HitTestResult.
The void *callback_data can be anything. It'll be saved and passed to your callback every time. You'll see this pattern a lot in C libraries that work with callbacks, since it allows you to pass additional state into callbacks - a poor man's std::function.
Your function, given coordinates, needs to return if they belong to a window title, or border (which one), or neither.
|
72,752,502 | 72,752,802 | Array doesn't print correct values beyond a certain limit of indices | The following code gives a very wrong and random output for inputs greater than 5,5 (respective values of m and n wrt the code below). Why is it so? What might be the fix to this?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int m,n;
cin>>m>>n;
int i,j,k;
int a[m][n];
k = 1;
a[0][0] == 1;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
cout<<(a[0][0]+k*(j+1))<<" ";
}
k = k+2;
cout<<'\n';
}
}
return 0;
}
| If you compile this withg warnings enabled you get:
<source>:18:15: warning: equality comparison result unused [-Wunused-comparison]
a[0][0] == 1;
~~~~~~~~^~~~
<source>:18:15: note: use '=' to turn this equality comparison into an assignment
a[0][0] == 1;
^~
=
1 warning generated.
You don't want comparison there but a[0][0] = 1;.
Now for other stuff you shouldn't do:
int a[m][n]; is not C++ but a compiler extension. Use std::vector.
int a[m][n]; leaves the array uninitialized and you only ever write to a[0][0] (if you fix the ==).
a is never ever used except for a[0][0]. The whole array is utterly pointless. A single const int a = 1; would do the same.
#include <bits/stdc++.h> is wrong and doesn't even exist on many compilers
using namespace std; is overly broad. You never want/need all of std. Be more selective.
|
72,752,841 | 72,752,934 | How to efficiently calculate the symmetric force matrix (Newton's 3rd law)? | Intro
For the N-body simulation I need to calculate the total received force Fi for each body it receives from the other bodies. This is an O(n^2) problem, because for each body the pairwise total force must be calculated. Because of the Newton's 3rd axiom fi,j = -fi,j we can reduce the number of force calculations by half.
Problem
How to implement this law in my code in order to optimize the acceleration calculation?
What I have did so far?
I programmed the total received force for each body, but without that optimization.
std::vector<glm::vec3> SequentialAccelerationCalculationImpl::calcAccelerations(
const std::vector<Body> &bodies,
const float softening_factor
) {
const float softening_factor_squared = softening_factor * softening_factor;
const size_t num_bodies = bodies.size();
std::vector<glm::vec3> accelerations(num_bodies);
// O(n^2)
for (size_t i = 0; i < num_bodies; ++i) {
glm::vec3 received_total_force(0.0);
for (size_t j = 0; j < num_bodies; ++j) { // TODO this can be reduced to half
if (i != j) {
const glm::vec3 distance_vector = bodies[i].getCurrentPosition() - bodies[j].getCurrentPosition();
float distance_squared =
(distance_vector.x * distance_vector.x) +
(distance_vector.y * distance_vector.y) +
(distance_vector.z * distance_vector.z);
// to avoid zero in the following division
distance_squared += softening_factor_squared;
received_total_force += ((bodies[j].getMass() / distance_squared) * glm::normalize(distance_vector));
}
}
accelerations[i] = GRAVITATIONAL_CONSTANT * received_total_force;
}
return accelerations;
}
I also sketched the force matrix:
| The simple solution is to have the inner loop start from i + 1 instead of from 0:
for (size_t i = 0; i < num_bodies; ++i) {
glm::vec3 received_total_force(0.0);
for (size_t j = i + 1; j < num_bodies; ++j) {
glm::vec3 distance_squared = glm::distance2(bodies[i].getCurrentPosition(), bodies[j].getCurrentPosition());
...
}
}
However now you have to ensure you update both accelerations[i] and accelerations[j] inside the inner loop, instead of first accumulating in received_total_force:
accelerations[i] += bodies[j].getMass() / distance_squared * glm::normalize(distance_vector);
accelerations[j] -= bodies[i].getMass() / distance_squared * glm::normalize(distance_vector);
|
72,753,084 | 72,753,174 | Values subtraction in the time calculation | Having such a bit of code:
DWORD time1 = 0xFFFFFFFC;
DWORD time2 = 0x0000000B; //11 dec
DWORD time3 = 0x0000000D; //13 dec
DWORD time4 = 0x0000000F; //15 dec
swprintf_s(g_msgbuf, L"delta1: %i, %u\n", time2 - time1, time2 - time1);
OutputDebugString(g_msgbuf);
swprintf_s(g_msgbuf, L"delta2: %i, %u\n", time3 - time1, time3 - time1);
OutputDebugString(g_msgbuf);
swprintf_s(g_msgbuf, L"delta3: %i, %u\n", time4 - time1, time4 - time1);
OutputDebugString(g_msgbuf);
if ((time2 - time1) == 15)
OutputDebugString(L"equal\n");
else
OutputDebugString(L"not equal\n");
I'm getting the following output:
delta1: 15, 15
delta2: 17, 17
delta3: 19, 19
equal
Can someone please explain me the output results: 15, 17, 19? (Where are the values coming from)
Since I'm implementing a simple game loop and have to measure a delta time between two frames. The code above just simulates so called "wrap around" problem (Yes, i'm using the timeGetTime function and PLEASE DON'T tell me to use another, newer/better time function!) when we deal with subtraction when the second number(second time) is bigger than first number(first time) thus in theory resulting in just negative number BUT as we can see the values 15, 17, 19 seems to be just what I have to get - the absolute delta time(minus 1) between two frames even if there was that "wrap around" and this is my second question - in the case above can i rely on that implicit compiler behavior and just forget about the "wrap around" problem since the resulting values seems to be correct(mins 1)?
| Unsigned arithmetic is performed modulo the max value the type can hold plus one.
Therefore
0x0000000B - 0xFFFFFFFC
with 4 byte unsigned types such as DWORD yields the same result as
0x0000000B - (0xFFFFFFFC + 4 - 4)
or
0x0000000B + 4 - (0xFFFFFFFC + 4)
or (using the fact that the brackets are 0 modulo the max value DWORD can hold + 1)
0x0000000B + 4 - 0x00000000
which is 15 (or 0x0F).
Similar for the other differences.
You can rely on this behaviour, see the Overflows section of the Arithmetic operators page on cppreference.com
|
72,753,113 | 72,753,151 | Is it ok to put the main loop of a program in the constructor of a class? | I am making a Bomberman game, and it needs a "main loop" where the game updates constantly. Here's basically what I did :
class BomberMan {
public:
BomberMan()
{
Init_BomberMan();
while (RayLib::ShouldWindowClose()) {
// game updates things
}
}
private:
Init_BomberMan()
{
// init data, load sprites, do things
}
};
int main ()
{
try {
BomberMan();
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}
Is putting the loop in the constructor of BomberMan class ok ?
Or is it better and cleaner to put it out of the constructor and do things differently ?
| It's pretty bad to do so.
The constructor is supposed to initialize the class. So having a function Init_BomberMan shows that you don't understand what a constructor is for. That function should be the constructor and probably nothing else.
And then you should have a function that runs your game, lets call that run as is so often used:
class BomberMan {
public:
void run()
{
while (RayLib::ShouldWindowClose()) {
// game updates things
}
}
BomberMan()
{
// init data, load sprites, do things
}
};
int main ()
{
try {
BomberMan().run();
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}
The biggest reason for this, besides bad style, is that exception handling in constructors is a pain. Also calling other functions of the class in the constructor is fishy. You can do that if you are careful and only use members of the class that have already been initialized and such. Keep your constructors simple. The best constructor is an empty one, only topped by not needing one at all.
Use member initialization lists in the constructor or inline initialization of the members.
|
72,753,182 | 72,755,299 | SOCKS5 responds with no BND.ADDR nor BND.PORT? | Although this looks like a bug, some developers argue how it complies perfectly with the RFC.
I wrote a simple C++ program on Linux which connects to a HTTP web-page and reads its contents over Tor. I start a tor service using this command:
tor --ignore-missing-torrc -f / --SocksPort auto --DataDirectory $HOME/tren/tor_0
$HOME/tren is just a directory I mount as tmpfs (btw, the same happens even if I only run tor). Tor connects successfully and I can use its socket. Now my program negotiates with the port like this:
I send {5,1,0}
SOCKS5 sends {5,0}
I send {5,1,0,3,17,www.icanhazip.com,0,80}
SOCKS5 sends {5,0,0,1,0,0,0,0,0,0}
This domain name address is written byte by byte, without null termiation. Why is my SOCKS5 responding with 0 address? If I connect to the web-site using it's IPv4 that I resolve locally, the same happens. I try requesting HTTP page and it responds properly.
I am using Arch and I have installed it's official tor package.
EDIT: I deleted my code as it was incomplete and far from 'minimal'
| Your SOCKS5 request is perfectly fine, and the proxy is replying back that it successfully connected to www.icanhazip.com:80, so just start exchanging your HTTP data as needed over your existing connection to the proxy.
The proxy's reply is simply telling you that it bound itself to 0.0.0.0:0 (or maybe it is choosing not to tell you the actual IP/port it is bound to) when it connected to www.icanhazip.com:80:
BND.ADDR/BND.PORT
|
\/
+--------+ +-------+ +--------+
| Client | x <-> p1 | Proxy | p2 <-> y | Target |
+--------+ +-------+ +--------+
^
| +-----+
+-----> | DNS |
+-----+
The zeros you are referring to are in the BND.ADDR/BND.PORT fields of the proxy's reply. Those fields represent p2 above - the outbound IP/Port used by the proxy to connect to the target server after it resolved the hostname that your client requested. It sounds like you are expecting those fields to contain the inbound IP/port for the target server at y instead, which is not the case.
You don't need to know the target's IP/Port in order to use the connection. You have a fully functional tunnel between you and the target via the proxy, just use the connection as-is once the tunnel is established. You just won't be able to know the target's IP/Port. You can't get that info from the proxy. The only way to get it is to either resolve the hostname yourself (which defeats the purpose of asking the proxy to resolve it for you), or else ask the target itself (if it has a script for that purpose).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.