question_id
int64 25
74.7M
| answer_id
int64 332
74.7M
| title
stringlengths 20
150
| question
stringlengths 23
4.1k
| answer
stringlengths 20
4.1k
|
|---|---|---|---|---|
74,579,071
| 74,579,154
|
Concept for using statement inside class
|
I have a class like this:
struct FooImpl {
public:
using Bar = int;
};
I would like to declare that FooImpl::Bar is an int through a concept.
This does the job:
template<typename Foo>
concept FooConcept = requires(Foo foo) {
{ std::vector<typename Foo::Bar>() } -> std::same_as<std::vector<int>>;
};
static_assert(FooConcept<FooImpl>);
Is there a more elegant way of doing this? I tried:
{ (typename Foo::Bar)() } -> std::same_as<int>;
But the compiler does not seem happy with this.
|
First, the reason { (typename Foo::Bar)() } -> std::same_as<int>; doesn't work is because of most vexing parse typename-specifier can’t be a declarator, and cannot be used within a C-styly-cast parentheses.* To make it work, you should use a brace init instead:
template<typename Foo>
concept FooConcept = requires(Foo foo) {
{ typename Foo::Bar{} } -> std::same_as<int>;
};
* Corrected by @DavisHerring from the comment
Second, if the only constraint you have is to make sure a certain nested type is the same as another, you can simply use std::same_as:
template<typename Foo>
concept FooConcept = std::same_as<typename Foo::Bar, int>;
Last, some terminologies:
I would like to declare that FooImpl::Bar is an int through a concept.
Declaring FooImpl::Bar is an int was already done by the using statement(using Bar = int). What you probably meant is:
You want to declare a concept for a type T that requires T::Bar to be an int.
Or:
You want to constraint a type T that T::Bar is an int through a concept.
|
74,579,182
| 74,579,344
|
C++ decltype failed on vector elem
|
template <typename T>
void F(T&) { std::cout << __FUNCTION__ << "\n"; }
template <typename T>
void F(vector<T>&) { std::cout << __FUNCTION__ << "\n"; }
int main()
{
int x = 0;
F<decltype(x)>(x); // this line compile and works fine
vector<int> v;
F<decltype(v[0])>(v); // this line won't compile
F<remove_reference<decltype(v[0])>>(v); // Neither this one
}
Why wouldn't F<decltype(v[0])>(v); work?
|
First, you do not have a v[0]. Even if you do have elements in v,* decltype(v[0]) will be int&, hence F<decltype(v[0])>(v) fails.
Note*: more in the comment about why having elements in v or not doesn't matter.
Second, remove_reference<decltype(v[0])> is the name of a struct, not a type. To properly get the type from it, you should call:
std::remove_reference<decltype(v[0])>::type
^^^^^^
Or:
std::remove_reference_t<decltype(v[0])>
^^
Also, instead of using remove_reference, you can simply get the element type of a vector with ::value_type:
F<decltype(v)::value_type>(v);
Demo
|
74,579,458
| 74,579,541
|
Opening a file in home directory
|
Say you have a program you run, and it has the following lines of code:
#include <fstream>
using std::fstream;
int main() {
fstream someFile;
someFile.open("~/someFile");
if(!someFile.is_open()) {
// Make the file
}
}
I'm trying to open a file in the home directory (i.e. "~" on Unix devices). How could this be done? What I'm doing right now doesn't seem to work. Additionally, how can I make the file if it doesn't exist yet?
Note that this program can run from anywhere; not just home, but I need it to look for a file in the home directory.
|
open has a second parameter: openmode, so you may want something like
someFile.open ("somefile", std::fstream::out | std::fstream::app);
if you want to append.
For the home directory you can check HOME environment variable and getpwuid:
const char *homedir;
if ((homedir = getenv("HOME")) == NULL) {
homedir = getpwuid(getuid())->pw_dir;
}
|
74,579,511
| 74,579,580
|
Why does my for loop print out a memory location
|
I'm doing a USACO prompt and when I print out the variable i it keeps on outputting a memory location(i think?). Each time I run it, it outputs something different at the end. I'm not sure if there is an uninitialized value since I'm not sure what variable it could be.
`
#include <fstream>
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <map>
#include <initializer_list>
#include <unordered_map>
using namespace std;
int main()
{
ifstream fin("blocks.in");
ofstream fout("blocks.out");
int n = 0;
fin >> n;
cout << n;
vector<int> alphab(26);
vector<int> usedA(26);
char foo[26] = { 'a', 'b', 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' };
int doo[26] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
string stringA = "d";
string stringB = "d";
for (int i = 0; i < n; i++)
{
fin >> stringA >> stringB;
stringA += stringB;
sort(begin(stringA), end(stringA));
auto last = unique(begin(stringA), end(stringA));
stringA.erase(last, end(stringA));
cout << i << "\n";
/*
for (int i = 0; i < stringA.length(); i++)
{
for (int j = 0; j < 26; i++)
{
if (stringA[i] == foo[j])
{
doo[j] += 1;
}
}
}
*/
}
cout << doo;
}
`
I made sure to give all the variables I have values prior to the loop but it didnt work :(
|
When you do cout << doo, your printing the memory location of where doo starts. You need to print a specific index inside of doo to get the value.
For example, cout << doo[0] will print the first value inside your array (if it exists). cout << doo[1] will print the second element, and so on.
|
74,579,643
| 74,579,722
|
Why does the starting directory matter when launching a OpenGL executable?
|
I am doing a openGL porject and readering my shaders from .vert and .frag glsl files. I am using CMake with an extension for auto ninja file generation as well. This is my readfile code:
std::string readFile(const char *filePath) {
std::string content;
std::ifstream fileStream(filePath, std::ios::in);
if(!fileStream.is_open()) {
std::cerr << "Could not read file " << filePath << ". File does not exist." << std::endl;
return "";
}
std::string line = "";
while(!fileStream.eof()) {
std::getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
I spent a long time thinking I was crazy because from my build dir I was doing ./app/NAME_OF_APP.exe but the shaders were not being applied just black. It was only when I clicked on it from within the file explorer that it worked so I cd'ed into build/app/ and called ./NAME_OF_APP.exe and boom it worked. Why is this behavior happening? does the starting dir effect the relative pathing of the actual application? seems odd to me. thanks.
|
If you run a program from a command line the current directory is whatever directory is current in that command prompt. If you run a program from explorer the current directory is the directory that houses the executable.
You could use a function like GetModuleFileName (with NULL as the hModule parameter) to get the path to the executable and then chop off at the last \ and then change to that directory and then the program would not depend on the directory the program is run from.
|
74,579,938
| 74,580,464
|
Preserve References in C++ During Functioncalls
|
I want to preserve references during function calls in C++. In The following example the function baz creates two classes: Foo and Bar. The class foo is then passed to Bar as reference but instead of keeping foo until Bar is destroyed, it is destroyed after function execution.
In all other cases the foo references stays until the referencing Bar class is destroyed.
My question now: is there a way of preserving references inside of classes until they are destroyed without new/delete or do I have to go the buffer-overflow way ?
Also what is the sense of references when they create such faulty behavior, because I can't safely access Foo references in Bar like this.
What I want is either pass a default (null, nofoo) class to Bar or a customized one without keeping track of new/delete because I am planning of passing a whole bunch of different classes without the memory overhead derivation would cause. Similar to a container based behavior.
class Foo
{
private:
int size;
int state;
int property;
float value;
public:
Foo ( int s )
{
size = s;
state = 0;
property = 0;
value = 0.0;
print ( "class Foo constructed with size: %i\n", size );
}
~Foo ( )
{
print ( "class Foo destructed with size: %i\n", size );
}
};
Foo nofoo ( 0 );
class Bar
{
private:
Foo &fooref;
public:
Bar ( Foo &ref = nofoo ) : fooref ( ref )
{
print ( "class Bar constructed with foo: %i, nofoo: %i\n", (Foo *)&fooref, (void *)&ref==(void *)&nofoo );
}
~Bar ( )
{
print ( "class Bar destructed with foo: %i\n", (Foo *)&fooref );
}
};
Foo faz()
{
print ( "function faz called\n" );
Foo ret ( 2 );
return ret; // Foo is not destroyed here
}
Bar baz()
{
print ( "function baz called\n" );
Foo foo4 ( 4 );
Bar ret ( foo4 );
return ret; // Foo is destroyed here but stays as reference in Bar
}
int main ()
{
print ( "test code started\n" );
Foo foo ( 1 );
Bar bar ( foo );
print ( "size of foo: %i\n", sizeof(foo) );
print ( "size of bar: %i\n", sizeof(bar) );
Foo fooref = faz();
print ( "size of fooref=faz(): %i\n", sizeof(fooref) );
Bar bar2;
print ( "size of bar2: %i\n", sizeof(bar2) );
Bar barref = baz();
print ( "size of barref=baz(): %i\n", sizeof(barref) );
return 0;
}
Output of this code:
test code started
class Foo constructed with size: 1
class Bar constructed with foo: -96188384, nofoo: 0
size of foo: 16
size of bar: 8
function faz called
class Foo constructed with size: 2
size of fooref=faz(): 16
class Bar constructed with foo: 1977483344, nofoo: 1
size of bar2: 8
function baz called
class Foo constructed with size: 4
class Bar constructed with foo: -96188480, nofoo: 0
class Foo destructed with size: 4
size of barref=baz(): 8
class Bar destructed with foo: -96188480
class Bar destructed with foo: 1977483344
class Foo destructed with size: 2
class Bar destructed with foo: -96188384
class Foo destructed with size: 1
class Foo destructed with size: 0
One could use pointers instead of references, but references are (at least should be) safer. Whenever I would call a member of a Foo pointer I have to check if it is valid.
A way could be unique_ptr<> template type which, at least, keeps track of deletion. But still I would have to check for nullptr. What I require is some kind of unique_ptr for references.
|
There is nothing that will allow you to extend the lifetime of a reference like you want. A reference does not give you that. Pointers are how we share and transfer ownership because it is only through a pointer that we can take on responsibility of deleting an object.
When we accept a reference as a parameter, we are communicating that we are not accepting any responsibility for the lifetime of the parameter.
With pointers, we have three options and different semantics for each:
Raw pointers. Here, it is unspecified who is responsible for the object. If you follow the general guidance, raw pointers should only be used when we are indicating that we are not taking on any responsibility for the lifetime of the object. Rather than relying on convention we can use one of the other options.
Unique pointers. With unique_ptr parameters we indicate that we are taking ownership of an object from elsewhere. Ownership is transferred to the function and nothing outside of the function owns it.
Shared pointer. Here we are indicating that we are taking on shared responsibility. If we are the last ones to hold the shared_ptr, we will delete it. If we are not the last one, we will not delete it.
All three of these pointer options give us tools for deleting the object. References are used to liberate us from any need to be responsible for deletion. In your case, you want a Bar to extend the lifetime of a Foo. This means you must address the deletion problem in some way. You do that with pointers.
Regarding having to check for validity - yes. Pointers give us the power of deletion. Because it can be deleted, it can also be invalid. References do not give us the power of deletion and thus they should always be valid. If you want the power of deletion (which you do in your example), you have to check for validity.
There is a huge caveat to all of this. You can always turn a reference into a pointer and vice-versa. A pointer and a reference are the same thing in the end, but we use them to communicate different things in our code and trying to break these conventions will generally not make your life easier.
I'll also add that your function baz is not indicating any problem with references. You created foo4 on the stack. Creating something on the stack also means it will be destroyed when the stack is popped. The fact that you are using a reference in Bar is irrelevant. If you used a pointer, you would have the same issue. If you want a Foo to last and have a reference or pointer remain valid, it must be allocated somewhere that remains valid for the duration of its usage (heap, higher level stack frame, global memory, etc.).
|
74,582,018
| 74,582,265
|
Ambiguous call when overloaded methods take reverse iterators in arguments
|
I'm trying to write an overloaded method that returns non-const result only when both the object on which it is called is non-const and iterator passed in the argument is non-const.
(Think of it like the standard methods begin() and begin() const that additionally take an iterator argument.)
I made a version for normal iterators with no problems.
However, for some reason, when I'm trying to do the same for reverse iterators, I get a compilation error about an ambiguous function call.
Here's a minimal example:
#include <vector>
class Foo
{
public:
void bar(std::vector<int>::iterator x) {}
void bar(std::vector<int>::const_iterator x) const {}
void baz(std::vector<int>::reverse_iterator x) {}
void baz(std::vector<int>::const_reverse_iterator x) const {}
};
int main()
{
std::vector<int> v;
Foo foo;
foo.bar(v.cbegin()); // OK
foo.baz(v.crbegin()); // ambiguous
}
For some reason it compiles if I remove const from the second method baz.
It also works in C++20 but currently I cannot use that version.
live demo
How can I make the function baz work in analogous way to the function bar?
|
Oh the joys of overloading resolution rules and SFINAE.
The methods are equivalent to free functions:
void bbaz(Foo&,std::vector<int>::reverse_iterator){}
void bbaz(const Foo&,std::vector<int>::const_reverse_iterator){}
and your usage becomes:
int main()
{
std::vector<int> v;
Foo foo;
bbaz(foo,v.crbegin());
}
The arguments do not exactly match either call:
foo is Foo&, not const Foo&
v.crbegin() return vector::const_reverse_iterator which is just a different instantiation of the same std::reverse_iterator template as vector::reverse_iterator.
reverse_iterator->std::reverse_iterator<vector::iterator>
const_reverse_iterator-> std::reverse_iterator<vector::const_iterator>
Cause of ambiguity
Now, the issue is that std::reverse_iterator's ctor is not SFINAE-friendly until C++20:
template< class U >
std::reverse_iterator( const std::reverse_iterator<U>& other );
I.e. there is a viable candidate converting std::reverse_iterator<T> to std::reverse_iterator<U> between any T-U pairs. In this case for T=vector::const_iterator, U=vector::iterator. But of course the template instantiation fails later because it cannot convert const int* to int*.
Since that happens in the template function's body, not the signature, it is too late for SFINAE and overloading considers it a viable candidate function, hence the ambiguity since both calls require one implicit conversion - although only the second one would compile.
This is explained in these answers, making this one essentially a duplicate of that question but it would be IMHO cruel to mark it as such without an explanation which I cannot fit into a comment.
C++20 fixes this omission and SFINAEs that ctor - cppreference:
This overload participates in overload resolution only if U is not the same type as Iter and std::convertible_to<const U&, Iter> is modeled (since C++20)
Solution
As pointed in the comments by @Eljay, forcing const Foo& at the call site is one option, one can use C++17 std::as_const:
#include <utility>
std::as_const(foo).baz(v.crbegin());
Fixing this at definition is more tricky, you could use SFINAE to actually force these overloads but that might be a hassle. @fabian 's solution with adding a third overload without const method qualifier seems easiest to me:
void Foo::baz(std::vector<int>::const_reverse_iterator x) {
return std::as_const(*this).baz(x);
}
It works because now it is a better (exact) match for non-const Foos than the still considered vector::reverse_iterator which would not compile anyway.
|
74,583,017
| 74,588,694
|
I'm using PropertyChanged to update textblock, but when clicked, crashed: Application called an interface that was marshalled for a different thread
|
Now I'm trying to use PropertyChangedEvent to test update the textblock, but when I click, it crashed: WinRT originate error - 0x8001010E : The application called an interface that was marshalled for a different thread.
//in WordArray.cpp
namespace winrt::Lexical_Frequency::implementation
{
WordArray::WordArray(winrt::hstring const& allword) : m_allword{ allword }
{
}
winrt::hstring WordArray::AllWord()
{
return m_allword;
}
void WordArray::AllWord(winrt::hstring const& value)
{
if (m_allword != value)
{
m_allword = value;
m_propertyChanged(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs{ L"AllWord" });
}
}
winrt::event_token WordArray::PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler)
{
return m_propertyChanged.add(handler);
}
void WordArray::PropertyChanged(winrt::event_token const& token)
{
m_propertyChanged.remove(token);
}
}
//in DataPage.xaml.cpp
namespace winrt::Lexical_Frequency::implementation
{
DataPage::DataPage()
{
m_mainviewModel = winrt::make<Lexical_Frequency::implementation::WordArrayViewModel>();
InitializeComponent();
}
void DataPage::ClickHandler(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
{
MainViewModel().WordArray().AllWord(L"xxx");
}
void DataPage::SaveFileButton_Click(IInspectable const&, RoutedEventArgs const&)
{
GetFileNameSave();
}
Lexical_Frequency::WordArrayViewModel DataPage::MainViewModel()
{
return m_mainviewModel;
}
}
Now I'm trying to use MainViewModel().WordArray().AllWord(L"To Kill a Mockingbird"); to test update the textblock, but when I click, it crashed: WinRT originate error - 0x8001010E : The application called an interface that was marshalled for a different thread.
|
You'll frequently encounter this error when dropping code written for Microsoft's "Modern" UI platform (that never got a name) into a WinUI 3 application.
A bit of historic context: Alongside the "Modern" UI platform, Windows 8 introduced a variation of the STA, the Application STA (wildly undocumented1, no surprises there). Windows 10 finally exposed the "Modern" UI platform (still unnamed) through Windows Runtime types under the Windows.UI.Xaml namespace. (Most) of those types will want to be accessed from the ASTA (which is apparently enforced at run time, evidenced by the RPC_E_WRONG_THREAD "exception").
Fast forward to today, the "Modern" UI platform mostly gone, together with its clean design language. The UWP sharing a coffin with Windows 10 Mobile, and the ASTA history, too. WinUI 3 has come full circle, ultimately supporting the classic Desktop application model only, back to the classic COM threading architecture: Zero or one MTA, and any number of STAs.
No ASTA, anywhere.
After that bit of a detour it should be easy to understand, what the issue is: The code is trying to access objects designed for the ASTA from a regular STA thread.
The solution is pretty straight forward, too: Replace all types from the Windows.UI.Xaml namespace with their WinUI 3 twins from the Microsoft.UI.Xaml namespace:
In the IDL for WordArray make sure to derive from Microsoft.UI.Xaml.Data.INotifyPropertyChanged rather than Windows.UI.Xaml.Data.INotifyPropertyChanged
Change the type parameter for the winrt::event class template from Windows::UI::Xaml::Data::PropertyChangedEventHandler to Microsoft::UI::Xaml::Data::PropertyChangedEventHandler and update the PropertyChanged implementations to use this type as well
Construct a Microsoft::UI::Xaml::Data::PropertyChangedEventArgs object instead of a Windows::UI::Xaml::Data::PropertyChangedEventArgs object when raising events
To do this you will also have to update the respective #include directives that reference <winrt/Windows.UI.Xaml. ... .h> header files to use <winrt/Microsoft.UI.Xaml. ... .h> instead, and replace any using namespace directives accordingly.
1 Raymond Chen explains what problem it is trying to solve in his blog entry What is so special about the Application STA?.
|
74,583,083
| 74,585,146
|
Awaiting a predicate with C++20 coroutines
|
We started using the modern C++20 coroutines on our project recently. There is a list of coroutines referred to as Tasks in the Executor, which steps through them one by one resuming them. All of this is done on a single thread. Sometimes coroutines need not to be resumed until some predicate is satisfied. In some cases it may be satisfied by another coroutine, which makes suspending for later execution just fine.
Here are the types in use:
struct Task : std::coroutine_handle<task_promise_t> {
using promise_type = task_promise_t;
};
struct task_promise_t {
Task get_return_object() { return {Task::from_promise(*this)}; }
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
struct Executor {
/* snip */
void enqueue_task(Task &&task) { tasks.push_back(task); }
void tick() {
while (!tasks.empty())
this->step();
}
void step() {
Task task = std::move(tasks.front());
tasks.pop_front();
task.resume();
if (!task.done())
tasks.push_back(task);
}
std::deque<Task> tasks;
/* snip */
}
Example of how I expect it to be used:
auto exec = Executor();
static bool global_predicate = false;
exec.enqueue_task([](Executor* exec) -> Task {
co_await WaitFor(/* bool(void) */ []() -> bool { return global_predicate; });
/* prerequisite satisfied, other logic goes here */
std::cout << "Hello, world" << std::endl;
}(&exec));
exec.step(); // no output, predicate false
exec.step(); // no output, predicate false
global_predicate = true;
exec.step(); // predicate true, "Hello, world!", coroutine is also done
I did manage to get the implementation going, this seems to work fine.
static bool example_global_predicate;
auto coro = []() -> Task {
while (!example_global_predicate)
co_await std::suspend_always();
/* example_global_predicate is now true, do stuff */
co_return;
}();
But I can't a good way to generalize and abstract it into it's own class. How would one go about it? I would expect to see that functionality in the standard library, but seeing how customizable the coroutines are I doubt there is a way to implement a one-size-fits-all solution.
|
The "await" style of coroutines is intended for doing asynchronous processing in a way that mirrors the synchronous equivalent. In sinchronous code, you might write:
int func(float f)
{
auto value = compute_stuff(f);
auto val2 = compute_more_stuff(value, 23);
return val2 + value;
}
If one or both of these functions is asychronous, you would rewrite it as follows (assuming the presence of appropriate co_await machinery):
task<int> func(float f)
{
auto value = compute_stuff(f);
auto val2 = co_await async_compute_more_stuff(value, 23);
co_return val2 + value;
}
It's structurally the same code except that in one case, func will halt halfway through until async_compute_more_stuff has finished its computation, then be resumed and return its value through Task<int>. The async nature of the code is as implicit as possible; it largely looks like synchronous code.
If you already have some extant async process, and you just want a function to get called when that process concludes, and there is no direct relationship between them, you don't need a coroutine. This code:
static atomic<bool> example_global_predicate;
auto coro = []() -> Task {
while (!example_global_predicate)
co_await std::suspend_always();
/* example_global_predicate is now true, do stuff */
co_return;
}();
Is not meaningfully different from this:
static atomic<bool> example_global_predicate;
register_polling_task([]() -> bool
{
if(!example_global_predicate)
return false;
/* example_global_predicate is now true, do stuff */
return true;
});
register_polling_task represents some global construct which will at regular intervals call your function until it returns true, at which point it assumes that it has done its job and removes the task. Your coroutine version might hide this global construct, but it still needs to be there because somebody has to wake the coroutine up.
Overall, this is not an async circumstance where using coroutines buys you anything in particular.
However, it could still be theoretically useful to attach coroutine resumption to a polling task. The most reasonable way to do this is to put the polling in a task outside of a coroutine. That is, coroutines shouldn't poll for the global state; that's someone else's job.
A coroutine would do something like co_await PollingTask(). This hands the coroutine_handle off to the system that polls the global state. When that global state enters the correct state, it will resume that handle. And when executing the co_await expression, it should also check the state then, so that if the state is already signaled, it should just not halt the coroutine's execution.
PollingTask() would return an awaitable that has all of this machinery built into it.
|
74,583,288
| 74,583,375
|
Cannot include .cpp and .h files in Visual Studio 2022
|
I have created a class Dialog and separated it into .cpp (Dialog.cpp) and .h (Dialog.h).
My cpp file looks like this:
#include "Dialog.h"
#include <iostream>
using namespace std;
namespace Model1
{
void Dialog::initialize ()
{
cout << "initialization";
}
}
And here is my h file:
using namespace std;
class Dialog
{
public:
void initialize ();
};
When I debug the code in visual studio 2022 I get this:
cannot open source file "Dialog.h"
name followed by '::' must be a class or namespace name
Cannot open include file: 'Dialog.h': No such file or directory ConsoleApplication1
symbol cannot be defined within namespace 'Model1' ConsoleApplication1
When I changed my header file to
using namespace std;
namespace Model1 {
class Dialog
{
public:
void initialize();
};
}
And now I have these errors:
cannot open source file "Dialog.h"
name followed by '::' must be a class or namespace name
Cannot open include file: 'Dialog.h': No such file or directory
How can I fix the problem?
|
The problem is that in the header file you've defined class Dialog in global namespace while you're trying to define the member function Dialog::initialize() in Model1 namespace.
This will not work because the out-of-class definition for the member function of a class must be in the same namespace in which the containing class is.
Thus, to solve this you can either define the class(in the header) in namespace Model1 or implement the member function(in the source file) in global namespace. Both these methods are shown below:
Method 1
Here we define the class in namespace Model1 in the header and leave the source file unchanged.
dialog.h
namespace Model1 //added this namepspace here
{
class Dialog
{
public:
void initialize ();
};
}
Working demo 1
Method 2
Here we define the member function in global namespace in source file and leave the header file unchanged.
dialog.cpp
#include "Dialog.h"
void Dialog::initialize ()
{
cout << "initialization";
}
Working demo 2
|
74,583,543
| 74,585,508
|
What is the expected lifetime of lpszClassName in WNDCLASS(EX)?
|
When creating a WNDCLASS(EX) in C++, one might do as follows:
WNDCLASSEX wndClass {};
wndClass.lpszClassName = "MyWndClass";
The data backed by the string literal is available for the whole program's lifetime.
So what if the data was only available during the invocation of RegisterClassEx?
{
char className[] = "MyWndClass";
WNDCLASSEX wndClass {};
wndClass.lpszClassName = className;
// other things...
RegisterClassEx(&wndClass);
}
HWND window = CreateWindowEx(0, "MyWndClass", /* other parameters... */);
Would this still work?
|
So what if the data was only available during the invocation of RegisterClassEx? Would this still work?
Yes, it is perfectly fine. The values that you register are copied by the OS until the class is unregistered at a later time. The actual WNDCLASSEX instance itself is no longer needed once RegisterClassEx() returns.
So, what is important is that the class name value that you register must match the class name value that you pass to CreateWindowEx(). They do not need to be pointing at the same memory address.
|
74,584,065
| 74,584,290
|
Benefit of promise/future compared to return by reference
|
I'm new to C++ threads concept and is trying to comprehend the benefit of the promise/future abstraction. With promise and future, I understand that it allows an async function to "return" like a regular subroutine does. However, it is not clear to me what it offers beyond using referenced argument to do the same thing.
#include <iostream>
#include <thread>
void f(int& x)
{
x += 1;
}
int main()
{
int a = 1;
std::thread t(f, std::ref(a));
t.join();
std::cout << a << '\n';
}
In the above example, I make the function f() "returns" the integer by passing a reference. This is safe as I only grab the value after thread is join. Now is there any benefit from using promise/future that the above paradigm cannot do?
|
This is safe as I only grab the value after thread is join
Well, that's kind of the point, isn't it? Is it really "safe" if all it takes for some code to become "unsafe" is for someone to inadvertently use the variable at the wrong time? If the difference between "safe" and "completely broken" is changing the order of two lines, and no compiler can catch the problem, is it really "safe?"
If you invoke an asynchronous action, the primary reason you did that was because you wanted to do something else while that action is going on. So leaving the current stack frame is kind of the point. Most code does not look like your simplistic example.
Your example is only "safe" because it is simplistic. Introduce any complexity, and it becomes increasingly unsafe.
Did the thread raise an exception instead of returning a valid value? Did you make sure that the lifetime of the object being referenced persists until the thread is finished writing to it? If you want the thread to be able to finish with a task and go do a different one (instead of incurring the cost of creating a new std::thread every time you want to do an async process), how do you communicate when the value is ready to the outside world?
promise/future has answers to all of these questions. It has an explicit mechanism for sheparding exceptions across threads. The lifetime of the shepherded object is rigidly controlled, so that simply can't break. Each promise/future is independent and thus a thread could have many of them, and any future can tell when the promised value is ready. Etc.
In summary, promise/future are tools that are safe at scale. Yours is increasingly less safe the more complexity is introduced.
|
74,584,691
| 74,584,834
|
How to turn verilog gate-level code to C++ tree representation?
|
module circuit(input a1, b1, d1, d2, output OUT);
wire a, b, c, d, e, f;
NOT A(a, a1);
NOT B(b, b1);
NOT C(c, a);
NAND D(d, d1, d2);
NAND E(e, b, c);
NAND F(f, d, e);
NOT G(OUT, f);
endmodule
Is there any method that is able to convert the above code to tree(in the attached the image shows the tree I want to convert to)?
I don't know if there's efficient way to construct the tree, and I have searched on the net, but didn't find relative ideas.
|
The Verilog syntax looks similar to C++ so you could try to shoehorn it into proper C++ although I doubt it would be a good idea :-D :
#include <vector>
#include <iostream>
enum class Op {
NOT, NAND
};
struct wire {
std::vector<wire*> inputs;
Op op;
bool constantValue = false;
bool evaluate() {
if (inputs.empty()) {
return constantValue;
} else if (op == Op::NOT) {
return !inputs[0]->evaluate();
} else if (op == Op::NAND) {
return !(inputs[0]->evaluate() && inputs[1]->evaluate());
} else {
return false;
}
}
};
class NOT {
public:
NOT(wire& dst, wire& src) {
dst.op = Op::NOT;
dst.inputs.push_back(&src);
}
};
class NAND {
public:
NAND(wire& dst, wire& a, wire& b) {
dst.op = Op::NAND;
dst.inputs.push_back(&a);
dst.inputs.push_back(&b);
}
};
#define module
#define endmodule
#define output
#define input
#define circuit(...) wire __VA_ARGS__
and then just insert the code in a C++ function.
int main()
{
module circuit(input a1, b1, d1, d2, output OUT);
wire a, b, c, d, e, f;
NOT A(a, a1);
NOT B(b, b1);
NOT C(c, a);
NAND D(d, d1, d2);
NAND E(e, b, c);
NAND F(f, d, e);
NOT G(OUT, f);
endmodule
std::cout << "The result of OUT = " << OUT.evaluate() << std::endl;
return 0;
}
Instances of the wire class will point at other wire instances from the inputs member variable, thereby forming a "tree". Is that what you ask for?
|
74,584,783
| 74,584,910
|
Cannot use BOOST_STRONG_TYPEDEF with std::string
|
I'm using Boost's (v 1.71) strong typedef to differentiate a std::string but I'm having a few problems.
BOOST_STRONG_TYPEDEF(std::string, StrongString);
First, I would like to use StrongString with unordered_map, but when I overload the hash:
std::unordered_map<StrongString, int, std::hash<StrongString>> umap;
I get the compiler error:
/usr/include/c++/11/bits/hashtable_policy.h:1126:7: error: use of deleted function ‘std::hash<StrongString>::~hash()’
Second, previously I was using string concatenation and invoking string::length():
std::string s;
s += "c";
s.length();
However, when I now do:
StrongString s;
s += "c";
s.length();
I get:
error: no match for ‘operator+=’ (operand types are ‘StrongString’ and ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’})
error: StrongString has no member named ‘length’
I can fix the compiler errors by using s.t to access the internal t member of Boost Strong Typedef, but this cannot be the correct way to use it.
|
The aim of BOOST_STRONG_TYPEDEF macro is generating a class that wraps and instance of a primitive type and provides appropriate conversion operators in order to make the new type substitutable for the one that it wraps.
std::string is not a primitive type.
The possible impl:
struct StrongString {
StrongString(const std::string& s) : wrapped_(s) {}
operator std::string&() { return wrapped_; }
private:
std::string wrapped_;
};
As you can see, StrongString does not have member functions, thus s.length() and += do not work, but this might work: std::size(s) and s = std::string(s) + "c".
std::hash is not defined for StrongString.
|
74,585,594
| 74,585,998
|
partial_sum() position of previous
|
Using partial_sum(), I am trying to get the position from previous during the recurrence. I don't understand the result. I was expecting to get :
recurrence i=0
recurrence i=1
...
As the recurrence unfolds. But I am getting :
recurrence i=-48115006
recurrence i=-48115006
...
What am doing wrong ?
#include <vector>
#include <algorithm>
#include <numeric>
#include <stdio.h>
using namespace std;
int main()
{
const int n=15;
vector<vector<int> > vv(n+1);
vv[0]={42};
auto next=[&](const vector<int>& previous, const vector<int>&){
const int i = &previous - &vv[0];
printf("recurrence i=%d\n", i);
fflush(stdout);
vector<int> v;
return v;
};
partial_sum(vv.begin(), vv.end(), vv.begin(), next);
}
|
The implementation for partial_sum that you are using is probably similar to the one described in cppreference, Possible implementation, Second version:
template<class InputIt, class OutputIt, class BinaryOperation>
constexpr // since C++20
OutputIt partial_sum(InputIt first, InputIt last,
OutputIt d_first, BinaryOperation op)
{
if (first == last)
return d_first;
typename std::iterator_traits<InputIt>::value_type sum = *first;
*d_first = sum;
while (++first != last)
{
sum = op(std::move(sum), *first); // std::move since C++20
*++d_first = sum;
}
return ++d_first;
}
That being the case, the first argument that partial_sum passes to op (the binary operation, next in your code) is fix: it's a reference to an accumulator. It is the second argument the one that varies: it's a reference to the current element in each iteration (starting at the second element). But, in your example, you don't use this second argument to set i. Instead, you always use &vv[0], which is also a fix value (unless vv changes in size, which is not the case). So it's expected that you are always printing the same value: the difference of two fix addresses.
You can see it working here with some more debugging output.
|
74,585,610
| 74,606,905
|
Strange behavior from decrypt EVP envelope_open()
|
I have a simple program that encrypts files in a directory. I can iterate through and everything works perfectly. This is using pub/priv key pair. When decrypting one file at a time, it works as it should. However, if there are multiple files in a directory, or even if I put the filenames in a vector and fopen them for reading/writing respectively, it ONLY decrypts the LAST file in the vector/directory. How is this even possible? It fails on everyone of them on OpenFinal(). Here is the function and heart of the program. Everything else is solid. As stated, it works as a standalone program if I just decrypt one file manually or if there is just ONE file in the directory or vector.
Any help would be appreciated. This makes no sense at all. It seems like an implementation issue on their end.
void handleErrors(void)
{
// perror("Error: ");
ERR_print_errors_fp(stderr);
abort();
}
int envelope_open(EVP_PKEY *priv_key, unsigned char *ciphertext,
int ciphertext_len, unsigned char *encrypted_key,
int encrypted_key_len, unsigned char *iv,
unsigned char **plaintext, int *plaintext_len)
{
EVP_CIPHER_CTX *ctx;
int len = 0, ret = 0;
unsigned char *tmpptxt = NULL;
if((ctx = EVP_CIPHER_CTX_new()) == NULL)
return 0;
if ((tmpptxt = (unsigned char*)malloc(ciphertext_len)) == NULL)
{
printf("tmptxt error!\n");
handleErrors();
}
if(EVP_OpenInit(ctx, EVP_aes_256_cbc(), encrypted_key, encrypted_key_len,
iv, priv_key) != 1)
{
printf("OpenInit error\n");
handleErrors();
}
if(EVP_OpenUpdate(ctx, tmpptxt, &len, ciphertext, ciphertext_len) != 1)
{
printf("OpenUpdate error\n");
handleErrors();
}
*plaintext_len = len;
if(EVP_OpenFinal(ctx, tmpptxt + len, &len) != 1)
{
printf("OpenFinal error\n");
handleErrors();
}
*plaintext_len += len;
*plaintext = tmpptxt;
tmpptxt = NULL;
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
free(tmpptxt);
return ret;
}
|
I was overwriting the key and iv returned from envelope_seal(). I looked over the fact it was unique. Each file must have this key and iv along with the private key and passphrase on the key to be able to decrypt a file. So this is definitely secure ... until someone cracks AES 256 of course.
|
74,586,138
| 74,586,221
|
Simplifying rationals during assignment
|
I'm trying to assign the numerator and denominator values to a rational object, but need to reduce them to their smallest corresponding numbers. Say for example I input 10 for the numerator, and 20 for the denominator, I need them reduced down to 1/2. Below is my constructor that takes a numerator and denominator and assigns them to the objects member variables.
Rational::Rational(int num, int denom) {
try {
this->num = num / gcd(num, denom);
this->denom = denom / gcd(num, denom);
}
catch(RationalException ex) {
cout << "Cannot set denominator to 0" << endl;
}
}
The gcd function is imported from an external .h file which is supposed to be used in the reduction process. But this code when run doesn't assign the reduced values into the member variables.
I've tried this alternative approach:
Rational::Rational(int num, int denom) {
try {
this->num = num;
this->denom = denom;
num /= gcd(this->getNumerator(), this->getDenominator());
denom /= gcd(this->getNumerator(), this->getDenominator());
}
catch(RationalException ex) {
cout << "Cannot set denominator to 0" << endl;
}
}
and it also doesn't reduce the object, not sure how to approach this outside of creating an external function but I won't be able to manipulate the member variables as the function will be considered nonmember.
Below is the code for the gcd function
#ifndef GCD_H
#define GCD_H
inline int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);}
#endif
Edit: Added gcd code
|
SUGGESTION:
Save the return value of "gcd()" into a temp variable
Step through the debugger to ensure each of the three variables are updated correctly:
Rational::Rational(int num, int denom) {
try {
int g = gcd(num, denom); // <-- Set bkpt here, step through in debugger
this->num = num / g;
this->denom = denom / g;
}
catch(RationalException ex) {
cout << "Cannot set denominator to 0" << endl;
}
}
|
74,586,333
| 74,638,533
|
(SOLVED) SFML-Audio LNK2001 error, linking error, I linked all the libraries but it doesn't work
|
when I try to use the SFML-Audio library, I get this error:
Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: __cdecl sf::SoundBuffer::~SoundBuffer(void)" (__imp_??1SoundBuffer@sf@@QEAA@XZ) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: bool __cdecl sf::SoundBuffer::loadFromFile(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_?loadFromFile@SoundBuffer@sf@@QEAA_NAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: __cdecl sf::SoundBuffer::SoundBuffer(void)" (__imp_??0SoundBuffer@sf@@QEAA@XZ) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: void __cdecl sf::Sound::setBuffer(class sf::SoundBuffer const &)" (__imp_?setBuffer@Sound@sf@@QEAAXAEBVSoundBuffer@2@@Z) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: virtual void __cdecl sf::Sound::play(void)" (__imp_?play@Sound@sf@@UEAAXXZ) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: virtual __cdecl sf::Sound::~Sound(void)" (__imp_??1Sound@sf@@UEAA@XZ) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: __cdecl sf::Sound::Sound(void)" (__imp_??0Sound@sf@@QEAA@XZ) War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\main.obj 1
Error LNK1120 7 unresolved externals War-Tech C:\Users\domon\Documents\myfiless\MyProjects\War-Tech\x64\Release\War-Tech.exe 1
My included libraries:
sfml-graphics.lib
sfml-window.lib
sfml-system.lib
sfml-audio-s.lib
sfml-system-s.lib
sfml-audio-s-d.lib
openal32.lib
opengl32.lib
winmm.lib
Please help me, I've been struggling with this problem for a long time, I can't seem to get the sound to play in the game.SFML itself works correctly, but for some reason SFML-Audio does not work for me :(
Sound code:
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("main.wav"))
{
std::cout << "ERROR" << std::endl;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();
|
Just include sfml-audio.lib instead of sfml-audio-d.lib
|
74,586,572
| 74,586,756
|
Is it legal to initialize a POD member of a base class before its constructor is called when it's not going to be initialized by it?
|
In the following code:
class Base
{
protected:
int v;
Base( void * ) { /* doesn't touch v at any point */ }
};
class Derived: public Base
{
public:
// Changes Base::v before calling Base::Base
Derived(): Base( ( (void )( v = 42 ), nullptr ) ) {}
};
Derived::Derived changes a POD member variable Base::v before calling Base::Base. It's known that Base::Base isn't touching v at all. The goal is to have Base::v initialized to 42 after leaving Derived::Derived.
While this should technically work (Base::v already has space allocated for it in memory when Derived::Derived is called, and no code in Base::Base is ever touching it), the question is, is this legal? More specifically, does this at any point imply any undefined behavior, which compilers famously like to optimize-out?
Note that this question is purely for language lawyers. I'm not asking whether there are better ways of doing this (in most cases there obviously are), and I'm not trying to solve any specific problem other than trying to learn more about C++ from the point of view of the C++ standard.
|
No, that is not valid:
class.cdtor/1
For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.
Also see the example below the above paragraph:
struct W { int j; };
struct X : public virtual W { };
struct Y {
int* p;
X x;
Y() : p(&x.j) { // undefined, x is not yet constructed
}
};
|
74,586,965
| 74,604,313
|
How to get around not passing a copyable object to the MATCHER within MOCK_METHOD?
|
I am attempting at having a MOCK_METHOD BarClass::Bar throw an exception however I seem to be running into a following error
error: call to implicitly-deleted copy constructor of 'FooMock'
And it's probably happening at the == inside MATCHER_P.
It seems as though MOCK_METHOD creates a data member that's not copyable however that leaves me with an option to use a pointer, which I can't really use since BarClass::Bar takes fooMock as a reference.
Is there a way to pass a dereferenced object to Matcher?
class FooClass
{
public:
virtual void Foo() const{}
};
class FooMock : public FooClass
{
public:
MOCK_METHOD(void, Foo, (), (const override));
};
struct BarClass
{
void Bar(const FooMock& fooMock) {}
};
class BarMock : public BarClass
{
public:
MOCK_METHOD(void, Bar, (FooMock& fooMock), (const override));
};
MATCHER_P(Matcher, fooMock, "")
{
return arg == fooMock;
}
ACTION(MyThrowException)
{
throw std::invalid_argument("Some exception thrown!");
}
TEST(UtClass, Test)
{
auto fooMock = std::make_shared<FooMock>();
BarMock barMock;
EXPECT_CALL(barMock, Bar (Matcher(*fooMock))) // <-- problem here
.Times(1)
.WillRepeatedly(MyThrowException());
barMock.Bar(*fooMock); // should throw
}
https://godbolt.org/z/rEGzxjoaY
|
Arguments to matchers are passed by copy per default. This is somewhat documented here. You can fix this by wrapping your argument in std::ref() or better std::cref() so you can't accidentally modify it:
EXPECT_CALL(barMock, Bar (Matcher(std::cref(*fooMock))))
.Times(1)
.WillRepeatedly(MyThrowException());
https://godbolt.org/z/1r695brK4
|
74,587,129
| 74,587,291
|
How to convert std::function to function pointer?
|
I need to use std::qsort() to sort an arry of nd-Point. But I get an error:
no known conversion from 'function<int (const void *, const void )>' to '__compar_fn_t' (aka 'int ()(const void *, const void *)')`
How to solve it, or sort it by dir in another method?
#include <iostream>
#include <functional>
int d, n;
struct Point {
int *x;
Point() : x(new int[d]) {};
};
std::function<int(const void *, const void *)> make_cmp(int dir) {
return [dir](const void *a, const void *b)->int {
auto a_ = (Point *)a;
auto b_ = (Point *)b;
return a_->x[dir] - b_->x[dir];
};
}
void sort_points(Point *value, int length, int dir) {
std::qsort(value, length, sizeof(Point), make_cmp(dir));
}
|
If you must use std::qsort then you are basically writing in C, not C++. This might be one of the few situations where a global variable is the least bad approach.
static thread_local int dir;
int cmp(const void *a, const void *b) {
auto a_ = (const Point *)a;
auto b_ = (const Point *)b;
return a_->x[dir] - b_->x[dir]; // beware of overflow
}
void sort_points(Point *value, int length, int d) {
dir = d;
std::qsort(value, length, sizeof(Point), cmp);
}
If this will never be called from more than one thread at a time, then you can drop the thread_local.
(Note that if the values might exceed the range [INT_MIN/2, INT_MAX/2] then you need to replace the subtraction with something that isn't vulnerable to overflow.)
|
74,587,411
| 74,587,437
|
Why static global variables initialized to zero, but static member variable in class not initialized?
|
static int counter // will initalized to 0
but if I make that variable inside a class, it's not initialized and I have to initialize it outside of class
class Test {
static int counter; // not initialized
};
...
Test::counter = 0;
I know the static variables are stored in BSS segment in memory and initialized by default to 0, so why is it when I make a static in class not initialized?
|
Why static global variables initialized to zero, but static member variable in class not initialized?
Because the declaration for a non-inline static data member inside the class is not a definition.
This can be seen from static data member documentation:
The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member. The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared:
Also the out of class definition Test::counter = 0; is incorrect. It should instead be int Test::counter = 0;
|
74,587,807
| 74,588,550
|
Cmake custom command conditional on build
|
I have an issue with cmake. Iv'e tried seraching all online but no answers and Ive tried many possible solutions and nothing has worked.
Im trying to copy a dll file into the executable directory automatically after the build and only if the dll file exists.
code Ive tried:
1.
add_custom_command(TARGET Game PRE_BUILD COMMAND -E
if(EXISTS "${PROJECT_SOURCE_DIR}/build/vendor/assimp/bin/$<CONFIGURATION>/assimp-vc143-mtd.dll")
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${PROJECT_SOURCE_DIR}/build/vendor/assimp/bin/$<CONFIGURATION>/assimp-vc143-mtd.dll" $<TARGET_FILE_DIR:Game>
endif()
)
Errors: bunch of visual studio errors. you can't nest Cmake custom commands
Ive also tried
in CMakeLists.txt
add_custom_command(TARGET Game PRE_BUILD COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/checkFile.cmake)
in checkFile.cmake
if(EXISTS "${PROJECT_SOURCE_DIR}/build/vendor/assimp/bin/$<CONFIGURATION>/assimp-vc143-mtd.dll")
add_custom_command(TARGET Game POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${PROJECT_SOURCE_DIR}/build/vendor/assimp/bin/$<CONFIGURATION>/assimp-vc143-mtd.dll" $<TARGET_FILE_DIR:Game>)
endif()
Errors: nothing it silently fails
Also tried in checkFile.cmake
add_custom_command(TARGET Game POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${PROJECT_SOURCE_DIR}/build/vendor/assimp/bin/$<CONFIGURATION>/assimp-vc143-mtd.dll" $<TARGET_FILE_DIR:Game>)
Errors: add_custom_command command is not scriptable
Nothing I try actually works. Is this even possible for Cmake?
As for why I'm doing this in the first place. this library I'm trying to use sometimes decides to use dynamic library despite being set to static only. On Linux it does static every time but on windows it's kind of random maybe.
Iv'e searched online but found nothing which can help solve this issue. There are two problems.
This dll copying needs to be done after the build is complete and it needs to do it automatically, so this whole setup must be invoked by a custom command and needs to run a custom command within a custom command which is possible, but Cmake says you can't do that see error 3.
Can anyone help me with this?
|
in checkFile.cmake
Do not add_custom_command in the script. It's in script mode, not cmake configuration. Actually copy the file. In checkFile.cmake:
if(EXISTS "${FROM}")
FILE(COPY "${FROM}" "${TO}")
endif()
and pass variabels:
add_custom_command(TARGET Game POST_BUILD
COMMAND ${CMAKE_COMMAND}
-P ${CMAKE_CURRENT_SOURCE_DIR}/checkFile.cmake
-D FROM="${PROJECT_SOURCE_DIR}/build/vendor/assimp/bin/$CONFIGURATION/assimp-vc143-mtd.dll"
-D TO=<TARGET_FILE_DIR:game>
)
|
74,587,853
| 74,588,131
|
Binary files get corrupted while unzipping with libzip
|
I was required to unzip .zip files in my Qt project. So I installed libzip. I wrote a function to unzip a .zip file given its location and destination directory path. The function is correctly able to unzip plain text files (like .json, .txt, and others) but it always corrupts any type of binary files like PNGs or MP4s. Here is the function I wrote:
void Converter::unzipFile(QString srcFilePath_, QString destinationDirectoryPath_) {
std::string srcFilePath = srcFilePath_.toStdString();
std::string destinationDirectoryPath = destinationDirectoryPath_.toStdString();
char bufferStr[100];
int error = 0;
int fileHandle;
struct zip *zipArchive = zip_open(srcFilePath.c_str(), 0, &error);
struct zip_file *zippedFile;
struct zip_stat zippedFileStats;
if (not QDir().exists(destinationDirectoryPath_)) {
QDir().mkpath(destinationDirectoryPath_);
}
if (zipArchive == NULL) {
zip_error_to_str(bufferStr, sizeof(bufferStr), error, errno);
std::cout << "[ERROR] Can not open the zip file: " << error << ":\n" << bufferStr;
}
for (int index = 0; index < zip_get_num_entries(zipArchive, 0); index++) {
if (zip_stat_index(zipArchive, index, 0, &zippedFileStats) == 0) {
int zipFileNameLength = strlen(zippedFileStats.name);
if (zippedFileStats.name[zipFileNameLength - 1] == '/') { // i.e. folder
QDir().mkpath(destinationDirectoryPath_ + "/" + zippedFileStats.name);
} else { // i.e. file
zippedFile = zip_fopen_index(zipArchive, index, 0);
if (zippedFile == NULL) {
qDebug() << "[ERROR] Can not open the file in zip archive.";
continue;
}
fileHandle = open((destinationDirectoryPath + "/" + zippedFileStats.name).c_str(), O_RDWR | O_TRUNC | O_CREAT, 0644);
if (fileHandle < 0) {
qDebug() << "[ERROR] Can not create the file (into which zipped data is to be extracted).";
continue;
}
int totalFileDataLength = 0;
while (totalFileDataLength != (long long) zippedFileStats.size) {
int fileDataLength = zip_fread(zippedFile, bufferStr, 100);
if (fileDataLength < 0) {
qDebug() << "[ERROR] Can not read the zipped file.";
exit(1);
}
write(fileHandle, bufferStr, fileDataLength);
totalFileDataLength += fileDataLength;
}
close(fileHandle);
zip_fclose(zippedFile);
}
} else {
qDebug() << "IDK what is here .";
}
}
if (zip_close(zipArchive) == -1) {
qDebug() << "[ERROR] Cannot close the zip file.";
}
}
NOTE: Everything related to Qt works, I have checked all the variables and made sure that they have the right path values. Plain text files get unzipped easily. This problem is only with binary files.
NOTE: I have tried all relevant solutions on the internet but nothing worked so this question is not a duplicate.
What do I do? Any help will be appreiciated.
|
Instead of this:
int totalFileDataLength = 0;
while (totalFileDataLength != (long long) zippedFileStats.size) {
int fileDataLength = zip_fread(zippedFile, bufferStr, 100);
This:
zip_uint64_t totalFileDataLength = 0;
while (totalFileDataLength != zippedFileStats.size) {
zip_int64_t fileDataLength = zip_fread(zippedFile, bufferStr, 100);
I'm not sure if that is your bug, but without the above change, you'll have an issue for any file larger than 2GB. That could result in an infinite loop or truncated file. Since write expects a size_t parameter (which can be 32-bit or 64-bit), you can safely cast if the compiler complains:
write(fileHandle, bufferStr, (size_t)fileDataLength);
Update
You need to bail out of the loop when zip_fread returns zero. Let's update the entire loop:
while (true) {
zip_int64_t fileDataLength = zip_fread(zippedFile, bufferStr, 100);
if (fileDataLength == 0) {
break; // end of file
}
if (fileDataLength < 0) {
qDebug() << "[ERROR] Can not read the zipped file.";
exit(1);
}
write(fileHandle, bufferStr, (size_t)fileDataLength);
}
Final Update
Windows needs you to pass O_BINARY or (_O_BINARY) into the open call.
fileHandle = open((destinationDirectoryPath + "/" + zippedFileStats.name).c_str(), O_RDWR | O_TRUNC | O_CREAT | O_BINARY, 0644);
|
74,587,930
| 74,587,950
|
Storing multiple strings in nested structure
|
I have 2 structures named Phone and Patient, respectively:
struct Phone{
char description[4];
char number[10];
};
struct Patient{
int id;
char name[15];
struct Phone phone;
};
Now, on creating a patient's array like:
struct Patient patient = [
{1024, "Shaggy Yanson", {"CELL","3048005191"} },
]
Upon printing the phone description value, I get the output as CELL3048005191.
NOTE: I cannot change the array
I want to know what is causing the problem. Is it the structure definition?
|
Yes it is. The problem is that C-style strings require one extra character to store a nul terminator. This is the character '\0' which is placed at the end of every C-style string. So, to store a string like "CELL" requires an array of size 5, not 4.
Of course, you can still store the 4 characters 'C', 'E', 'L' 'L' in an array of size 4. It's just that, then it's no longer a C-style string, because it no longer has a nul terminator. If this is what you want to do, then you will have to take special measures when you process the data (like, when you print it, for example).
|
74,588,501
| 74,588,733
|
Sorting two arrays using C++23 zip view
|
There is a rather typical task of sorting two arrays simultaneously, assuming that same indexed elements of the arrays form virtual pairs, which are sorted. Such questions appear at least 10 years ago: boost zip_iterator and std::sort
Now this task can be solved using range-v3 library:
#include <array>
#include <range/v3/all.hpp>
int main() {
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
ranges::sort( ranges::views::zip( x, y ) );
// here x = {1,2,3,4}, y={'D','B','A','C'}
}
Online demo: https://gcc.godbolt.org/z/WGo4vGsx5
In C++23 std::ranges::zip_view appears, and my expectation was that the same program can be written using the standard library only:
#include <array>
#include <ranges>
#include <algorithm>
int main() {
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
std::ranges::sort( std::views::zip( x, y ) );
}
Unfortunately, it results in long compilation errors. E.g. in GCC:
...
/opt/compiler-explorer/gcc-trunk-20221127/include/c++/13.0.0/bits/ranges_algo.h:54:31: error: no matching function for call to '__invoke(std::ranges::less&, std::pair<int, char>&, std::pair<int&, char&>)'
54 | return std::__invoke(__comp,
| ~~~~~~~~~~~~~^~~~~~~~
55 | std::__invoke(__proj, std::forward<_TL>(__lhs)),
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56 | std::__invoke(__proj, std::forward<_TR>(__rhs)));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
Online demo: https://gcc.godbolt.org/z/47xrzM6ch
Is it just because the implementations are not mature enough yet, or zip view in C++23 will not help to sort two array?
|
At least the trunk version of libc++ (llvm) supports this:
std::ranges::sort(std::views::zip(x, y), [](auto&& a, auto&& b) {
return std::tie(std::get<0>(a), std::get<1>(a)) <
std::tie(std::get<0>(b), std::get<1>(b));
});
Demo
If you use three ranges instead of two, it works without having to supply a user-defined comparator function:
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
auto z = std::array{"Z", "Y", "X", "W"};
std::ranges::sort(std::views::zip(x, y, z));
Demo
I assume the version that zips two ranges will not need a user-defined comparator function when fully implemented.
|
74,588,869
| 74,593,670
|
What is decl-reachable in C++ 20?
|
§10.4/3 gives all the possible situations of decl-reachable in detail. However, I can't fully understand it. Consider the example described in §10.4/6:
Source file "foo.h":
namespace N {
struct X {};
int d();
int e();
inline int f(X, int = d()) { return e(); }
int g(X);
int h(X);
}
Module M interface:
module;
#include "foo.h"
export module M;
template<typename T> int use_f() {
N::X x; // N::X, N, and :: are decl-reachable from use_f
return f(x, 123); // N::f is decl-reachable from use_f,
// N::e is indirectly decl-reachable from use_f
// because it is decl-reachable from N::f, and
// N::d is decl-reachable from use_f
// because it is decl-reachable from N::f
// even though it is not used in this call
}
template<typename T> int use_g() {
N::X x; // N::X, N, and :: are decl-reachable from use_g
return g((T(), x)); // N::g is not decl-reachable from use_g
}
template<typename T> int use_h() {
N::X x; // N::X, N, and :: are decl-reachable from use_h
return h((T(), x)); // N::h is not decl-reachable from use_h, but
// N::h is decl-reachable from use_h<int>
}
int k = use_h<int>();
// use_h<int> is decl-reachable from k, so
// N::h is decl-reachable from k
Module M implementation:
module M;
int a = use_f<int>(); // OK
int b = use_g<int>(); // error: no viable function for call to g;
// g is not decl-reachable from purview of
// module M's interface, so is discarded
int c = use_h<int>(); // OK
Why is N::g not decl-reachable from use_g? Why is N::h not decl-reachable from use_h, but N::h is decl-reachable from use_h<int>? Why doesn't §10.4/(3.2) or §10.4/(3.3) apply to them?
|
N::f is decl-reachable from use_f due to rule 10.4.3.2.
In determining whether N::g is reachable from use_g, we find that neither 10.4.3.2 nor 10.4.3.3 applies.
10.4.3.2 does not apply because g((T(), x)) is a dependent call and thus, at the point of declaration of the template use_g, it can't be determined yet which function is actually named by the call. (It will be determined when use_g is instantiated, but in that case it may only imply that N::g is reachable from that particular specialization of use_g, not the template use_g itself.)
10.4.3.3 instructs us to consider a hypothetical call to g where each type-dependent argument is replaced by an expression of a type that has no associated namespaces or entities. Thus, for example, we could replace (T(), x) by 0, giving the hypothetical call g(0). This would not find N::g during the name lookup phase, so it doesn't make N::g decl-reachable.
For similar reasons, N::h is not decl-reachable from use_h.
When use_h<int> is instantiated, then rule 10.4.3.2 applies. At that point, the compiler determines that the type of (T(), x) is N::X, and actually performs the name lookup for h, finding N::h through argument-dependent lookup. That is, h((T(), x)) names the function N::h in this particular specialization (where T = int), but not in the original template.
|
74,588,958
| 74,591,625
|
define anonymous enum with x-macros produces compilation error
|
Im working on a big project and I have a lot of errno macros.
I want to write a helper functions for the logger that stringify each of these errno to a string. i decided to use x-macros but Im getting compilation errors
in the first place the code was like this:
// project_errno.h
#define PROJECT_ERR_KEY_FAILURE 12222
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
#define PROJECT_ERR_FAILED_TO_SETUP_ENC_KEY 14004
the way i sort it out is as the following:
In a different file i places the x-macros:
// project_errno.hx
PROJECT_ERR_FUNC(PROJECT_ERR_KEY_FAILURE) 12222
PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING) 12345
PROJECT_ERR_FUNC(PROJECT_ERR_FAILED_TO_SETUP_ENC_KEY) 14004
then I turned it into an enum:
// project_errno.h
enum {
#define PROJECT_ERR_FUNC(name, value) name=value,
#include "project_errno.hx"
#undef PROJECT_ERR_FUNC
};
then i added a function that will be used by the logger:
// logging.h (declaration) and (definition) logging.c
const char* stringify_errno(int errno) {
switch (errno) {
#define PROJECT_ERR_FUNC(name, value) case name: return #value ;
#include "project_errno.hx"
#undef PROJECT_ERR_FUNC
}
}
So, looks pretty good, but i can't get it to compile, Im getting the following compilation errros:
project_errno.h:8:53: error: error: expected identifier before numeric constant
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
project_errno.h:8:53: error: error: expected ‘}’ before numeric constant
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
project_errno.h:8:53: error: expected unqualified-id before numeric constant
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
^~~~~~~~~~~~~~~~~~~~~~~
In file included from ......../project_errno.h:20:1: error: expected declaration before ‘}’ token
};
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
^~~~~~~~~~~~~~~~~~~~~~~
I can't understand why im getting those errors (im getting the same error message multiple time in the same compilation session), and i hope you guys could help me.
Also, if you have any other solution to solve the problem i intended to solve in the first place (using the errno macros and add a functions to stringify those errnos whenever Im adding an errno to the project [in only one place]), i'd love to hear about it Thanks
|
I'd follow the recipe shown in the Wikipedia page about X Macros:
Implementation
An X macro application consists of two parts:
The definition of the list's elements.
Expansion(s) of the list to generate fragments of declarations or statements.
The list is defined by a macro or header file (named, LIST) which generates no code by itself, but merely consists of a sequence of invocations of a macro (classically named X) with the elements' data. Each expansion of LIST is preceded by a definition of X with the syntax for a list element. The invocation of LIST expands X for each element in the list.
In particular the second example, the one with X macro as argument
Pass name of the worker macro into the list macro. This both avoids defining an obscurely named macro (X), and alleviates the need to undefine it.
Which, in OP's use case, leads to the following three files:
// project_errno.h
#ifndef PROJECT_ERRNO_H
#define PROJECT_ERRNO_H
#define FOR_EACH_ERR_ID_VALUE_PAIR(DO) \
DO(PROJECT_ERR_KEY_FAILURE, 12222) \
DO(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345) \
DO(PROJECT_ERR_FAILED_TO_SETUP_ENC_KEY, 14004)
#define DEFINE_ENUM_ITEM(err, value) err = value,
enum project_errs {
FOR_EACH_ERR_ID_VALUE_PAIR( DEFINE_ENUM_ITEM )
};
#undef DEFINE_ENUM_ITEM
#endif
// logging.h
#ifndef LOGGING_H
#define LOGGING_H
const char* stringify_errno(int errno);
#endif
// logging.c
#include <stdio.h>
#include "project_errno.h"
#define STRINGIFY_ERR_VALUE_NAME(name, value) case name: \
return "[" #value "] " #name;
const char* stringify_errno(int errno)
{
switch (errno) {
FOR_EACH_ERR_ID_VALUE_PAIR(STRINGIFY_ERR_VALUE_NAME)
default:
return "[-----] UNKWOWN";
}
}
#undef STRINGIFY_ERR_VALUE_NAME
Testable here: https://wandbox.org/permlink/aNJCI7lQihkFnYzp
|
74,589,477
| 74,589,976
|
Can a pointer to a memory be used as initialized trivial type?
|
Is it undefined behavior to use a trivial type without initialization?
void* mem = malloc(sizeof(uint64_t)*100);
void* num_mem = mem + sizeof(uint64_t)*31;
//does the lifetime of uint64_t starts here:
uint64_t* mynum = reinterpret_cast<uint64_t*>(num_mem); //?
*mynum = 5; //is it UB?
std::cout << *mynum << std::endl; //is it UB?
free(mem);
I found out that calling of a destructor of trivial/POD/aggregate types is not necessary, but can't find the same for beginning of a lifetime of trivial/POD/aggregate type. Did I have to call new(num_mem) uint64_t; instead of reinterpret_cast ..?
Does the behavior changes if it's a POD or aggregate object, without constructors?
|
All of the following is following the rules of C++20, although the implicit object creation is considered a defect report against earlier versions as well. Before C++17 the meaning of pointer values was very different and so the discussion in the answer and the comments might not apply. All of this is also strictly about what the standard guarantees. Of course compilers may allow more in practice.
Yes, if the type and all of the types of its subobjects are implicit-lifetime types, which is a weaker requirement than being trivial or POD. It does apply to aggregate types, but not necessarily to the subobjects of the aggregate type, in which case these still need to be explicitly newed (e.g. consider the member of struct A { std::string s; };).
You also need to assure that the size and alignment of the memory are suitable. std::malloc returns memory aligned at least as strict as std::max_align_t, so it is good for any scalar type, but not for overaligned types.
Also, std::malloc is one of a few functions that is specifically specified to implicitly create objects and return a pointer to one. It does not generally work for arbitrary memory. For example if you use the memory location as uint64_t, then the implicitly created object is uint64_t. Cast afterwards to a different type will cause an aliasing violation.
The details are rather complicated and are easy to get wrong. It is much safer to explicitly create objects with new (which doesn't require initialization to a value either) and then use the pointer returned by new to access the object.
Also mem + sizeof(uint64_t)*31 is a GNU extension. It is not possible to perform pointer arithmetic on void* pointers in standard C++. You need to cast to the element type first and then perform the arithemtic, assuming that you only store the same types in the memory. Otherwise it gets a bit more complicated.
(Also, you are missing a null pointer check for the return value of malloc.)
|
74,589,652
| 74,589,948
|
Can you convert a pointer to an element in std::forward_list to the iterator to this element?
|
Since the std::forward_list is implemented as a single-linked list, its iterator should be just a pointer to the underlying element ± some offset.
Is there a way to convert a pointer to an element on a list to the iterator to this element without iterating through the entire list?
#include <forward_list>
template<typename T>
typename std::forward_list<T>::iterator makeIterator(T *element)
{
// magic here
}
int main()
{
std::forward_list<int> list;
list.emplace_front(101);
auto i = makeIterator(&list.front());
return i == list.begin() ? 0 : 1;
}
|
Short answer: Yes, I could hack a function makeIterator that does that:
template<typename T>
typename std::forward_list<T>::iterator makeIterator(T *element)
{
typedef typename std::forward_list<T>::iterator Iter;
typedef decltype(Iter()._M_node) NodeType;
static int offset = learnOffset<T>();
auto node = reinterpret_cast<NodeType>(reinterpret_cast<uint8_t*>(element) - offset);
return Iter(node);
}
Essentially, it does some pointer arithmetic to derive the address of the underlying list node and constructs an iterator from the derived pointer. The function learnOffset returns the offset needed in the pointer arithmetics.
See the long answer for details on how the function learnOffset is implemented. Note however, that this solution depends on the implementation of your C++ standard library. I am not aware of any public API function that does what you are asking for.
Long answer
I studied the implementation of the forward list iterator in the file /usr/include/c++/11/bits/forward_iterator.h and specifically the implementation of template<typename _Tp> struct _Fwd_list_iterator. It exposes a public member variable that points at the node in the linked list:
_Fwd_list_node_base* _M_node;
and is used for example from the dereferencing operator:
reference
operator*() const noexcept
{ return *static_cast<_Node*>(this->_M_node)->_M_valptr(); }
Reading the source code further suggests that the value stored in a list node is stored by value in the node itself. If so, there should be a constant offset between the pointer to that value and the list node itself. To test that, I wrote the function learnOffset:
template <typename T>
int learnOffset() {
// Populate a list with some data
std::forward_list<T> list;
for (int i = 0; i < 10; i++) {
list.emplace_front(T());
}
// Iterate over the populated list and the address differences
// between the stored element and the list node address held
// by the iterator.
std::unordered_set<int> offsets;
for (auto i = list.begin(); i != list.end(); i++) {
uint8_t* valAddr = reinterpret_cast<uint8_t*>(&(*i));
auto node = reinterpret_cast<uint8_t*>(i._M_node);
offsets.insert(valAddr - node);
}
// We expect exactly one difference. If not, produce an error.
if (offsets.size() != 1) {
std::cerr << "Couldn't learn forward_list iterator offset :-(" << std::endl;
abort();
}
return *(offsets.begin());
}
which returns 8 bytes. We can now directly call this function from the implementation of makeIterator above.
The above implementation of learnOffset leaves a lot to be desired. This code should just be considered a proof-of-concept.
Edited: Made learnOffset a template and to return offset in bytes.
|
74,589,757
| 74,589,961
|
QT SQL Create table with placeholder as name
|
I want to create Tables which use the actual year as name.
All I tried ended up returning an empty file.
First I tried to convert the variable to hex:
query.prepare("CREATE TABLE " + year.toUtf8().toHex() +
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
"comment TINYTEXT)");
After I tried it with QString and arguments:
query.prepare(QString("CREATE TABLE %1 "
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
"comment TINYTEXT)").arg(year));
And the last try was using Value binding:
query.prepare("CREATE TABLE :year "
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
"comment TINYTEXT)");
query.bindValue(":year", year);
All failed :/
|
Well,
It does work as it should.
Can't use numbers as Table name:
query.prepare("CREATE TABLE '" + year + "' "
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
"comment TINYTEXT)");
Or:
query.prepare(QString("CREATE TABLE %1 "
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
"comment TINYTEXT)").arg("'" + year + "'"));
But I would still like to know why it doesn't work with query.bindValue?
|
74,589,767
| 74,589,842
|
Function returning a pointer to the same function
|
In this code a function returns a pointer to itself
typedef void (*voidfunc)();
voidfunc f(int) {
return (voidfunc) f;
}
and generates the assembly was expecting, but uses a cast to a different function type to do so. How can this be done without casting in C++?
In other words what can be placed instead of ??? in the following snippet?
??? f(int) {
return f;
}
I tried first with
auto f(int) {
return f;
}
but it doesn't work, then I tried with templates but it didn't work either.
|
It is impossible since the type of the function would need to be contain an infinite recursion.
The version with the cast is also not useful. Any actual use of the return value would need to cast back to the actual function type.
Without additional information about the use case it is difficult to make a recommendation to solve this.
|
74,590,155
| 74,590,248
|
Expected ";" before Object_name C++
|
I have two files. One a header file named shape.h. I wanted to call the shapes from the class through the header file. But the file is not compiling.
#include <iostream>
#include <graphics.h>
using namespace std;
class Shape{
protected:
int x;
int y;
public:
Shape(){
x =0;
y = 0;
int gd = DETECT, gm;
char pathtodriver[] = "";
initgraph(&gd, &gm, pathtodriver);
}
virtual void draw();
};
class Rectangle : public Shape{
protected:
int x1;
int y1;
public:
Rectangle(int x, int y,int x1,int y1){
this->x = x;
this->y = y;
this->x1 = x1;
this->y1 = y1;
};
void draw(){
rectangle(200,200,100,250);
closegraph();
};
};
class Circle : public Shape{
protected:
int x1;
public:
Circle(int x,int y,int x1){
this->x = x;
this->y = y;
this->x1 = x1;
};
void draw(){
circle(x,y,x1);
closegraph();
};
};
class Ellipse : public Shape{
protected:
int a;
int b;
int x1;
int y1;
public:
Ellipse(int x,int y,int a, int b,int x1,int y1){
this->x = x;
this->y = y;
this->a = a;
this->b = b;
this->x1 = x1;
this->y1 = y1;
};
void draw(){
ellipse(x,y,a,b,x1,y1);
closegraph();
};
};
And another file to call in shapes.
#include "shape.h"
using namespace std;
int main(){
Shape *s1;
cout<<"1.Rectangle"<<
"2.Circle"<<
"3.Ellipse"<<
"4.Exit"<<endl;
int choice;
cout<<"Enter your choice :"<<endl;
cin >> choice;
switch(choice){
case 1:
Rectangle R1(100,100,50,60);
s1 = &R1;
s1->draw();
break;
case 2:
Circle c1(100,100,20);
s1 = &c1;
s1 ->draw();
break;
case 3:
Ellipse e1(100,100,0,360,30,40);
s1 = &e1;
s1->draw();
break;
case 4:
exit(0);
default:
cout<<"Error choice";
}
}
But it gives the following errors:
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\shape.h||In constructor 'Shape::Shape()':|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\shape.h|14|warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp||In function 'int main()':|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|13|error: expected ';' before 'R1'|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|14|error: 'R1' was not declared in this scope|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|20|error: jump to case label [-fpermissive]|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|17|note: crosses initialization of 'Circle c1'|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|21|error: expected ';' before 'e1'|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|22|error: 'e1' was not declared in this scope|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|24|error: jump to case label [-fpermissive]|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|17|note: crosses initialization of 'Circle c1'|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|27|error: jump to case label [-fpermissive]|
C:\Users\rbmoh\OneDrive\Desktop\Docs\C++\labb7.cpp|17|note: crosses initialization of 'Circle c1'|
||=== Build failed: 7 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
Please help
I tried changing the name of class but it did not work as well. The code did not compile.
|
You need to but the case statements with declarations in { ... } blocks. You also need to add breaks to not fallthrough to the next case statement.
You also need to take the choice input from the user. You currently use choice uninitialized.
Example:
while (std::cin >> choice) {
switch (choice) {
case 1: {
Rectangle R1(100, 100, 50, 60);
s1 = &R1;
s1->draw();
} break;
case 2: {
Circle c1(100, 100, 20);
s1 = &c1;
s1->draw();
} break;
case 3: {
Ellipse e1(100, 100, 0, 360, 30, 40);
s1 = &e1;
s1->draw();
} break;
case 4:
std::exit(0);
default:
cout << "Error choice";
}
}
Also note that void initgraph(int *graphdriver, int *graphmode, char *pathtodriver); takes a char* as the last argument. You provide a const char*. You need to change that:
char pathtodriver[] = "";
initgraph(&gd, &gm, pathtodriver);
Demo
|
74,590,457
| 74,591,014
|
CUDA deep copy with other data
|
I'm trying to copy my struct Test to the GPU, change the data, and upload it back to the CPU. This is what I've tried so far, note that my code crashes on the last, commented out, line:
struct Test {
int x, y;
int* data;
};
// Test kernel
static __global__ void TestKernel(Test* d) {
const uint32_t index = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
// increment some values
++d->data[0];
++d->data[1];
++d->data[2];
++d->x;
++d->y;
}
// Test snippet:
Test* host = new Test{ 10, 20,new int[3]{1, 2, 3} };
Test* device = nullptr;
int* deviceData;
COMPUTE_SAFE(cudaMalloc(&device, sizeof(Test)));
COMPUTE_SAFE(cudaMalloc(&deviceData, 3 * sizeof(int)));
COMPUTE_SAFE(cudaMemcpy(device, host, sizeof(Test), cudaMemcpyHostToDevice));
COMPUTE_SAFE(cudaMemcpy(deviceData, host->data, 3 * sizeof(int), cudaMemcpyHostToDevice));
COMPUTE_SAFE(cudaMemcpy(&(device->data), &deviceData, sizeof(float*), cudaMemcpyHostToDevice));
TestKernel <<< 1, 1 >>> (device);
COMPUTE_SAFE(cudaDeviceSynchronize());
COMPUTE_SAFE(cudaMemcpy(host, device, sizeof(Test), cudaMemcpyDeviceToHost));
COMPUTE_SAFE(cudaMemcpy(host->data, deviceData, 3 * sizeof(float), cudaMemcpyDeviceToHost));
printf("\nhost:\n");
printf("%d %d\n", host->x, host->y); // works
// printf("%d %d %d\n", host->data[0], host->data[1], host->data[2]); // crashes
Note that I've seen multiple related questions, but none of them also copy some data apart from the deep copied data pointer.
My error message:
Exception thrown at 0x00007FF7A2C5297D in VFD.exe: 0xC0000005: Access
violation reading location 0x0000000B01600208.
Note that I'm probably copying the memory incorrectly, or something along those lines. If I remove the COMPUTE_SAFE(cudaMemcpy(host, device, sizeof(Test), cudaMemcpyDeviceToHost)); line I'm able to access the host->data array, but the x and y values stay unincremented for obvious reasons.
|
After you cudaMemcpy into the host struct back from the GPU, you override the data pointer in it with an invalid GPU data pointer.
In order to fix it you need to restore the original data pointer (and then copy the actual data).
Working version:
struct Test
{
int x, y;
int* data;
};
static __global__ void TestKernel(Test* d)
{
++(d->data[0]);
++(d->data[1]);
++(d->data[2]);
++(d->x);
++(d->y);
}
int main()
{
int* hostData = new int[3]{ 1, 2, 3 };
Test* host = new Test{ 10, 20, hostData };
int* deviceData = nullptr;
Test* device = nullptr;
COMPUTE_SAFE(cudaMalloc(&device, sizeof(Test)));
COMPUTE_SAFE(cudaMalloc(&deviceData, 3 * sizeof(int)));
COMPUTE_SAFE(cudaMemcpy(device, host, sizeof(Test), cudaMemcpyHostToDevice));
COMPUTE_SAFE(cudaMemcpy(deviceData, host->data, 3 * sizeof(int), cudaMemcpyHostToDevice));
COMPUTE_SAFE(cudaMemcpy(&(device->data), &deviceData, sizeof(int*), cudaMemcpyHostToDevice));
TestKernel << < 1, 1 >> > (device);
COMPUTE_SAFE(cudaDeviceSynchronize());
COMPUTE_SAFE(cudaMemcpy(host, device, sizeof(Test), cudaMemcpyDeviceToHost));
host->data = hostData; // Restore host data pointer
COMPUTE_SAFE(cudaMemcpy(host->data, deviceData, 3 * sizeof(int), cudaMemcpyDeviceToHost));
printf("\nhost:\n");
printf("%d %d\n", host->x, host->y);
printf("%d %d %d\n", host->data[0], host->data[1], host->data[2]);
return 0;
}
Output:
host:
11 21
2 3 4
Some notes:
For clarity I added () in the kernel increment statements.
You used sizeof(float*) for the data pointer, although it is an int* (of course the size is the same).
|
74,590,672
| 74,590,713
|
How to include asio boost in cmake project
|
I'm trying to include asio boost using CMakein my project but I'm getting this error. libraries linking is working in VS but I don't know how to link them in Cmake project.
Working Solution with VS:-
asio boost version: 1.24.0
VS ScreenShot
cmake_minimum_required(VERSION 3.10)
project(networking_examples)
#set(CMAKE_CXX_COMPILER D:/System/msys2/mingw64/bin/clang++)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Link Boost Asio library
target_include_directories(networking_examples PRIVATE "./asio-1.24.0/include")
add_executable(
networking_examples
./src/index.cpp
)
CMake Project
I want to link ./asio-1.24.0/include with my project using CMAKE.
Error:
CMake Error at CMakeLists.txt:9 (target_include_directories):
Cannot specify include directories for target "networking_examples" which
is not built by this project.
-- Configuring incomplete, errors occurred!
See also "D:/Git Repo/c++/networking/cmake-build-debug/CMakeFiles/CMakeOutput.log".
|
When you use target_include_directories there is not target named networking_examples. You add that target after.
Order matters, and just like in C++ symbols must be defined before they can be used.
So you need to change to:
add_executable(
networking_examples
./src/index.cpp
)
# Asio library header directory
target_include_directories(networking_examples PRIVATE "./asio-1.24.0/include")
On another couple of notes: First you don't seem to be using Boost ASIO but rather the standalone header-only library.
Secondly, you don't link with the library (it's a header-only library). You only tell the build-system where it can find the ASIO header files.
|
74,590,755
| 74,591,152
|
Shipping Python interpreter with C++ project
|
Problem description:
I have a Visual Studio 2022 C++ project that involves live python script interpretation. Naturally, I need a valid Python installation to do this. However, I intend to ship this as an application, so I'd like to have a localized Python installation, to avoid consumer-side installation, but that doesn't interfere with Windows' Environmental Variables.
What I've done:
I included "Python.h" from my Python installation's "include" folder, I've added its "libs" folder to "Additional Library Directories", I've added "python311.lib" to "Additional Dependencies", and I remembered to copy Python311.dll to my project's Solution Directory.
Everything is linked properly.
However, when I run compile and execute my program, I receive a long list of errors, which are as follows:
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'python'
isolated = 0
environment = 1
user site = 1
safe_path = 0
import site = 1
is in build tree = 0
stdlib dir = 'C:\Coding Projects\MaSGE\Lib'
sys._base_executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe'
sys.base_prefix = 'C:\\Coding Projects\\MaSGE'
sys.base_exec_prefix = 'C:\\Coding Projects\\MaSGE'
sys.platlibdir = 'DLLs'
sys.executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe'
sys.prefix = 'C:\\Coding Projects\\MaSGE'
sys.exec_prefix = 'C:\\Coding Projects\\MaSGE'
sys.path = [
'C:\\Coding Projects\\MaSGE\\python311.zip',
'C:\\Coding Projects\\MaSGE\\Lib',
'C:\\Coding Projects\\MaSGE\\DLLs',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
Current thread 0x0000399c (most recent call first):
<no Python frame>
Of particular interest to me are the first two lines, plus the "PYTHONHOME = (not set)" and "PYTHONPATH = (not set)" on lines 4 and 5 which, to my knowledge, are Environmental Variables.
This brings me to the crux of the problem:
Is there some way in which I can install a portable Python interpreter to a specific folder to circumvent the issue with Environmental Variables?
|
To embed python into your application, you need two things:
Initialize isolated python
This will not let user's system interfere with your app.
https://docs.python.org/3/c-api/init_config.html#init-isolated-conf
Deploy python stuff with your application
On windows, you need:
Python DLL (python311.dll).
Python standard library.
Either copy Lib folder from python installation, or zip its contents and name it after python dll (e.g. python311.zip), or use the same zip from Windows embeddable package)
Python modules (DLLs directory)
On linux, situation is slightly different:
Python shared library (libpython311.so)
Python standard library (Either copy lib/python311/ folder from python installation, or zip its contents except lib-dynload folder and name it lib/python311.zip)
(If using zipped standard library) Copy lib-dynload to lib/python3.11/lib-dynload
Of course, you have to replace 311 and 3.11 with your version of python.
|
74,591,455
| 74,591,486
|
How can I make an array of method pointers?
|
I want to create an array of pointers to methods, so I can quickly select a method to call, based on a integer. But I am struggling a little with the syntax.
What I have now is this:
class Foo {
private:
void method1();
void method2();
void method3();
void(Foo::*display_functions[3])() = {
Foo::method1,
Foo::method2,
Foo::method3
};
};
But I get the following error message:
[bf@localhost method]$ make test
g++ test.cpp -o test
test.cpp:11:9: error: cannot convert ‘Foo::method1’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
11 | };
| ^
test.cpp:11:9: error: cannot convert ‘Foo::method2’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
test.cpp:11:9: error: cannot convert ‘Foo::method3’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
make: *** [<builtin>: test] Error 1
|
Yes, you can, you just need to take the address of them:
void(Foo::*display_functions[3])() = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};
... however, it's likely better if you have virtual methods for an interface or a simple method that calls them all for a multi-method pattern.
|
74,593,059
| 74,593,486
|
Protocol-Buffers C++ can't set variables
|
I'm new to C++ (and programming overall). Trying to understand protobuf and have some issues.
Here is the proto file:
syntax="proto3";
message FullName{
string Surname = 1;
string Name = 2;
optional string Patronymic = 3;
}
message Student{
FullName sName = 1;
repeated int32 Grade = 2;
int32 AverageMark = 3;
}
message StudentsGroup{
repeated Student sInfo = 1;
}
and here is the code:
#include <iostream>
#include "Students.pb.h"
int average(const google::protobuf::RepeatedField<int32_t>& grades)
{
int32_t s = 0;
for (const int& i : grades)
{
s = s + i;
}
return s/grades.size();
}
int main()
{
FullName name1;
name1.set_surname("Sergeev");
name1.set_name("Sergey");
name1.set_patronymic("Sergeevich");
std::cout << name1.name() << std::endl;
Student student1;
student1.set_name(name1); // <--
student1.add_grade(4);
student1.add_grade(3);
student1.set_averagemark(average(student1.grade()));
StudentsGroup group1;
group1.add_sinfo(student1); // <--
}
The issue is I don't know how to set student1 sName and add sInfo in group1. The syntax I use is incorrect.
Please help)
|
Student has no Name field, thus Student::set_name() cannot be available.
Student has FullName sName, FullName is not a base type, thus the setter is Student::set_allocated_sname(::FullName* sname).
Student sInfo = 1 is repeated values of not a base type in StudentsGroup, thus it should be accessed through the mutable collection ::google::protobuf::RepeatedPtrField<::Student>* StudentsGroup::mutable_sinfo()
The fix:
auto name1 = std::make_unique<FullName>();
name1->set_surname("Sergeev");
name1->set_name("Sergey");
name1->set_patronymic("Sergeevich");
std::cout << name1->name() << std::endl;
auto student1 = std::make_unique<Student>();
student1->set_allocated_sname(name1.release());
student1->add_grade(4);
student1->add_grade(3);
student1->set_averagemark(average(student1->grade()));
StudentsGroup group1;
group1.mutable_sinfo()->AddAllocated(student1.release());
|
74,593,507
| 74,593,908
|
const&& binding to ref in lambda capture: clang vs gcc?
|
In the following code:
int foo() {
int a = 5;
auto l = [&r = std::move(std::as_const(a))] { return r; };
return l();
}
clang compiles just fine
gcc produces error.
error: cannot capture 'std::move<const int&>((* & std::as_const<int>(a)))' by reference
I need community help to argue about this case from C++ standard point of view: who is correct in C++20 and why exactly.
From [expr.prim.lambda.capture] not clear to me if this clause:
An init-capture without ellipsis behaves as if it declares and explicitly captures a variable of the form "auto init-capture"
means that clang is right? If yes then why removing as_const makes this an error for both?
code example on godbolt
|
Seems to be a GCC bug. The init-capture should behave as if declaring a corresponding variable with auto prefixed and which is then captured (exactly as in your quote from the standard):
auto &r = std::move(std::as_const(a));
This would deduce auto to const int so that the variable has type const int& and initialization would be well-formed because the initializer is a rvalue of type const int which a const lvalue reference can bind to directly.
However std::move has no effect here and the result would be identical without it. (std::move on a const type basically never makes sense.)
It fails without as_const because then auto will be deduced to just int so that the variable has type int&. You are then trying to initialize it from an rvalue (the result of std::move) which is not allowed when initializing non-const lvalue references.
|
74,594,151
| 74,594,313
|
How to enable structured bindings for a std::tuple wrapper class?
|
I'm trying to implement a wrapper class for another class that has a private std::tuple member and enable structured bindings on the wrapper class. Here's the class with the private tuple:
class widget {
friend class wrap;
std::tuple<int, double> m_tuple {1, 1.0};
};
Here's my attempt at the wrapper class after reading about how to enable structured bindings for custom types (e.g., this post on devblogs.microsoft.com):
class wrap {
public:
wrap(widget& f) : m_tuple(f.m_tuple) {}
// auto some_other_function();
template<std::size_t Index>
auto get() & -> std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
template<std::size_t Index>
auto get() && -> std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
template<std::size_t Index>
auto get() const& -> const std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
template<std::size_t Index>
auto get() const&& -> const std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
private:
std::tuple<int, double>& m_tuple;
};
Here are the specialized std::tuple_size and std::tuple_element for wrap:
namespace std {
template<>
struct tuple_size<wrap> : tuple_size<std::tuple<int, double>> {};
template<size_t Index>
struct tuple_element<Index, wrap> : tuple_element<Index, tuple<int, double>> {};
} // namespace std
I'd like the following behavior:
int main() {
widget w;
auto [i_copy, d_copy] = wrap(w);
i_copy = 2; // Does not change w.m_tuple because i_copy is a copy of std::get<0>(w.m_tuple).
d_copy = 2.0; // Does not change w.m_tuple because d_copy is a copy of std::get<1>(w.m_tuple).
// w.m_tuple still holds {1, 1.0}.
auto& [i_ref, d_ref] = wrap(w);
i_ref = 2; // Changes w.m_tuple because i_ref is a reference to std::get<0>(w.m_tuple).
d_ref = 2.0; // Changes w.m_tuple because d_ref is a reference to std::get<1>(w.m_tuple).
// w.m_tuple now holds {2, 2.0}.
}
But this doesn't even compile (tested with gcc 12.2.0 and clang 14.0.6). The error I get is
error: cannot bind non-const lvalue reference of type ‘wrap&’ to an rvalue of type ‘wrap’
| auto& [i_ref, d_ref] = wrap(w);
Does the non-const lvalue reference of type ‘wrap&’ refer to auto& [i_ref, d_ref] and the rvalue of type ‘wrap’ to wrap(w)? Why are i_ref and d_ref not references to the integer and double of the tuple in w?
Edit: How can I implement a wrapper class that has the desired behavior?
|
In your second example usage you have
auto& [i_ref, d_ref] = wrap(w);
The auto& is the type for the invisible variable bound to the expression on the right side of the = which is a temporary. It's like doing
wrap& wr = wrap(w);
I learned this from T.C. in 2016, see that answer for all the relevant citations.
We can produce the same error without any of your classes, just a tuple and an auto&
This code:
auto& [i, d] = std::tuple{1, 1.0};
produces this error:
prog.cc: In function 'int main()':
prog.cc:4:25: error: cannot bind non-const lvalue reference of type 'std::tuple<int, double>&' to an rvalue of type 'std::tuple<int, double>'
4 | auto& [i, d] = std::tuple{1, 1.0};
| ^~~~~~~~~~~~~
You can't bind a non-const lvalue reference to a temporary. If you change the line to
const auto& [i_ref, d_ref] = wrap(w);
Then you get through that line, but can't use i_ref or d_ref to modify anything because they're now aliases for the fields of a const object. If you want something you can modify then you'd have to give a name to the wrap object.
auto wrapped = wrap(w);
auto& [i_ref, d_ref] = wrapped;
i_ref = 2;
assert(std::get<0>(w.m_tuple) == 2);
live here
You could also make this work with an rvalue reference
auto&& [i_ref, d_ref] = wrap(w);
i_ref = 2;
assert(std::get<0>(w.m_tuple) == 2);
live here
Or no reference at all
auto [i_ref, d_ref] = wrap(w);
i_ref = 2;
assert(std::get<0>(w.m_tuple) == 2);
|
74,594,393
| 74,605,059
|
Thread-safe stack in C++: combined top() and pop()
|
In his excellent book "C++ Concurrency in Action" (2nd edition including C++17) Anthony Williams discusses the implementation of a thread-safe stack.
In the course of this, he proposes an adapter implementation of std::stack, which, among other things, would combine the calls of top() and pop() into one. The separation into 2 separate functions, however, was done for a reason in std::stack, namely to avoid losing data in the case that a potential copy made when returning the popped element to the caller throws an exception inside the copy constructor. When returning, the element will have already been popped off and is consequentially lost.
Instead of having a function T pop(), he proposes other variations of pop that would be able to remove the element off the stack and provide it to the caller in one operation, all of which come with their own problems, though.
The 1st alternative he proposes has the signature void pop(T&). The caller passes in a reference to a T and gets the popped off object that way. This way of doing it, however, comes with the problem that a T need be constructed prior to the call to pop, which might be an expensive operation, or it might not be possible to construct a T beforehand at all because necessary data might not be available yet at the time. Another problem the author mentions is that T might not be assignable, which would be required for this solution, though.
Now my question: Wouldn't all of the mentioned problems be solved if we passed a std::optional<T>& instead of a T&?
In that case, no instance of T would need to be constructed prior to the call to pop. Furthermore, assignability would not be required anymore either, since the object to be returned could be constructed into the std::optional<T> instance directly using its emplace function.
Am I missing something crucial here or am I right? If I am indeed right, I would be curious to know why this was not considered (for a good reason or just plainly an oversight?).
|
std::optional does solve all of the mentioned problems, and using it to control lifetime can be quite valuable, although it would appear a bit strange in
std::optional<T> o;
st.pop(o);
to have o always engaged.
That said, with a stupid scope-guard trick it's possible in C++17 to safely return T even without requiring no-throw-movability:
T pop() {
struct pop_guard {
C &c;
int u=std::uncaught_exceptions();
~pop_guard() {if(std::uncaught_exceptions()==u) c.pop_back();}
} pg{c};
return std::move(c.back());
}
(We could of course test for a throwing move and just move (perhaps twice) in its absence.)
However, what wasn't mentioned is that separate top and pop allows a T that isn't even movable, so long as the underlying container supports it. std::stack<std::mutex> works (with emplace, not push!) because std::deque doesn't require movability.
|
74,594,599
| 74,594,674
|
p > nullptr: Undefined behavior?
|
The following flawed code for a null pointer check compiles with some compilers but not with others (see godbolt):
bool f()
{
char c;
return &c > nullptr;
}
The offensive part is the relational comparison between a pointer and nullptr.
The comparison compiles with
gcc before 11.1
MSVC 19.latest with /std:c++17, but not with /std:c++20.
But no version of clang (I checked down to 4.0) compiles it.
The error newer gccs produce ("ordered comparison of pointer with integer zero ('char*' and 'std::nullptr_t')"1 is a bit different than the one from clang ("invalid operands to binary expression ('char *' and 'std::nullptr_t')").
The C++20 ISO standard says about relational operators applied to pointers in 7.6.9/3ff:
If both operands are pointers, pointer conversions (7.3.12) [...] are performed to
bring them to their composite pointer type (7.2.2). After conversions, the operands shall have the same type.
The result of comparing unequal pointers to objects is defined in terms of a partial order consistent with the following rules:
(4.1) — If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript is required to compare greater.
(4.2) — If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member is required to compare greater provided the two members have the same access control (11.9), neither member is a subobject of zero size, and their class is not a union.
(4.3) — Otherwise, neither pointer is required to compare greater than the other.
("Pointer to object" in this context means only that the type is not a pointer to function, not that the pointer value refers to an actual object.)
(4.1) and (4.2) clearly don't apply here, which leaves (4.3). Does (4.3), "neither pointer is required", mean the behavior is undefined, and the code is invalid? By comparison, the 2012 standard contained the wording in 5.9/2 "[...] if only one of [two pointers of the same type p and q] is null, the results
of p<q, p>q, p<=q, and p>=q are unspecified."
1 The wording doesn't seem correct. nullptr_t is not, if I read the standard correctly, an integral type.
|
7.6.9 states, "The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the operands. .... The converted operands shall have arithmetic, enumeration, or pointer type."
None of the specified conversions is applicable to the literal nullptr. Also, it does not have arithmetic, enumeration, or pointer type. Therefore, the comparison is ill-formed.
|
74,594,632
| 74,594,690
|
How to change 1 or 0, into a true or false output
|
I have this hw assignment that I have completed. I am using a bool value in order for it to print 1 or 0. My question is how do I make it print out true or false, instead of the 1 or 0.
My output:
1 = true, 0 = false
------------
c1 >= c2 : 1
c1 <= c2 : 0
c1 != c2 : 1
c1 < c2 : 0
c1 > c2 : 1
c1 == c2 : 0
My code
int main()
{
//Declearing the radii of 2 circles in order to compare
Circle c1(7);
Circle c2(6);
//prints true or false in boolean so 1 or 0
bool compare;
cout << "1 = true, 0 = false" << endl;
cout << "------------" << endl;
compare = c1 >= c2;
cout<< "c1 >= c2 : "<< compare << endl;
compare = c1 <= c2;
cout<< "c1 <= c2 : "<< compare << endl;
compare = c1 != c2;
cout << "c1 != c2 : " << compare << endl;
compare = c1 < c2;
cout<< "c1 < c2 : " << compare << endl;
compare = c1 > c2;
cout << "c1 > c2 : " << compare << endl;
compare = c1 == c2;
cout << "c1 == c2 : " << compare << endl;
cout << endl;
}
This is a multiple file program so I only added the main.cpp. Any advice would be greatly appreciated.
|
It looks like we have some good options (ordered by time of submission):
std::cout << (compare ? "true" : "false");
std::cout << std::boolalpha << compare;
const char *s[] = { "false", "true" }; std::cout << s[compare];
|
74,594,651
| 74,594,694
|
How to update a pointer member variable in C++
|
This is the rough outline of my code. I've left out some details so let me know if you need more context.
class A;
class B;
class C {
public:
C(int dat, int idx) {
data = dat;
i = idx;
}
friend class A;
friend class B;
private:
int data;
int i;
};
class A {
public:
void insert(int dat, int idx) {
c = new C(dat, idx);
// ... other operations to place it
}
// I have the correct destructor, etc..
// function that returns an address to a specific instance of a dynamically allocated C
C* getPointer(int dat) const {
return getPointer(dat); // a call to an internal function
// omitted for simplicity because this works
}
private:
C* c;
};
class B {
public:
B() {
size = 5;
arr = new D[size];
}
// I have the correct destructor, etc..
C* getPtr(int idx) {
return(arr[idx].X);
}
void setPtr(C*& oldPtr, C* newPtr) {
oldPtr = newPtr;
}
private:
struct D{
int d;
C* X;
D() {
d = 0;
X = nullptr;
}
};
D* arr;
int size;
};
int main() {
A a;
B b;
// index is a value returned from an insert function in class B
// dat is a value to find which address should be returned of the objects in class A
a.setPtr(b.getPtr(index), a.getPointer(dat));
return 0;
}
I wrote a function (getPointer(int dat) in class A) that returns the address of an instance of the dynamically allocated object of class C. So, how do I update X to point at this address instead of null?
I've tried many different ways and currently (what I thought was the most promising) was the setPtr() function in class B. It correctly changes the address X is pointing to once, but when I call any other functions its value is back to nullptr.
Any help or advice would be greatly appreciated. Thank you.
|
You correctly wrote getPtr(int idx) (if I understand your spec. correctly). Now, the return value is C* there, which is not C*& or C**, so it won't be updated if you change the result afterwards - think of it as a return i; won't expose int i; member if return type is int.
So either:
you need to change the return type of getPtr(int idx) and then setPtr() is not really needed;
or you can build both of these in setPtr() as:
void setPtr(int idx, C* newPtr) {
arr[idx].X = newPtr;
}
|
74,594,653
| 74,594,747
|
I have a question about merge sort algorithm
|
I've looked at the merge sort example code, but there's something I don't understand.
void mergesort(int left, int right)
{
if (left < right)
{
int sorted[LEN];
int mid, p1, p2, idx;
mid = (left + right) / 2;
mergesort(left, mid);
mergesort(mid + 1, right);
p1 = left;
p2 = mid + 1;
idx = left;
while (p1 <= mid && p2 <= right)
{
if (arr[p1] < arr[p2])
sorted[idx++] = arr[p1++];
else
sorted[idx++] = arr[p2++];
}
while (p1 <= mid)
sorted[idx++] = arr[p1++];
while (p2 <= right)
sorted[idx++] = arr[p2++];
for (int i = left; i <= right; i++)
arr[i] = sorted[i];
}
}
In this code, I don't know about while loops that increase p1 and p2 respectively.
In detail, This code inserts p1, p2 in order into the 'sorted array', but I don't understand why the array is sorted in ascending order.
I looked at many explanations on the internet, but couldn't find a clear answer.
I would appreciate it if you could write your answer in detail so that I can understand it.
|
I'm a developer working in the field.
I was surprised to see you embodying merge sort.
Before we start, the time complexity of the merge sort is O(nlogn).
The reason can be found in the merge sort process!
First, let's assume that there is an unordered array.
Merger sorting process:
Divide it into an array of 1 size by the number of size of the array.
Create an array that is twice the size of the divided array.
Compare the elements of the two divided arrays and put the smaller elements in order in the created array.
Repeat this process until it reaches the size of the original array.
merge sort img
There is a reason why the time complexity of the merge sort is O(nLogn).
In this process, the time complexity of log is obtained because the array is continuously divided by half, and the time complexity of nlogn is obtained because the process is performed by a total of n times.
|
74,594,809
| 74,594,856
|
the largest element in the array outputs as -858993460 [C++]
|
im trying to let the user input a number for each person. the console then outputs the maximum value in the array. everything works fine but the max always outputs as -858993460. i tried multiple combinations but i cant seem to figure it out
im new to arrays so any help would be appreciated as well as an feedback on how to improve my code
#include <iostream>
int main()
{
int people[10];
int max = people[0];
std::cout << "please enter number of pancakes eaten by each person.\n";
//lets the user input values for each element
for (int i = 0; i < 10; ++i) {
std::cin >> people[i];
}
//outputs all the elements of the array
for (int i = 0; i < 10; ++i) {
std::cout << people[i] << " ";
}
//finds the largest element in the array
for (int i = 0; i > 10; ++i) {
if (people[i] > max) {
max = people[i];
}
}
std::cout << "\nmax: " << max;
return 0;
}
also i keep getting a warning saying: ill-defined for-loop. loop body not executed. i tried looking this warning up but the warning seems very broad and i couldnt find anything that helped
|
int people[10];
This declares an array of ten int values. None of the values are explicitly initialized. This is how plain values that get declared in automatic scope work in C++, they are not initialized to any values. It is the code's responsibility to initialize them.
int max = people[0];
This sets the value of max to the first value of the array. Which has not been initialized to any value. This is undefined behavior. From this point on the program's behavior is undefined.
Furthermore, even if peoples values were initialized this will still be broken. The intent of the program is clear: read values into the people array, and then find their maximum value.
However, at this point, nothing has been read from anywhere.
The attempted goal here is to set max, initially, to the first value in the array, the first read value.
But in order for this to make sense, max should be set after the values in the array get read from input, and not before. This should be done after all the values are read in, and not before.
|
74,594,984
| 74,594,989
|
"./main: not found" (C++, RP 3/B, Geany IDE)
|
I'm attempting to write a simple program that calls a function written in a pair of Header and CPP files.
I'm doing this on a Raspberry Pi 3 Model B, and the Geany IDE v1.37.1.
Compile Command:
g++ -Wall -c "%f" -c test.cpp
Build Command:
g++ -Wall -o "%e" "%f" -o test test.cpp
main.cpp:
#include "test.h"
int main()
{
test_function();
return 0;
}
test.h:
#ifndef _test_h_
#define _test_h_
#include <iostream>
void test_function();
#endif
test.cpp:
#include "test.h"
void test_function()
{
std::cout << "hello world";
}
The code above compiles & builds fine, however attempting to run it yields the following error:
./main: not found
(program exited with code: 127)
Perhaps I am messing something up with the Compile & Build Commands?
Thank you for reading my post, any guidance is apprecaited!
|
Notice the compile command:
-o test
This means that the output binary will be test, so you can execute the application in your terminal or shell via ./test.
|
74,595,339
| 74,595,459
|
How to declare and access method functions from different class files
|
So I'm writing a POS system for a project at school and I'm having trouble declaring the call method for each file to access the said methods
main.cpp
#include <iostream>
#include <windows.h>
int main()
{
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
UI.MainMenu();
}
AppUI.cpp
#include <iostream>
#include <windows.h>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <stdio.h>
#include "SecuritySys.h"
#include "AppUI.h"
#include "EditBook.h"
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
using namespace std;
void AppUI::MainMenu()
{
//variable declarations
int opt;
MenuStart:
system("CLS");
TitleHeader();
setTxtColor(10);
PageTitle("Main Menu");
string Menu[] = {"Add Books", "Search Books", "View Books", "Delete Book", "Exit"};
cout << "1.\tAdd Books" << endl;
cout << "2.\tSearch Books" << endl;
cout << "3.\tView Books" << endl;
cout << "4.\tDelete Books" << endl << endl;
cout << "0.\tExit";
cout << "\n\nEnter Option: ";
cin >> opt;
switch(opt)
{
case 1:
BookFunc.AddBook();
break;
case 2:
BookFunc.AddBook();
break;
case 3:
BookFunc.AddBook();
break;
case 4:
BookFunc.AddBook();
break;
case 0:
SecSysFunc.Logout();
break;
default:
cout << "Invalid option!";
sleep(1);
goto MenuStart;
}
}
AppUI.h
#ifndef APPUI_H
#define APPUI_H
class AppUI
{
public:
void MainMenu();
void AddBook();
void SearchBook();
private:
};
#endif // APPUI_H
EditBook.cpp
#include <iostream>
#include <windows.h>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <stdio.h>
#include "SecuritySys.h"
#include "AppUI.h"
#include "EditBook.h"
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
using namespace std;
void EditBook::AddBook()
{
system("CLS");
UI.AddBook();
}
SearchByTitle(string searchTxt)
{
cout << "Enter search by title code here";
system("pause");
UI.MainMenu();
}
EditBook.h
#ifndef EDITBOOK_H
#define EDITBOOK_H
class EditBook
{
public:
void AddBook();
void SearchBook();
void ViewBooks();
void DeleteBooks();
protected:
private:
};
#endif // EDITBOOK_H
SecuritySys.cpp
#include <iostream>
#include <windows.h>
#include <iomanip>
#include <string>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <stdio.h>
#include "SecuritySys.h"
#include "AppUI.h"
#include "EditBook.h"
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
using namespace std;
void SecuritySys::Login()
{
UI.MainMenu();
}
void SecuritySys::Logout()
{
exit(0);
}
SecuritySys.h
#ifndef SECURITYSYS_H
#define SECURITYSYS_H
class SecuritySys
{
public:
void Login();
void Logout();
private:
};
#endif
When I add AppUI UI; SecuritySys SecSysFunc; EditBook BookFunc; to the top of AppUI.cpp EditBook.cpp and SecuritySys.cpp I get an error saying multiple definition of UI,SecSysFunc and the BookFunc. But if I don't add them at the top, then the BookFunc.AddBook(); for example, the method can't be recognized and therefor can't be called or used. What am I doing wrong here?
|
You are getting a multiple definition error because you are just redeclaring the objects UI, SecSysFunc and BookFunc. You need to make it clear to the compiler that these identifiers point to the same object. You can do so by picking one of the four declarations to be the definition, leave those lines as is. But to the declarations in other code files add extern before the declaration. This will tell the compiler to look in other linked object files for the definition of those objects
|
74,595,458
| 74,597,610
|
Should B-Tree nodes contain a pointer to their parent (C++ implementation)?
|
I am trying to implement a B-tree and from what I understand this is how you split a node:
Attempt to insert a new value V at a leaf node N
If the leaf node has no space, create a new node and pick a middle value of N and anything right of it move to the new node and anything to the left of the middle value leave in the old node, but move it left to free up the right indices and insert V in the appropriate of the now two nodes
Insert the middle value we picked into the parent node of N and also add the newly created node to the list of children of the parent of N (thus making N and the new node siblings)
If the parent of N has no free space, perform the same operation and along with the values also split the children between the two split nodes (so this last part applies only to non-leaf nodes)
Continue trying to insert the previous split's middle point into the parent until you reach the root and potentially split the root itself, making a new root
This brings me to the question - how do I traverse upwards, am I supposed to keep a pointer of the parent?
Because I can only know if I have to split the leaf node when I have reached it for insertion. So once I have to split it, I have to somehow go back to its parent and if I have to split the parent as well, I have to keep going back up.
Otherwise I would have to re-traverse the tree again and again each time to find the next parent.
Here is an example of my node class:
template<typename KEY, typename VALUE, int DEGREE>
struct BNode
{
KEY Keys[DEGREE];
VALUE Values[DEGREE];
BNode<KEY, VALUE, DEGREE>* Children[DEGREE + 1];
BNode<KEY, VALUE, DEGREE>* Parent;
bool IsLeaf;
};
(Maybe I should not have an IsLeaf field and instead just check if it has any children, to save space)
|
Even if you don't use recursion or an explicit stack while going down the tree, you can still do it without parent pointers if you split nodes a bit sooner with a slightly modified algorithm, which has this key characteristic:
When encountering a node that is full, split it, even when it is not a leaf.
With this pre-emptive splitting algorithm, you only need to keep a reference to the immediate parent (not any other ancestor) to make the split possible, since now it is guaranteed that a split will not lead to another, cascading split more upwards in the tree. This algorithm requires that the maximum degree (number of children) of the B-tree is even (as otherwise one of the two split nodes would have too few keys to be considered valid).
See also Wikipedia which describes this alternative algorithm as follows:
An alternative algorithm supports a single pass down the tree from the root to the node where the insertion will take place, splitting any full nodes encountered on the way preemptively. This prevents the need to recall the parent nodes into memory, which may be expensive if the nodes are on secondary storage. However, to use this algorithm, we must be able to send one element to the parent and split the remaining −2 elements into two legal nodes, without adding a new element. This requires = 2 rather than = 2−1, which accounts for why some textbooks impose this requirement in defining B-trees.
The same article defines and :
Every internal node contains a maximum of children and a minimum of children.
For a comparison with the standard insertion algorithm, see also Will a B-tree with preemptive splitting always have the same height for any input order of keys?
|
74,596,501
| 74,596,572
|
How to get values for the variables inside a class using a friend functions
|
#include <iostream>
#include <string>
using namespace std;
class person {
string name;
int age;
public :
person() {
name = "no data found";
age = 0;
}
person(string x, int y) {
name = x;
age = y;
}
friend void getdata(person);
friend void printdata(person);
};
void getdata(person x) {
cout<<"Enter name : "<<endl;
getline(cin, x.name);
cout<<"Enter age : "<<endl;
cin>>x.age;
};
void printdata(person x) {
cout<<"Name : "<<x.name<<endl;
cout<<"Age : "<<x.age<<endl;
}
int main() {
person a;
getdata(a);
person b("Raj Mishra", 17);
printdata(a);
printdata(b);
return 0;
}
in the above code, even if i enter the values through the getdata(a) function the values in the default constructor show up on the console screen when the printdata(a) function runs.
This is not the case when i create an object using the constructor like when creating the object b.
What do i do?
|
You have to pass the person object by reference:
class person {
// ...
friend void getdata(person&);
friend void printdata(person const&);
};
void getdata(person& x) {
// ^
std::cout << "Enter name : " << std::endl;
getline(std::cin, x.name);
std::cout << "Enter age : " << std::endl;
std::cin >> x.age;
};
void printdata(person const& x) {
// ^^^^^^
std::cout << "Name : " << x.name << std::endl;
std::cout << "Age : " << x.age << std::endl;
}
Also, you should not use using namespace std;.
|
74,597,018
| 74,597,360
|
Weird "╠" characters output in console from c++ console application (possibly char arrays?)
|
I'm trying to make a program that reads input from a file (it is named grades.txt) and make an output of (image attached)
.
Apparently, I'm converting strings to char arrays and my program's output quite unexpected (image attached) I have checked twice, the IDE doesn't show any errors as well.
I'm using this as the source code.
#pragma warning(disable:4996)
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
//Author: Hidden for privacy
const int MAXNAME = 20;
int main()
{
ifstream inData;
inData.open("grades.txt");
string rawInputString;
char name[MAXNAME + 1]; // holds student name
float average; // holds student average
inData.get(name, MAXNAME + 1);
while (inData)
{
bool firstSpace = false;
bool secondSpace = false;
char converter[23];
getline(inData, rawInputString, '\n');
strcpy(converter, rawInputString.c_str());
for (int a = 0; a <= 22; a++) {
if (converter[a] != ' ') {
cout << converter[a];
}
if (converter[a] == ' ') {
if (!firstSpace) {
firstSpace = true;
continue;
}
if (!secondSpace) {
secondSpace = true;
continue;
}
}
if (firstSpace) {
cout << converter[a];
if (secondSpace) {
cout << converter[a];
}
}
}
}
inData.close();
return 0;
}
Here is the grades.txt file:
Adara Starr 94
David Starr 91
Sophia Starr 94
Maria Starr 91
Danielle DeFino 94
Dominic DeFino 98
McKenna DeFino 92
Taylor McIntire 99
Torrie McIntire 91
Emily Garrett 97
Lauren Garrett 92
Marlene Starr 83
Donald DeFino 73
What I've tried: As seen in the source code, I tried to make the program print the output char by char. But apparently, the first few characters printed are not even in the file where the program is taking input from. I know that float average and char array name are uninitiated, but it doesn't affect the rest of the code (too much), so I'm just leaving those there. I tried reading the fstream library to maybe figure out if this was something caused by the ifstream, but that doesn't seem to be the case either.
|
There are a few different problems in your code, but the main ones is that:
You start with inData.get(name, MAXNAME + 1) which reads only a part of the first line
You iterate over the whole array no matter its string length
The character array converter is just too small to fit a full line including the null-terminator
Among the other problems is that you read from the input file before checking its status; You use while (inData) which is not correct; You use a C-style character array when there's no need; And you forget to print a newline.
There are also better ways to handle the input and output, like using an input string stream to parse out the fields, and use standard I/O manipulators for your output.
If we put it all together I would recommend something like this instead:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <fstream>
int main()
{
std::ifstream infile("grades.txt");
std::string inputline;
// Read line by line from the input, includes error checking
// Also includes checking if the file was opened or not
while (std::getline(infile, inputline))
{
// An input stream to parse out the data we need
std::istringstream parser(inputline);
std::string firstname;
std::string lastname;
int value;
parser >> firstname >> lastname >> value;
// Just construct a simple string of the name
// To simplify "pretty" output
std::string fullname = firstname + ' ' + lastname;
// And finally the output with the name in one column and the value in another
std::cout << std::left << std::setw(20) << fullname << value << '\n';
}
}
|
74,597,058
| 74,635,435
|
Does ATR indicator include the current bar
|
I understand from the MQL4 documentation on the ATR indicator, that it can return the the value of the indicator for the current bar if 0 is used for the shift argument. However, when looking at the MQL5 documentation for the indicator, I notice that there doesn't appear to be any way to determine this. Possibly, this is because the indicator is intended to be used in conjunction with CopyBuffer like so:
// Note that error handling has been omitted in this code
double values[];
int handle = iATR(Symbol(), PERIOD_D1, 10);
CopyBuffer(handle, 0, 0, 1, values);
In this example, I'm retrieving the daily ATR for a period of 10 days and copying the first value of this buffer into an array. So, is values[0] the ATR value for the current day, or the ATR value for the previous day?
|
According to @PaulB, index 0 always represents the current bar. Ergo, this code:
double values[];
int handle = iATR(Symbol(), PERIOD_D1, 10);
CopyBuffer(handle, 0, 0, 1, values);
was retrieving the Daily ATR for the current day, which includes the current bar. In order to fix this, I simply had to change the shift from 0 to 1, like so:
double values[];
int handle = iATR(Symbol(), PERIOD_D1, 10);
CopyBuffer(handle, 0, 1, 1, values);
which retrieves the daily ATR for the previous day.
|
74,597,682
| 74,597,704
|
How to sort a UDT vector in descending order?
|
#include <bits/stdc++.h>
using namespace std;
class Point
{
public:
int x;
int y;
Point(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
bool operator>(const Point &p1)
{
return (x + y) > (p1.x + p1.y);
}
};
int main()
{
vector<Point> v = {{1, 2}, {3, 1}, {0, 1}};
sort(v.begin(), v.end(), greater<Point>());
for (auto i : v)
cout << i.x << " " << i.y << endl;
return 0;
}
I want to sort a UDT vector in descending order. So I tried to overload the operator > as written in the class. But it's giving me error. What should I do to sort the UDT vector in descending order.
This is the error:
In file included from /opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/string:49,
from /opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bitset:52,
from /opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/x86_64-linux-gnu/bits/stdc++.h:52,
from <source>:1:
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/stl_function.h: In instantiation of 'constexpr bool std::greater<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Point]':
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/predefined_ops.h:158:30: required from 'constexpr bool __gnu_cxx::__ops::_Iter_comp_iter<_Compare>::operator()(_Iterator1, _Iterator2) [with _Iterator1 = __gnu_cxx::__normal_iterator<Point*, std::vector<Point> >; _Iterator2 = __gnu_cxx::__normal_iterator<Point*, std::vector<Point> >; _Compare = std::greater<Point>]'
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/stl_algo.h:1819:14: required from 'void std::__insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Point*, vector<Point> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<greater<Point> >]'
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/stl_algo.h:1859:25: required from 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Point*, vector<Point> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<greater<Point> >]'
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/stl_algo.h:1950:31: required from 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Point*, vector<Point> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<greater<Point> >]'
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/stl_algo.h:4893:18: required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<Point*, vector<Point> >; _Compare = greater<Point>]'
<source>:27:9: required from here
/opt/compiler-explorer/gcc-trunk-20221128/include/c++/13.0.0/bits/stl_function.h:398:20: error: no match for 'operator>' (operand types are 'const Point' and 'const Point')
398 | { return __x > __y; }
| ~~~~^~~~~
<source>:17:10: note: candidate: 'bool Point::operator>(const Point&)' (near match)
17 | bool operator>(const Point &p1)
| ^~~~~~~~
<source>:17:10: note: passing 'const Point*' as 'this' argument discards qualifiers
|
Add the word const to your operator> method so that its signature becomes
bool operator>(const Point &p1) const
instead of
bool operator>(const Point &p1)
Adding const to this method means that you inform the compiler that the method won't modify the object that the method is associated with. That is required because greater expects the objects being compared to be constant.
|
74,599,137
| 74,599,426
|
When inheriting a Base class privately, can I declare the Base classes Basse class public?
|
I have a class "SuperBase" with public methods and a class "Base", that derives from SuperBase, also with public methods. I cannot alter these, as they come from an external project.
I want my own class "Derived" to inherit privately from Base, but still keep SuperBase public.
External Code (cannot be changed):
class SuperBase
{
public:
void printSuperBase() const
{
std::cout << "Super Base Class\n";
}
};
class Base : public SuperBase
{
public:
void print() const
{
std::cout << "Base Class\n";
}
};
My own code (can be changed):
class Derived: private Base
{
public:
void print() const
{
std::cout << "Derived Class\n";
}
};
void function(SuperBase const& sb)
{
sb.printSuperBase();
}
int main()
{
Derived D{};
D.print(); //prints "Derived Class\n"
function(D); //cannot access SuperBase, as Base was included privately
}
Note that I cannot override any of the Base class methods, as they are not declared virtual.
Including both, Base and SuperBase does not work as this makes SuperBase ambiguous.
class Derived: private Base, public SuperBase
{
public:
void print() const
{
std::cout << "Derived Class\n";
}
};
void function(SuperBase const& sb)
{
sb.printSuperBase();
}
int main()
{
Derived D{};
D.print(); //prints "Derived Class\n"
function(D); //base class SuperBase is ambiguous
}
Including Base publicly and declaring it's methods as private does not work either, as I now can pass Derived to functions using Base, that can access all privately declared methods
class Derived: public Base
{
public:
void print() const
{
std::cout << "Derived Class\n";
}
private:
using Base::print; //declare base method private to make it inaccessible
};
void function2(Base const& b)
{
b.print(); //prints "Base Class\n", but shall be inaccessible instead.
b.printSuperBase();
}
int main()
{
Derived D{};
D.print(); //prints "Derived Class\n"
function2(D); //D gets passed as Base class, but shall not be allowed
}
|
You could not actually derive from Base or SuperBase at all but rather use composition and cast operators:
class Derived
{
private:
Base mBase;
public:
void print() const
{
std::cout << "Derived Class\n";
}
operator SuperBase const&() const
{
return mBase;
}
operator SuperBase&()
{
return mBase;
}
};
https://gcc.godbolt.org/z/bnsY4e5Wz
|
74,599,245
| 74,599,382
|
rvalue Reference not matching
|
I have this exercise in which we try various combinations of rvalue and lvalue references using a template class, I am getting two assertion errors; if someone could guide.
#include <assert.h>
typedef int& IntLRef;
typedef IntLRef& IntLLRef;
typedef IntLRef&& IntLRRef;
typedef int&& IntRRef;
typedef IntRRef& IntRLRef;
typedef IntRRef&& IntRRRef;
template<typename T, typename U>
struct IsSameType
{
static const bool value = false;
};
template<typename T>
struct IsSameType <T, T>
{
static const bool value = true;
};
static_assert(IsSameType<IntLRef, IntLLRef>::value, "LRef DIF LLRef"); static_assert(IsSameType<IntLRef, IntLRRef>::value, "LRef DIF LRRef"); static_assert(IsSameType<IntLLRef, IntLRRef>::value, "LLRef DIF LRRef");
static_assert(IsSameType<IntRRef, IntRLRef>::value, "RRef DIF RLRef"); static_assert(IsSameType<IntRRef, IntRRRef>::value, "RRef DIF RRRef"); static_assert(IsSameType<IntRLRef, IntRRRef>::value, "RLRef DIF RRRef");
int main();
I am getting assertion error :
rvalue_ex3.cpp:34:48: error: static assertion failed: RRef DIF RLRef
34 | static_assert(IsSameType<IntRRef, IntRLRef>::value, "RRef DIF RLRef");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
rvalue_ex3.cpp:36:49: error: static assertion failed: RLRef DIF RRRef
36 | static_assert(IsSameType<IntRLRef, IntRRRef>::value, "RLRef DIF RRRef");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
akm009@a
I need to make modfications to assert it as true and understand why it is failing
|
This is called reference collapsing:
It is permitted to form references to references through type
manipulations in templates or typedefs, in which case the reference
collapsing rules apply: rvalue reference to rvalue reference collapses
to rvalue reference, all other combinations form lvalue reference
(emphasis added)
Which means that IntRRef which is int&& is not the same as IntRLRef because the latter is defined as IntRRef& which is an lvalue reference to an rvalue reference and thus collapses to an lvalue reference: int&.
|
74,599,752
| 74,599,816
|
Getting "exited with code=3221226356" error (STATUS_HEAP_CORRUPTION) while opening a output file stream
|
As evolution of a school exercise I'm making a program that writes a file in every subfolder starting from the location where the program is executed.
So there is a recursive function and another function called inside that writes the file.
If I execute this I get "exited with code=3221226356" error the second time I'm writing the file (inside the first subfolder, when I create the ofstream)... only while not in debug. After a bit of experiments I removed the recursive call and the files into all the main directories are written. There are no arrays except the input variable (char*), what could be causing this memory leak?
This is the code:
#include <dirent.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <time.h>
#include <limits.h>
const char * separator_char() {
#ifdef _WIN32
return "\\";
#else
return "/";
#endif
}
void createCopy(const char * path) {
const char * separator = separator_char();
char * file_name_path = strdup(path);
strcat(file_name_path, separator);
printf("Writing Roberto.txt...\n");
strcat(file_name_path, "Roberto.txt");
std::ofstream dst(file_name_path, std::ios::binary | std::ofstream::trunc); -- ERROR HERE
dst << "test";
printf("Wrote %s\n", file_name_path);
dst.close();
}
void multiply(const char * path) {
const char * separator = separator_char();
char * path_2 = strdup(path);
strcat(path_2, separator);
DIR * dir = opendir(path);
struct dirent * entry = readdir(dir);
while (entry != NULL) {
if (strcmp(entry -> d_name, ".") != 0 && strcmp(entry -> d_name, "..") && entry -> d_type == DT_DIR) {
char * path_3 = strdup(path_2);
strcat(path_3, entry -> d_name);
printf("%s\n", path_3);
createCopy(path_3);
multiply(path_3);
}
entry = readdir(dir);
}
closedir(dir);
}
int main(int argc, char ** argv) {
const char * PATH = ".";
multiply(PATH);
getchar();
return 0;
}
|
These two lines are a likely problem:
char * file_name_path = strdup(path);
strcat(file_name_path, separator);
The strdup call allocates enough memory for the string you want to duplicate, not a single byte more.
That means the strcat call will cause your program to write pout of bounds of the allocated memory, leading to undefined behavior (and heap corruption).
One possible C-like solution is to use the snprintf function to construct your string. It can be used with a null pointer destination string and a zero size, then will return the number of bytes needed for the string (excluding the null-terminator). Then you can allocate memory for the string, and use snprintf again to actually create the string.
Or since you're programming C++, just use std::string and append as needed. No out-of-bounds problems, no memory leaks (which you also have).
And considering you're dealing with filesystem paths, use std::filesystem::path instead:
void createCopy(std::filesystem::path const& path) {
auto file_name_path = path / "Roberto.txt";
std::ofstream dst(file_name_path, std::ios::binary | std::ofstream::trunc);
dst << "test";
}
|
74,600,130
| 74,600,204
|
How to make a class derived from the same base class twice, in C++?
|
Assuming that there is a class A.
I want my class to derived from A twice, in order to manage two A segment and visit their protected methods.
Like:
typedef A yetA;
class D: public A, public yetA {};
This doesn't work. Is there a method to do that?
|
First off all... I'd caution you to rethink this design, because (barring any other details) it seems a little dodgy. I'm willing to bet composition may very well work better to manage those multiple instances.
But... if you are gonna do this, you can achieve it by intermediate inheritance. Can't have the same direct base appear more than once, but indirection is permissible.
template<int N>
struct ACopy : A {
using A::A;
};
class D: public ACopy<1>, public ACopy<2> {
};
Just go through the corresponding intermediate base for disambiguation purposes.
Alternatively (or additionally), the template ACopy can have using declarations to make the protected members you care about into public ones*. That should facilitate the composition I suggested.
* - An often overlooked aspect of C++ is that "protected" is really "public with some extra steps required".
|
74,601,281
| 74,608,810
|
[hiredis]Multiple hincrbys only return one result(REDIS_REPLY_INTEGER)
|
When using hiredis, use redisAppendCommand to put multiple hincrby commands, the reply->type result of redisGetReply is REDIS_REPLY_INTEGER, and only one of the results is returned.
But when I use hmget, the result of reply->type is REDIS_REPLY_ARRAY.
|
Since you call redisAppendCommand multiple times, you should call redisGetReply the same number of times to get all replies. For each reply, it's of type REDIS_REPLY_INTEGER. Because the reply type of hincrby is integer type, or array type.
The reply type of hmget is array reply, and that's why you get REDIS_REPLY_ARRAY.
Since you tag the question with c++, you can try redis-plus-plus, which is a user-friendly C++ client for Redis and you don't need to parse the reply manually:
auto r = sw::redis::Redis("tcp://127.0.0.1:6379");
for (auto idx = 0; idx < 5; ++idx) {
r.hincrby("key", "field", 1);
}
std::vector<std::string> fields = {"f1", "f2"};
std::vector<std::optinal<std::string>> vals;
r.hmget("key", fields.begin(), fields.end(), std::back_inserter(vals));
Disclaimer: I'm the author of redis-plus-plus.
|
74,601,373
| 74,603,447
|
Is owning the lock required to request a stop while waiting on a condition_variable_any with stop_token?
|
While waiting on a condition variable, the thread changing the state of the predicate must own the lock, so the update isn't missed during the wakeup. According to the documentation, this is necessary, even while using atomic variables.
However I'm not certain if request_stop() already handles it correctly.
So the question is, which of the two options is the correct and standard conforming one?
~jthread() naturally doesn't take a lock to request_stop(), but then I don't understand where the difference between a stop_token and an atomic shared variable is. And thereby, how one of them requires the lock, while the other doesn't.
#include <thread>
#include <condition_variable>
#include <iostream>
#include <chrono>
std::mutex m;
std::condition_variable_any cv;
void waitingThread(std::stop_token st){
std::unique_lock<std::mutex> lk(m);
std::cout<<"Waiting"<<std::endl;
cv.wait(lk, st, [](){return false;});
std::cout<<"Awake"<<std::endl;
}
void withoutLock(){
std::jthread jt{waitingThread};
std::this_thread::sleep_for(std::chrono::seconds(1));
jt.request_stop();
}
void withLock(){
std::jthread jt{waitingThread};
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(m);
jt.request_stop();
}
}
int main(){
withoutLock();
withLock();
}
std::condition_variable specifies:
Even if the shared variable is atomic, it must be modified while owning the mutex to correctly publish the modification to the waiting thread.
std::condition_variable_any::wait,
std::stop_token
and
std::stop_source
do not specify, if the interrupt of the wait is guaranteed register the change in the stop state.
|
While waiting on a condition variable, the thread changing the state of the predicate must own the lock, so the update isn't missed during the wakeup.
... do not specify, if the interrupt of the wait is guaranteed register the change in the stop state.
The issue isn't exactly missing the update, but going back to sleep after the notify has happened and before checking the predicate again.
The sequence in this answer is the problematic one.
According to the documentation, this is necessary, even while using atomic variables. However I'm not certain if request_stop() already handles it correctly.
The shared state itself is synchronized just fine: thread.stoptoken.intro/5 says
Calls to the functions request_stop, stop_requested, and stop_possible do not introduce data races.
A call to request_stop that returns true synchronizes with a call to stop_requested on an associated stop_token or stop_source object that returns true.
The wait-predicate loop described in thread.condvarany.intwait would have the same problem:
while (!stoken.stop_requested()) {
if (pred())
return true;
wait(lock);
}
return pred();
if request_stop is called between the first line and the wait(lock), then stop_requested() will become true and the condition variable be notified while nobody is waiting. Then we'll start waiting, for a notification that never comes.
If request_stop can only be called while the mutex is released inside wait, we'll always be guaranteed to check stop_requested() before sleeping again.
In fact though, the GNU ISO C++ library does this for us: std::condition_variable_any has an additional internal mutex used to synchronize the request_stop callback (which just notifies the condvar in the requesting thread) correctly with the wait-predicate loop. So, if that behaviour is required by the standard, you don't need your own mutex here.
|
74,601,482
| 74,601,821
|
How to merge two numbers from two sorted files into a third file in ascending order
|
I'm trying to merge two files that contain some numbers into a third file but I'm not getting the right result.
This is my code:
void merge(string input_file1, string input_file2, string output_file){
fstream fs1;
fstream fs2;
fstream fs3;
int n1, n2;
fs1.open(input_file1);
fs2.open(input_file2);
fs3.open(output_file);
while(fs1 >> n1 && fs2 >> n2){
if(n1 < n2){
fs3 << n1 << " ";
fs1 >> n1;
}
else{
fs3 << n2 << " ";
fs2 >> n2;
}
}
while(fs1 >> n1)
fs3 << n1 << " ";
while(fs2 >> n2)
fs3 << n2 << " ";
}
input:
input file1: 1 2 3 4 5 6 7
input file2: 34 56 77 78 88 90 100
output file: 1 3 5 7 88 90 100
|
If n1 < n2, you do fs1 >> n1 twice (once immediately and then once in the loop condition) and discard both the first value and n2; if n1 >= n2, you do fs2 >> n2 twice and discard both its first value and n1.
You can't do any unconditional reading in the "selection loop", as you should only replace the smallest number.
Something like this (untested):
// Potentially read the first two numbers.
fs1 >> n1;
fs2 >> n2;
// This loop is entered only if there were two numbers.
// Note that the last successfully read number is written only for the shorter input (if any).
while (fs1 && fs2)
{
if (n1 < n2)
{
fs3 << n1 << ' ';
fs1 >> n1;
}
else
{
fs3 << n2 << ' ';
fs2 >> n2;
}
}
// Write-then-read because the last value read has not been written yet.
while (fs1)
{
fs3 << n1;
fs1 >> n1;
}
while (fs2)
{
fs3 << n2;
fs2 >> n2;
}
|
74,601,668
| 74,602,289
|
Is it possible to terminate (compute) shader execution in OpenGL?
|
I have a compute shader that computes the Mandelbrot set. For deeper zooms this can take minutes. Is it possible to terminate the compute shader (for example if I pan or change zoom while it computes)? I'm using C++.
I guess I could let the shader do its computation in stages and check on the CPU-side if parameters have changed. But I think this would cost performance and would make the code a little messy...
Does anybody know a clean, fast and easy way to do this?
|
There is no valid way to affect the execution of any OpenGL operation after it has already been told to execute. If you dispatch the work, you dispatched the work. You can't take it back later.
|
74,602,153
| 74,602,220
|
C++ Parenthesis Operator Overloading Error
|
I am getting an unexpected error trying to implement ()-overloading according to the following get_chessman() method in a chessboard class: "expression preceding parentheses of apparent call must have pointer to function type". Am I overloading in the wrong way?
Minimal example code:
In chessboard header:
class Chessboard
{
private:
Chessman** board;
int size;
bool turn; // 1 for white, 0 for black
public:
Chessboard(int size = 8);
~Chessboard();
bool is_whites_turn() const;
bool is_game_over() const;
int get_size() const { return size; }
Chessman* operator() (int row, int col) const; // <------ overloading
Chessman* get_chessman(int row, int col) const; // reference method
}
Implementation:
Chessman* Chessboard::operator()(int row, int col) const
{
return &board[row][col];
}
Chessman* Chessboard::get_chessman(int row, int col) const
{
return &board[row][col];
}
Result:
int main() {
cout << "hello Chess" << endl;
//Chessboard cb();
Chessboard* cb = new Chessboard();
cb->show();
Chessman* cm = cb->get_chessman(7,4);
cout << cm->get_symbol() << endl;
Chessman* cm1 = cb(7, 4); // ERROR: expression preceding parentheses of apparent call must have (point-to-) function
cout << cm1->get_symbol() << endl;
return 0;
}
|
Just like you dereference cb in cb->get_chessman(7,4), you must dereference it in the line in question, like (*cb)(7, 4).
Side note: the way you code is reminiscent of Java where everything is a pointer. You should probably make use of simple variables, references, and standard containers (among other things) when coding in C++. Example:
class Chessboard
{
private:
std::vector<std::vector<Chessman>> board;
int size;
bool turn; // 1 for white, 0 for black
public:
Chessboard(int size = 8);
~Chessboard();
bool is_whites_turn() const;
bool is_game_over() const;
int get_size() const { return size; }
Chessman const& operator() (int row, int col) const; // <------ overloading
Chessman const& get_chessman(int row, int col) const; // reference method
void show();
};
Chessman const& Chessboard::operator()(int row, int col) const
{
return board[row][col];
}
Chessman const& Chessboard::get_chessman(int row, int col) const
{
return board[row][col];
}
int main() {
std::cout << "hello Chess" << std::endl;
Chessboard cb;
cb.show();
auto cm = cb.get_chessman(7,4);
std::cout << cm.get_symbol() << std::endl;
auto cm1 = cb(7, 4);
std::cout << cm1.get_symbol() << std::endl;
}
|
74,602,934
| 74,603,981
|
how does this template parameter deduction work?
|
How did compiler decide to call bar function without knowing the type of template parameter T of foo function?
Usually when we call foo(2), T is deduced as int based on argument 2.
Here T is deduced based on parameters of function bar to which foo is passed.
#include <iostream>
template<typename T>
void foo(const T& a_) {
std::cout << a_<< std::endl;
}
void bar(void (*ptr) (const int&)) {
std::cout << "bar called" << std::endl;
}
int main() {
bar(foo);
}
compiler: gcc
|
When you have an overload set like foo, meaning that the result of name lookup for foo results in (potentially multiple) non-template functions or function templates and the overload set has its address or a reference taken (here implicitly by passing it as a function argument), then the compiler will try to do overload resolution against the target type if there is any. The target type here is void(*)(const int&). The whole procedure is specified in [over.over], parts of which I explain below.
The way this works is that the compiler will look at each function and function template in the overload set, will look whether it can match its type against the target type and will then add those functions and function template specializations that match to a set of selected overloads. Afterwards a few more elimination steps are done to reduce the set of selected overloads (e.g. checking whether associated constraints are satisfied and preferring functions over function template specializations, see [over.over]/5 for all details) and hopefully at the end exactly one selected function or function template specialization remains, which will then be chosen as the result of overload resolution that the original name (foo) refers to and from which the address/reference is taken.
For a non-template function a match means that the function type of the target ( void(const int&)) needs to simply be identical to the function's type. But you don't have any non-template overload here.
For a function template the compiler will try to perform template argument deduction to select one specialization of the template that matches the type and can be added to the list of selected overloads. Specifically this works just the same as in template argument deduction of a function call where there is usually a list of function argument/parameter pairs to deduce template arguments from, but in this case (given that there is a target type) the deduction will consider only one argument/parameter pair with the argument being the target type (void(*)(const int&)) and the parameter being the function type of the template containing the template parameters, i.e. here void(const T&), adjusted to a pointer type void(*)(const T&) because the argument is a function pointer type.
So in the end the compiler will perform normal deduction of
void(*)(const int&)
against
void(*)(const T&)
to decide what T should be in the selected specialization. I guess it is pretty obvious that T should be int for the types to match. So the selected specialization will be the one with T = int which has a function type matching the target type and since it is the only selected overload and since it will not be eliminated in any of the further steps, it will be chosen as the result of overload resolution.
|
74,603,194
| 74,605,112
|
Is it possible to get a HMONITOR Handle from a Windows Object Manager Path?
|
I have a path that looks like this:
\\?\DISPLAY#IVM1A3E#5&1778d8b3&1&UID260#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
From that I would like to get a HMONITOR handle.
Using WinObj I can see under GLOBAL?? that it's a Symbolic link to some \Device\<number>.
How would I go about doing something like that?
Edit:
The path can be split in three parts. First the \\?\ prefix, then second DISPLAY#IVM1A3E#5&1778d8b3&1&UID260 if the # are replaced by \ it is the same as the device instance ID. Thirdly {e6f07b5f-ee97-4a90-b076-33f57bf4eaa7} is the GUID for Monitor devices.
With the device instance ID I can walk the device tree using CM_Get_Child and CM_Get_Sibling, checking the device names with CM_Get_Device_ID. But that only gives me a DEVINST not a HMONITOR.
|
You can use Connecting and configuring displays (CCD) API, especially the The QueryDisplayConfig function which retrieves information about all possible display paths for all display devices, or views, in the current setting.
With the following code, you'll get the correspondance between a Device Path and a Monitor (and its handle).
#include <Windows.h>
#include <stdio.h>
#include <vector>
#include <tuple>
#include <string>
int main()
{
// get all paths
UINT pathCount;
UINT modeCount;
if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &pathCount, &modeCount))
return 0;
std::vector<DISPLAYCONFIG_PATH_INFO> paths(pathCount);
std::vector<DISPLAYCONFIG_MODE_INFO> modes(modeCount);
if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &pathCount, paths.data(), &modeCount, modes.data(), nullptr))
return 0;
// enum all monitors => (handle, device name)>
std::vector<std::tuple<HMONITOR, std::wstring>> monitors;
EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hmon, HDC hdc, LPRECT rc, LPARAM lp)
{
MONITORINFOEX mi = {};
mi.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(hmon, &mi);
auto monitors = (std::vector<std::tuple<HMONITOR, std::wstring>>*)lp;
monitors->push_back({ hmon, mi.szDevice });
return TRUE;
}, (LPARAM)&monitors);
// for each path, get GDI device name and compare with monitor device name
for (UINT i = 0; i < pathCount; i++)
{
DISPLAYCONFIG_TARGET_DEVICE_NAME deviceName = {};
deviceName.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
deviceName.header.size = sizeof(DISPLAYCONFIG_TARGET_DEVICE_NAME);
deviceName.header.adapterId = paths[i].targetInfo.adapterId;
deviceName.header.id = paths[i].targetInfo.id;
if (DisplayConfigGetDeviceInfo((DISPLAYCONFIG_DEVICE_INFO_HEADER*)&deviceName))
continue;
wprintf(L"Monitor Friendly Name : %s\n", deviceName.monitorFriendlyDeviceName);
wprintf(L"Monitor Device Path : %s\n", deviceName.monitorDevicePath);
DISPLAYCONFIG_SOURCE_DEVICE_NAME sourceName = {};
sourceName.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
sourceName.header.size = sizeof(DISPLAYCONFIG_SOURCE_DEVICE_NAME);
sourceName.header.adapterId = paths[i].targetInfo.adapterId;
sourceName.header.id = paths[i].sourceInfo.id;
if (DisplayConfigGetDeviceInfo((DISPLAYCONFIG_DEVICE_INFO_HEADER*)&sourceName))
continue;
wprintf(L"GDI Device Name : %s\n", sourceName.viewGdiDeviceName);
// find the monitor with this device name
auto mon = std::find_if(monitors.begin(), monitors.end(), [&sourceName](std::tuple<HMONITOR, std::wstring> t)
{
return !std::get<1>(t).compare(sourceName.viewGdiDeviceName);
});
wprintf(L"Monitor Handle : %p\n", std::get<0>(*mon));
wprintf(L"\n");
}
return 0;
}
On my PC (with 2 monitors), it will output something like this:
Monitor Friendly Name : C27HG7x
Monitor Device Path : \\?\DISPLAY#SAM0E16#7&307b5912&0&UID1024#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
GDI Device Name : \\.\DISPLAY2
Monitor Handle : 0000000000160045
Monitor Friendly Name : DELL U2715H
Monitor Device Path : \\?\DISPLAY#DELD069#7&307b5912&0&UID1028#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
GDI Device Name : \\.\DISPLAY1
Monitor Handle : 0000000000020083
Note you can also get the same information using WinRT's DisplayManager class => DisplayView class => Paths property, DisplayPath class, => Target property => TryGetMonitor function
|
74,604,020
| 74,604,315
|
File not updating after reading and writing
|
I am trying to read and write to a file.
My file contains just one line that has a value.
and this is my code where I am trying to calculate a mean value and write it in the file instead of the first one, but the file keeps containing 37.
long int moy;
std::string line;
std::fstream file;
long int x = 35 + ( std::rand() % ( 37 - 35 + 1 ) );
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::out | std::ios::in);
std::getline(file, line);
std::cout<<line<<endl;
moy=(x+stoi(line))/2;
file<<moy<<endl;
file.close();
The x variable contains different value every time, I also tried to write a string directly: file<<"test"<<endl; but still not updating.
|
The simple way is to close the file before reopening it for writing.
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::in);
std::getline(file, line);
file.close();
std::cout<<line<<endl;
moy=(x+stoi(line))/2;
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::out);
file<<moy<<endl;
file.close();
If you don't want to do that then you need to clear any error, and then reposition the file to the beginning.
file.clear(); // clear any error
file.seekp(0); // position file at beginning
The problem with this method is that it will not replace existing content. If your new line is shorter than the old line then the trailing characters of the old line will remain.
|
74,605,126
| 74,605,903
|
Compile and execute cpp in xcode, and add additional execution instructions, Such as iconv command
|
Sorry, I'm new to Xcode and not very familiar with it, I use Xcode (command line tool project with external build system) to compile cpp files and automatically execute cpp unix executable files. After the program is compiled (command+R), I set the settings as shown in the screenshot below to automatically execute. Is there any way for me to execute also add additional commands?
Such as iconv.
The following line is what I ultimately want to execute.
./myFile argument1 | iconv -f big5
But my Xcode looks like it's executing only
./myFile argument1
really thanks
|
On the same place where you setup the build scheme, you can also add a post-build script.
Go to the left of the panel, and expand Build
Select Post-actions
Near the bottom center, click on + -> New Run Script Action
Add script like you would run them in terminal
Note the current directory will not be where the project is built
You can use ${TARGET_BUILD_DIR} macro for the build directory
Note, you want to make sure to select your current project at the Provide build settings from so it can import the correct path macros like TARGET_BUILD_DIR
A screenshot of adding a post-build script:
*Older versions of Xcode might have different GUI, but the idea should be about the same.
Sidenote, ⌘R is really for running the program within Xcode, consider using ⌘B.
|
74,605,269
| 74,605,874
|
How does GCC optimize this `switch`
|
Today I discovered that GCC does some amazing magic for optimizing switches in this code:
StairsType GetStairsType(uint8_t tileId, uint8_t dlvl)
{
if (dlvl == 0)
return StairsType::Part;
if (tileId == 48) {
return dlvl >= 21 ? /* Crypt */ StairsType::Down : /* Caves */ StairsType::Part;
}
switch (tileId) {
case 57: return StairsType::Down;
// many more tile IDs go here
}
}
Have a look at this :
https://godbolt.org/z/snY3jv8Wz
(gcc is on the left, clang is on the right)
Somehow GCC manages to compile this to 1/4 of the code compared to Clang.
What does this asm do, conceptually?
How does GCC do this?
|
Both compilers compile this part in the obvious way:
if (dlvl == 0)
return StairsType::Part;
When it comes to this part:
if (tileId == 48) {
// This ID is used by both Caves and Crypt.
return dlvl >= 21 ? /* Crypt */ StairsType::Down : /* Caves */ StairsType::Part;
}
gcc checks tileId==48 directly, while clang decides to merge it into the switch statement.
Both compilers decide to calculate dlvl >= 21 ? 1 : 4 branchlessly in more-or-less the same way, but with different exact instructions. GCC sneakily uses the carry flag to calculate ((dlvl >= 21 ? 0 : -1) & 3) + 1 while clang straightforwardly calculates ((dlvl < 21) * 3) + 1.
// GCC
cmp sil, 21
sbb eax, eax
and eax, 3
add eax, 1
// clang
xor eax, eax
cmp sil, 21
setb al
lea eax, [rax + 2*rax]
inc eax
When it comes to the switch statement, clang implements it with a jump table. The lowest entry is 16 and the highest is 160, so it subtracts 16 and then checks whether the number is greater than 144. There's a well-known trick to save one check, where numbers smaller than 16 wrap around to very big numbers, so they're greater than 144. For whatever reason, it chooses to preload the number 1 (StairsType::Down) into the return value register before doing the jump.
Meanwhile on gcc, it first checks if the tile ID is between 16 and 78. If so, it subtracts 16 and checks some bitmasks:
if(tileID < 16) {
return 0;
} else if(tileID <= 78) {
mask = (1 << (tileID - 16));
if(2307251517974380578 & mask) return 2;
if(4611688220747366401 & mask) return 1;
return ((421920768 & mask) != 0) << 2;
} else {
tileID += 125; // The same as tileID -= 131
// because it's being treated as a byte
if(tileID > 29) { // values lower than 131 wrapped around
return 0;
}
// notice that if we get here it means the tileID is >= 131 and <= 160
// << only looks at the bottom 5 bits of tileID (i.e. tileID & 31)
return -((541065279 & (1 << tileID)) != 0) & 3;
}
Let's try that again, but with the bitmasks in binary and let's figure out what those return statements return:
if(tileID < 16) {
return StairsType::Invalid;
} else if(tileID <= 78) {
mask = (1 << (tileID - 16));
// tile 17, 21, 35, 36, 38, 51, 56, 64, 66, 77
if(0010000000000101000000010000100000000000010110000000000000100010 & mask) return StairsType::Up;
// tile 16, 39, 40, 46, 47, 57, 78
if(0100000000000000000000100000000011000100100000000000000000000001 & mask) return StairsType::Down;
// tile 33, 34, 37, 40, 43, 44
return ((00011001001001100000000000000000 & mask) != 0) ? StairsType::Part : StairsType::Invalid;
} else {
if(tileID < 131 || tileID > 160) {
return 0;
}
// tile 131, 132, 133, 134, 135, 136, 153, 160
return (00100000010000000000000000111111 & (1 << (tileID - 131))) ? StairsType::ShortcutToTown : StairsType::Invalid;
}
Seems that the compiler noticed that you grouped your tile IDs into somewhat logical groups. E.g. above 130 there are only shortcuts to town.
I have no idea how compiler writers come up with this stuff.
|
74,605,459
| 74,605,468
|
C++ - How to use preprocessor if statements(#if, #elif, #endif) inside a macro?
|
I am currently developing a program that I intend to be portable. I have access to both Windows and macOS, and I would like to be able to debug easily on both. When error handling, I want to have debug breaks in there to make it easy(__debugbreak() for MSVC). Since I intend to develop and test on multiple platforms, I would like to make a macro to do something like this:
#define DEBUG_BREAK #ifdef DEBUG\
#if _MSC_VER \
__debugbreak(); \
#elif __GNUC__ \
__builtin_trap(); \
#endif \
#endif
So I can write DEBUG_BREAK anywhere I want to break code when debugging on any platform. When I use this macro, I get the error '#' not expected here.
I found two somewhat related questions:
How to use #if inside #define in the C preprocessor?
C preprocessor #if expression
But neither of them answered my question, as they were trying to accomplish different things.
So my question is: How can I have preprocessor if statements inside of a macro if that is allowed? If it isn't possible, what can I do to get the same functionality this broken DEBUG_BREAK macro is trying to do?
Note: DEBUG is defined when compiling for debugging; it is not defined when compiling for release.
|
You can't. But you can do this:
#ifdef DEBUG
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak();
#else
#define DEBUG_BREAK __builtin_trap();
#endif
#else
#define DEBUG_BREAK /*nothing*/
#endif
|
74,605,769
| 74,605,833
|
Can't multiply two matrices, where hight and width are defined by template
|
I wrote Class Matrix, parameters of which I define by template. So when I tried to declare operator* between two matrices, I found out? that Cpp counts matrices with different parameters as different classes (For example 7x3 and 3x5). How can I avoid this?
Here is my class
template <size_t N, size_t M, typename T = int64_t>
class Matrix {
public:
Matrix();
Matrix(std::vector<std::vector<T>> const input);
Matrix(const T elem);
Matrix operator+(const Matrix& other) const;
Matrix& operator+=(const Matrix& other);
Matrix operator-(const Matrix& other) const;
Matrix& operator-=(const Matrix& other);
Matrix operator*(const T& other) const;
Matrix& operator*=(const T& other);
Matrix operator*(const Matrix& other) const;
Matrix& operator*=(const Matrix& other);
Matrix Transposed();
T Trace();
T& operator()(const size_t i, const size_t j) const;
bool operator==(const Matrix& other) const;
private:
};
Cppref did not helped :(
|
Template arguments are part of the type; otherwise they couldn't be considered in type resolution and SFINAE. Thus, there are two choices:
either make N, M runtime arguments of e.g. Matrix (or can even be deduced from current input), thereby making it non-template, or
you live with the fact that the concrete class depends on N, M and, optionally, you might have a base class where this part of the type is erased; or, if you don't need a common base type, you might have the operator as a template and then you might have a different Matrix on the rhs.
The latter can be like this:
typename<T = int64_t>
class Matrix {
Matrix();
Matrix(std::vector<std::vector<T>> const input);
Matrix(const T elem);
// other operators, functions
virtual Matrix operator*(const Matrix& other) const;
};
template <size_t N, size_t M, typename T = int64_t>
class FixedSizeMatrix : Matrix<T> {
// as now, possibly with override when appropriate
Matrix<N, M1> operator*(const Matrix& other) const override /* final? */;
};
However, this will be slower, due to virtual resolution. If you don't need a common base:
template <size_t N, size_t M, typename T = int64_t>
class Matrix {
public:
// as before
template<size_t N1, size_t M1, typename T2 = int64_t>
Matrix operator*(const Matrix<N1, M1, T2>& other) const;
};
Main question to ask yourself is, why you want `N, M` to be compile-time arguments.
|
74,606,432
| 74,606,521
|
how to run consecutive commands in CMD when the first command starts a different instance (e.g. mysql -u root)
|
I'm stuck on a problem where I can't find a reasonable work around.
I'm trying to run multiple commands in the Windows CMD from inside a C++ Program using
CreateProcessW(NULL,L"mysql -u root -ptoor && source C:\Users\IEUser\Documents\SWE-Software\Datenbank\datenbank-build.sql", ... );
The Problem is that when i run this code (or even when I manually put in the the CMD Window, that the second half of the command won't run since prior to this it changes the "instance?" of the CMD to that of the mysql executable.
How would I fix or work around this?
I know in python you can somewhat simulate typing in a way, which could potentially be a work around here.. But i prefer a simple solution without any external libraries.
EDIT: To clarify the first Command seems to run since I can literally see the new console text of the mysql command. Its just that the second command won't be copied in there. It just stays blank and waits for input.
EDIT: This is the Output I'm getting:
What I do want is this:
SOLUTION
you can run normal statements in cmd before e.g.set PATH=\%PATH\%;
then you would use an operator like &&.
When you want to an mysql statement it has a special syntax we can use here:
mysql -u username -ppassword -e "ANY VALID MYSQL STATEMENT GOES IN HERE"
e.g.:
set PATH=\%PATH\%;C:\\mariadb\\bin && mysql -u root -ptoor -e "source C:\Users\IEUser\Documents\SWE-Software\Datenbank\datenbank-build.sql"
If you encounter problems with your cmd try adding an cmd /c at the start of the whole statement.
Also if mysql statement fails replace the path code with a cd mariaspath\bin, this made everything work for me.
FINAL CODE AS IT RAN IN CMD cmd /c set PATH=%PATH%;C:\Program Files\MariaDB 10.10\bin\ && mysql -u root -ptoor -e "source C:\Users\IEUser\Documents\SWE-Software\Datenbank\datenbank-build.sql" -q (note that those were ofc not hard coded but obtained at runtime.
|
Update:
It turns out there is another problem that masked what will become a follow-on problem with &&:
Your mysql -u root -ptoor command enters an interactive session, which requires manual exiting before processing continues.
Once you make this call non-interactive, you need to apply the cmd /c fix described below.
However, based on your latest feedback it appears that you mistakenly thought that you could send the mysql command string that starts with source ... to the interactive session via &&, which cannot work. If anything, you'd have to provide such a string via stdin (echo source ... | mysql ..., for which you'd need cmd /c too), though the better option is use arguments, as shown in this answerlink courtesy of drescherjm.
Since you're trying to use a shell operator, &&, you must call via that shell's CLI, i.e. via cmd /c on Windows:
CreateProcessW(NULL,L"cmd /c mysql -u root -ptoor && source C:\Users\IEUser\Documents\SWE-Software\Datenbank\datenbank-build.sql", ... );
As noted, && by design only executes its RHS command if the LHS one signaled success (via an exit code of 0).
As for what you tried:
Without cmd /c, all arguments starting with && are passed as additional, verbatim arguments to mysql.
|
74,606,679
| 74,606,758
|
Why are you allowed to re-define a extern variable in c++?
|
I have an extern variable declared in driver.h:
namespace org::lib {
extern bool myVar;
void myFunction();
}
I also have it defined in driver.cpp:
#include driver.h
namespace org::lib {
bool myVar = false;
void myFunction(){
if (myVar){
//....
}
}
}
Now I have main.cpp which redefines myVar:
#include driver.h
using org;
int main(int arc, char** argv){
lib::myVar = true; //redefines it to be true, while it was defined as false in driver.cpp
lib::myFunction();
}
Why doesn't compiling main.cpp give me a redefinition error on myVar ? Isn't it defined already in driver.cpp, and redefined again in main.cpp ?
Ah never mind, you are re-assigning it in main.cpp.
|
You don't define the variable in main, you assign it a new value
|
74,606,777
| 74,607,051
|
Enabling certain template parameters based on user provided template arguments
|
Consider the following class template:
template<class T, std::size_t S, SomeEnum = SomeEnum::NOT_DYNAMIC>
class Foo {
Where SomeEnum would be defined as
class SomeEnum { NOT_DYNAMIC, DYNAMIC };
This class has a private std::array, but based on the value passed by the user to SomeEnum, I would like to instead use std::vector. For example, if the user passes SomeEnum::DYNAMIC, I would use std::vector instead of std::array. This would be implemented through std::conditional_t and [[no_unique_address]].
I am wondering if there is a way to "remove" the non-type template parameter S, in case the user passed SomeEnum::DYNAMIC. This is to avoid having the user type a size, when it is unnecessary because the underlying contaier is std::vector. Meanwhile, I need to keep the S parameter in case the user does not pass anything to SomeEnum, because std::array requires the size too.
Is it possible with some trickery, and if not, how would I solve this?
Current thoughts:
Using std::conditional_t as explained,
Using inheritance, or using a specialization (not yet attempted or thought of)
Polymorphism is NOT an option
|
A similar situation in the standard library exists with std::span<T, N> or std::span<T>: Omitting the template parameter entirely defaults the size to std::dynamic_extent ((std::size_t) -1), which you can use to have a std::vector instead of a std::array:
template<class T, std::size_t S = std::dynamic_extent>
class Foo {
private:
std::conditional_t<(S == std::dynamic_extent), std::vector<T>, std::array<T, S>> container;
};
|
74,607,691
| 74,607,817
|
Substituting a reserved value dynamically doesn't work
|
I am trying to copy one dynamically reserved array into another, both of which are placed in a vector. But it does not work. Why?
struct A {
int *p;
};
int main()
{
vector<A> v;
A test;
test.p = new int[5];
//fill the array
for (int i = 0; i < 5; i++)
test.p[i] = i;
v.push_back(test);
A test2;
test2.p = new int[10];
//fill the array
for (int i = 0; i < 10; i++)
test2.p[i] = i;
delete[] test.p;
//reallocate test to test2
test.p = new int[10];
//copy test2 to test
for (int i = 0; i < 10; i++)
test.p[i] = test2.p[i];
//delete test2
delete[] test2.p;
//print the array
for (int i = 0; i < 10; i++)
cout << v[0].p[i] << endl;
return 0;
}
My output is:
0
0
-997294064
32767
4
0
33
0
-997220688
32767
|
The only thing in A is a pointer. When you push a copy of test to the vector, notice that the copied version in the vector will have a pointer pointing to the same location as the one that's not in the vector.
So later, when you delete the data from the outside copy, you are also deleting the data from the one in the vector, because both of them are pointing to the same data.
Next part, you reallocated more memory for test through new int[10]. So now test.p is pointing to another memory location. However, this does not have any effect to the copy in the vector, because the one in the vector is still pointing to the old location. You can only change where it is pointing at manually.
Because of that, the one in the vector lost its 5 original data, and was never updated with the 10 new data.
To make it work, you can reassign the pointer in the vector manually to the one outside the vector after you have allocated the new memory for the outside one:
v[0].p = test.p;
|
74,608,229
| 74,609,229
|
Do two consecutive DirectX 12 Dispatch() calls run sequentially or concurrently on the GPU?
|
When running two Dispatch() calls consecutively, like:
m_computeCommandList->Dispatch(111, 1, 1);
m_computeCommandList->Dispatch(555, 1, 1);
Is it guaranteed that the second Dispatch() will run after the first Dispatch() on the GPU? Or, could they run concurrently on the GPU?
Just to clarify, there is no more C++ code in between those two Dispatch() calls.
|
Like in other graphics API, when you execute command calls on CPU side it leads to putting these commands to a command queue. It guarantees that commands will be processed in the order of queue, First-In-First-Out.
However, on GPU everything becomes massive parallel and concurrent. We can't know on what processing unit the actual execution will be scheduled, or what threads from what Dispatch will be finished earlier. Typically it's not a problem if there are no resources (buffers, textures) shared between invocations, and we need to synchronize only the end of frame.
If there is resource sharing, there is a possibility of some memory conflicts ("write-read", "write-write" or "read-write"). Here we need to use resource barriers that allow us to organize access to these resources. Using different options for barriers you can reach the consecutive execution of different Dispatch calls.
For example, a transition from D3D12_RESOURCE_STATE_UNORDERED_ACCESS to D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE|D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE will wait for ALL preceding Graphics and Compute shader execution to complete, and block ALL subsequent Graphics and Compute shader execution.
Enhanced barriers in DirectX 12 allow you to get fine-tuned control on resource and execution synchronization.
|
74,608,299
| 74,608,300
|
How can I use the control key as a wxWidgets accelerator on a Mac?
|
wxWidgets seems biased towards Windows, as 'Ctrl' binds to the control key on a Windows machine, but is converted to the command key on a Mac.
menuFile->Append(CONNECT_KEYSTROKE, wxT("&Connect\tCtrl-R"));
The code above shows up as ⌘R in your menu.
How do you bind to the control key on a Mac?
|
Use 'RawCtrl'
menuFile->Append(CONNECT_KEYSTROKE, wxT("&Connect\tRawCtrl-R"));
The code above shows up as ^R in your menu.
|
74,608,824
| 74,609,365
|
Difference between "using namespace name::space;" vs "namespace name::space{}"?
|
I have a namespace defined in A.h
namespace org::lib{
bool xyz = true;
}
I have B.cpp
#include A.h
namespace org::lib {
void function() {
if (lib::xyz){
//....
}
}
}
Why is lib::xyz in void function() able to correctly find 'xyz'? Since I'm already under org::lib namespace in B.cpp, doing an lib::xyz will try to find org::lib::lib namespace, which doesn't exist. What am I missing?
Now, if I change B.cpp to be:
#include A.h
using namespace org::lib;
namespace{
void function() {
if (lib::xyz){
//....
}
}
}
Now the lib::xyz is unidentified, and I have to replace it with xyz.
I guess it boils down to, what is the difference between:
using namespace org::lib
vs
namespace org::lib{
}
Are they not both saying "the following code is now under the namespace org::lib ?
|
Name lookup proceeds from the scope the name is used outwards.
In the first example, the definition of function is nested inside namespace lib which is nested inside namespace org. When lib is looked up, first the function itself is searched, then org::lib, then org, and naturally lib is there.
In the second example, names from org::lib are brought into scope in the global namespace. Nothing is done with names from org.
|
74,608,858
| 74,609,002
|
Find max in pair vector c++
|
I have a pair vector in c++
std::vector<std::pair<long, long>> currNodeAndChain
I want to find the maximum of the second element. Then push the first element to another vector corresponding to the max second element.
for (const auto& p : currNodeAndChain){
if (total_longest_chain(currNodeAndChain.begin(),
currNodeAndChain.end(),
[](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; })==p.second){
result.push_back(p.first);
}
}
//pseudocode
//for (const auto& p : currNodeAndChain){
// if (max==p.second){
// result.push_back(p.first);
//}
But I'm getting the error: ‘total_longest_chain’ was not declared in this scope.
|
you can try this:
// #include <algorithm> for sort
std::sort(currNodeAndChain.begin(), currNodeAndChain.end(),
[&](const auto& lhs, const auto& rhs)
{
return lhs.second > rhs.second;
});
result.push_back(currNodeAndChain.front().first);
|
74,608,902
| 74,609,155
|
How to make `enable_if` a hard requirement
|
This answer contains the following code:
#include <type_traits>
template<
typename T, //real type
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
> struct S{};
int main() {
S<int> s; //compiles
S<char*> s; //doesn't compile
}
The requirement that T satisfy is_arithmetic can easily be defeated, though, by specifying an arbitrary second type argument for the template S, e.g. S<char*, void>. Is there a way to foreclose this possibility?
|
Is there a way to foreclose this possibility?
Yes, there is as shown below. In particular, we can make the second parameter a non-type parameter with a default.
template<
typename T,
//make the second parameter a non-type parameter with default
typename std::enable_if<std::is_arithmetic<T>::value, nullptr_t>::type N = nullptr
> struct S{};
int main() {
S<int> s; //compiles
//S<int, void> S2; //DOESN'T COMPILE
//S<int, 1> S3; //DOESN'T COMPILE
}
|
74,609,137
| 74,609,223
|
Is there any case that the atomicity of std::atomic is not guaranteed, when is_lock_free() == false?
|
Even if is_lock_free() == false , typically maybe, the atomicity of std::atomic can be guaranteed. Is that right?
I wander that there are computer environments or cases where the atomicity is not guaranteed, when is_lock_free() == false.
|
Non-lock-free atomics aren't address-free, so shared memory between two processes would mean they don't respect each other's lock. (Same for two virtual mappings of a page holding the same atomic object in the same process, unless the hash table of locks is only indexed on the low bits of the address, the offset-within-page, but that would probably be a bad design.)
ISO C++ doesn't define memory-mapping functions or processes, so the standard itself doesn't go into much detail other than saying lock-free atomics should be address-free (which makes them work in shared memory). That is the case on real-world implementations.
Otherwise it's always atomic. The usual implementation mechanism is simple: use the address to index a table of spinlocks or mutexes.
Of course, this assumes a program free of undefined behaviour, but so does everything else in C++. Any UB anywhere during the execution of a C++ program means all guarantees of anything before or after that point are out the window.
In practice there aren't a lot of ways you could break atomicity of a non-lock-free std::atomic, other than really obvious stuff like using memcpy or a plain-uint64_t* to access the object representation, instead of going through the std::atomic<uint64_t> class.
Lock-free std::atomic is actually easier to break with UB, e.g. by dereferencing an atomic<T>* that's not aligned to alignof(std::atomic<T>). On many ISAs that support unaligned loads/stores, that will run but not actually be atomic, because the C++ implementation was relying on hardware guarantees for atomicity of aligned loads and stores.
|
74,609,303
| 74,634,992
|
How to deallocate Ada Record from CPP
|
I am attempting to free a heap allocated Ada tagged record from cpp. I have used the code AdacoreU as a starting place.
I receive the following error when running the code below.
20
double free or corruption (out)
raised PROGRAM_ERROR : unhandled signal
Am I overthinking things? Do I need an Ada based deallocation mechanism.
What is my real end goal? I would like to use dynamic libraries to create a plugin infrastructure where each library is its own factory for a given type. Something along the lines of boost dll but with ada based dynamic libraries.
Modified Code below:
main.cpp
1 #include <iostream>
2 #include "animal.h"
3
4 extern "C" {
5 void adainit (void);
6 void adafinal (void);
7 Animal* new_animal();
8 void del_animal(Animal *);
9 }
10
11 int main(void) {
12 adainit();
13 Animal* A = new_animal();
14 std::cout << A->age() << std::endl;
15 //delete A;
16 del_animal(A);
17 adafinal();
18 return 0;
19 };
alib.ads
1
2 with Interfaces.C;
3
4 package ALib is
5
6 type Animal is tagged record
7 The_Age : Interfaces.C.int;
8 end record;
9 pragma Convention (CPP, Animal);
10
11 type Animal_Class_Access is access Animal'Class;
12
13 function New_Animal return access Animal'Class;
14 pragma Export(CPP, New_Animal);
15
16 procedure Del_Animal (this : in out Animal_Class_Access);
17 pragma Export(CPP, Del_Animal);
18
19 function Age(X : Animal) return Interfaces.C.int;
20 pragma Export(CPP, Age);
21
22 end ALib;
alib.adb
1 with ada.unchecked_deallocation;
2
3 package body ALib is
4
5 function New_Animal
6 return access Animal'Class is
7 begin
8 return new Animal'(The_Age => 20);
9 end New_Animal;
10
11
12 procedure Del_Animal (this : in out Animal_Class_Access) is
13 procedure Free is new ada.unchecked_deallocation(Animal'Class, Animal_Class_Access);
14 begin
15 Free(this);
16 --null;
17 end Del_Animal;
18
19 function Age(X : Animal)
20 return Interfaces.C.int is
21 begin
22 return X.The_Age;
23 end Age;
24
25 end ALib;
~
other resources used as a starting point
3.11.3.5 Interfacing with C++ at the Class Level
What have I attempted:
Used various combinations of the type and access type when attempting to create the Free procedure
Animal, type Animal_Access is access Animal
Animal'Class, type Animal_Class_Access is access Animal'Class
Animal, type Animal_Access is access Animal'Class
I was at some point under the impression that I should be using system address for the pointers to the Animal object as either part of the return on New_Animal and as the argument to Del_Animal
What did I expect:
I expected to clean up Ada heap objects from Ada.
|
The problem is with the in out parameter to Del_Animal and its mapping to the C world.
Your intention with Del_Animal is that it should behave like Ada.Unchecked_Deallocation, in other words that the parameter is set to null (or 0!) after the call, but that means that what you have to pass is the address of the actual.
That is,
void del_animal(Animal**);
called as
del_animal(&A);
See ARM B3(68).
|
74,609,901
| 74,613,740
|
How create a big array in shared memory with boost::interprocess::managed_shard_memory in fast way?
|
I created an instance of "boost::interprocess::managed_shared_memory" and constructed an array of char with "2 * 1024 * 1024 * 1024" elements. Unfortunately it took time more than 50 seconds.
namespace bip = boost::interprocess;
auto id_ = "shmTest"s;
size_t size_ = 2*1024*1024*1024ul;
auto ashmObj_ = make_unique<bip::managed_shared_memory>(bip::create_only,
id_.c_str(),
size_ );
auto data_ = shmObj_->construct<char>("Data")[size_]('\0');
After that I got rid of it's initializing and decrease time to 30 second.
auto data_ = shmObj_->construct<char>("Data")[size_]();
Is there any way to get better time for this operation?
|
Sidenote: I don't think the size calculation expression is safe for the reason you seem to think (ul): https://cppinsights.io/s/c34003a4
The code as given should always fail with bad_alloc because you didn't account for the segment manager overhead:
A puzzle about boost::interprocess::managed_shared_memory->size
Shared memory size calculation c++
boost::interprocess::managed_mapped_file deque of strings runs out of space and others
Fixing it e.g. like this runs in 5s for me:
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bip = boost::interprocess;
int main() {
auto id_ = "shmTest";
size_t size_ = 2ul << 30;
bip::shared_memory_object::remove(id_);
bip::managed_shared_memory sm(bip::create_only, id_, size_ + 1024);
auto data_ = sm.construct<char>("Data")[size_]('\0');
}
Changing to
auto data_ = sm.construct<char>("Data")[size_]();
makes no significant difference:
If you want opaque char arrays, just could just use a mapped region directly:
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
namespace bip = boost::interprocess;
int main() {
auto id_ = "shmTest";
size_t size_ = 2ul << 30;
bip::shared_memory_object::remove(id_);
bip::shared_memory_object sm(bip::create_only, id_, bip::mode_t::read_write);
sm.truncate(size_);
bip::mapped_region mr(sm, bip::mode_t::read_write);
auto data_ = static_cast<char*>(mr.get_address());
}
Now it's significantly faster:
BONUS
If you insist you can do raw allocation from the segment:
auto data_ = sm.allocate_aligned(size_, 32);
Or, you can just use the segment as it intended, and let is manage your allocations:
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
namespace bip = boost::interprocess;
using Seg = bip::managed_shared_memory;
template <typename T> using Alloc = bip::allocator<T, Seg::segment_manager>;
template <typename T> using Vec = bip::vector<T, Alloc<T>>;
int main() {
auto id_ = "shmTest";
size_t size_ = 2ul << 30;
bip::shared_memory_object::remove(id_);
bip::managed_shared_memory sm(bip::create_only, id_, size_ + 1024);
Vec<char>& vec_ = *sm.find_or_construct<Vec<char>>("Data")(size_, sm.get_segment_manager());
auto data_ = vec_.data();
}
This takes a little more time:
But for that you get enormous flexibility. Just search some of my existing posts for examples using complicated data structures in managed shared memory: https://stackoverflow.com/search?tab=newest&q=user%3a85371%20scoped_allocator_adaptor
|
74,610,092
| 74,665,674
|
(Windows) fatal error: sqlite3.h: No such file or directory
|
I am trying to build a c++ application that uses sql.
For that I need sqlite3 header. I have already installed sql in my system and
sqlite3 in terminal gives:
SQLite version 3.36.0 2021-06-18 18:36:39 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite>
I have tried searching for this over web and found many relevant solutions including this.
Since I am working on Windows,
$ sudo apt-get install libsqlite3-dev
did not work.
I also tried to change
#include <sqlite3.h>
to
#include "sqlite3.h"
with sqlite.h file in the same directory as my cpp code file(as I found people using it in videos). But this time I ended up with
'''
C:\Users\username\AppData\Local\Temp\ccwQfHZB.o:temp.cpp:(.text+0x1e): undefined reference to `sqlite3_open'
collect2.exe: error: ld returned 1 exit status
'''
I am quite new to it, so any help is appreciated. Thanks.
|
I found the solution to this problem:
included two files(*): sqlite3.0, sqlite3.h in same folder as my main code.
added #include "sqlite3.h"
compiled using the command: g++ sqlite3.o main.cpp -o main
This finally resolved my error.
*(these were downloaded from sqlite.org)
|
74,611,249
| 74,611,654
|
std::promise::set_exception with type non extending std::exception calls terminate
|
In the following snippet
#include <iostream>
#include <future>
int main()
{
auto ep = std::make_exception_ptr( X ); // (1)
std::promise<int> p;
p.set_exception(ep);
try {
p.get_future().get(); // (2)
} catch(const std::exception& exc) {
std::cout << exc.what();
}
return 0;
}
if X in line (1) is a type not extending std::exception, the call at line (2) will call terminate. I can't find anywhere this specification.
Godbolt with latest gcc and msvc
|
As noted in comments, the problem is not catching the right type of exception, e.g. using catch(...).
|
74,611,284
| 74,612,057
|
if user enter 5 then display the last 5 elements of linked list vise versa
|
i am stuck in my uni assignment....
i have an linked list of 20 elements, i have to take the value from user and if user enter 5 then print the last 5 elements of linked list
void traverse(List list) {
Node *savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
for(int i = 1; list.next() == true; i++)
{
std::cout << "Element " << i << " " << list.get() << endl;
}
list.currentNode = savedCurrentNode;
}
im trying this but this method prints all the elements of my linked list
|
For what little code you have, a review:
// Why are you passing the list by value? That is wasteful.
void traverse(List list) {
// I don't see you taking a value anywhere; surely you know how to do that
// What is happening here? Can't you just assign the head to something
// directly?
Node *savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
// Like you said, this traverses the entire list, it's also poorly
// formed. You literally don't need i.
// for (; list.next(); /* However your list increments here */)
for(int i = 1; list.next() == true; i++)
{
std::cout << "Element " << i << " " << list.get() << endl;
}
// What is the purpose of this?
list.currentNode = savedCurrentNode;
}
For someone who is writing a linked list, this code seems to be fundamentally flawed. My expectation of someone tackling a linked list is that they are about to stop being a beginner, but I'm not seeing that here in the code and what structure of the list class is implied. The list class is weird to say the least.
And just to be clear, my expectation stems from where I place the linked list assignment in my curriculum. It's also more idiomatic than this list.
With that out of the way, this task is trivial if you took the time to think the project through. Most students skip the planning step and create unnecessary headaches for themselves.
Knowing that you would need the total size of the list, why not just make it member data? Any function that adds to the list will increment the value accordingly. And any function that subtracts from the list will decrement accordingly. That way you always know the size of the list at all times.
Knowing the size of the list is most of the battle. You then need to do the arithmetic necessary to advance in the list to satisfy your requirement. And now you can print.
#include <iostream>
class SList {
public:
SList() = default;
//
// Rule of 5 intentionally left out
//
void push_front(int val) {
m_head = new Node{val, m_head};
++m_size; // The magic happens here
}
std::size_t size() const { return m_size; }
void traverse_last(int numElements, std::ostream& sout = std::cout) const {
int placement = m_size;
Node* walker = m_head;
// Move our walker node the appropriate amount of steps
while (walker && placement > numElements) {
walker = walker->next;
--placement;
}
// Now that we're in position, we can print
while (walker) {
sout << walker->data << ' ';
walker = walker->next;
}
sout << '\n';
}
private:
struct Node {
int data;
Node* next = nullptr;
};
Node* m_head = nullptr;
std::size_t m_size = 0ULL;
};
int main() {
SList test;
for (int i = 5; i > 0; --i) {
test.push_front(i);
}
std::cout << "Size: " << test.size() << '\n';
for (int i = 1; i <= 5; ++i) {
test.traverse_last(i);
}
test.traverse_last(10);
}
Output:
❯ ./a.out
Size: 5
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
1 2 3 4 5
|
74,611,503
| 74,612,625
|
Why does QColor use 32-bit signed int to represent e.g. rgba values?
|
QColor can return rgba values of type int (32-bit signed integer). Why is that? The color values range from 0-255, don't they? Is there any situation where this might not be the case?
I'm considering to implicitly cast each of the rgba values returned by QColor.red()/green()/blue()/alpha() to quint8. It seems to work but I don't know if this will lead to problems in some cases. Any ideas?
|
I assume you are talking about QColor::rgba() which returns a QRgb.
QRgb is an alias to unsigned int. In these 32 bits all fours channels are encoded as #AARRGGBB, 8 bits each one (0-255, as you mentioned). So, a color like alpha=32, red=255, blue=127, green=0 would be 0x20FF7F00 (553615104 in decimal).
Now, regarding your question about casting to quint8, there should be no problem since each channel is guaranteed to be in the range 0..255 (reference). In general, Qt usually uses int as a general integer and do not pay too much attention to the width of the data type, unless in some specific situations (like when it is necessary for a given memory access, for example). So, do not worry about that.
Now, if these operations are done frequently in a high performance context, think about retrieving the 32 bits once using QColor::rgba and then extract the components from it. You can access the individual channels using bitwise operations, or through the convenience functions qAlpha, qRed, qBlue and qGreen.
For completeness, just to mention that the sibbling QColor::rgb method returns the same structure but the alpha channel is opaque (0xFF). You also have QColor::rgba64, which returns a QRgba64. It uses 16 bits per channel, for higher precision. You have the 64 bits equivalents to qAlpha, etc, as qAlpha64 and so on.
|
74,611,579
| 74,616,777
|
coredump when calling virtual method of a dynamic allocated object
|
The snippet below will coredumped in fun() method. Why calling c->b.f() works in main() but failed in the function call?
class A {
public:
inline virtual void f() const {printf("A\n");}
};
class B : public A {
public:
inline void f() const override {printf("B\n");}
};
class C {
public:
B b;
};
void fun(const B &b) {
b.f(); // coredump
}
int main() {
C *c = (C*)malloc(sizeof(C));
c->b.f(); // print "B"
fun(c->b);
return 0;
}
I guess it's because the virtual table is not initialized properly.
|
You are allocating memory for class C using malloc, but this doesn't create any object of class C. your program don't have any valid object and have undefined behavior.
As it is undefined behavior, your program may fail or may not be at c->b.f();
If you really want to use malloc, you should use placement new in your program to create object of your class.
C *c = (C*)malloc(sizeof(C));
new (c) C();
And to destroy your object and free the allocated memory, you should do
c->~C();
free(c);
|
74,612,412
| 74,612,490
|
g++ failing when trying to use GDAL library
|
I just want to compile this easy example of the GDAL library in my Ubuntu 22.04 system using the system-packed g++, version 11.3.0:
#include <iostream>
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "gdal.h"
using namespace std;
int main(int argc, char* argv[])
{
GDALDataset *poDataset;
GDALAllRegister();
poDataset = (GDALDataset *) GDALOpen(argv[1], GA_ReadOnly);
if (poDataset == NULL)
{
cout << "No dataset loaded for file " << argv[1] << ". Exiting." << endl;
return 1;
}
cout << "Driver: "
<< poDataset->GetDriver()->GetDescription()
<< "/"
<< poDataset->GetDriver()->GetMetadataItem(GDAL_DMD_LONGNAME)
<< endl;
cout << "Size: "
<< poDataset->GetRasterXSize() << "x"
<< poDataset->GetRasterYSize() << "x"
<< poDataset->GetRasterCount()
<< endl;
if (poDataset->GetProjectionRef() != NULL)
{
cout << "Projection: " << poDataset->GetProjectionRef() << endl;
}
}
Of course I installed the GDAL libraries, as it can be seen here:
~$ dpkg -l | grep gdal
ii gdal-bin 3.4.1+dfsg-1build4 amd64 Geospatial Data Abstraction Library - Utility programs
ii gdal-data 3.4.1+dfsg-1build4 all Geospatial Data Abstraction Library - Data files
ii libgdal-dev 3.4.1+dfsg-1build4 amd64 Geospatial Data Abstraction Library - Development files
ii libgdal30 3.4.1+dfsg-1build4 amd64 Geospatial Data Abstraction Library
ii python3-gdal 3.4.1+dfsg-1build4 amd64 Python 3 bindings to the Geospatial Data Abstraction Library
Everything seems to be settled and ready to go, but then, when I trigger this g++ command to compile my little program
g++ -I/usr/include/gdal -L/usr/lib -lgdal open_file.cpp -o open_file -g
it fails with this output:
/usr/bin/ld: /tmp/ccU6PwuP.o: in function `main':
/home/jose/Code/concepts/gdal/open_file.cpp:13: undefined reference to `GDALAllRegister'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:14: undefined reference to `GDALOpen'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:29: undefined reference to `GDALDataset::GetRasterXSize()'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:30: undefined reference to `GDALDataset::GetRasterYSize()'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:31: undefined reference to `GDALDataset::GetRasterCount()'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:34: undefined reference to `GDALDataset::GetProjectionRef() const'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:36: undefined reference to `GDALDataset::GetProjectionRef() const'
collect2: error: ld returned 1 exit status
Which doesn't make any sense, because I am indeed passing the GDAL libraries in -I/usr/include/gdal and the definition of the "undefined" references do exist in the multiple .h files there.
Moreover, this works using clang++:
clang++ -I/usr/include/gdal -L/usr/lib -lgdal open_file.cpp -o open_file -g
Did anyone have a similar issue, or can give some hint on where the problem might be? Thank you.
|
Include paths have nothing to do with the symbols.
-I/usr/include/gdal -L/usr/lib both are not necessary as they are set by default. But you should use #include <gdal/gdal.h>, not just <gdal.h> and certainly not "gdal.h".
Move -lgdal after all other cpp/object files.
In general, it should be g++ <OPTIONS> <OBJECTS> <LIBRARIES> where library A which uses symbols from lib B should appear after B i.e. -lB -lA, the order matters for ld. Because it will use the library to resolve just the currently missing symbols and then will promptly forget the library ever existed. So any newly found unresolved symbols will not be resolved, hence shifting the library arguments "right". One can resolve circular dependencies by repeating libraries more than once.
|
74,613,359
| 74,615,623
|
What is the correct way to get beginning of the day in UTC / GMT?
|
::tm tm{0, 0, 0, 29, 10, 2022 - 1900, 0, 0}; // 10 for November
auto time_t = ::mktime(&tm);
cout << "milliseconds = " << time_t * 1000 << endl;
Above code outputs 1669660200000, which is equivalent to 2022 November 29, 00:00:00. But it is in local timezone. How to get the UTC time for the aforementioned date?
A modern c++17 way with thread-safety will be appreciated.
|
There's a nit picky weak point in your solution (besides the thread safety issue): The members of tm are not guaranteed to be in the order you are assuming.
The tm structure shall contain at least the following members, in any order.
Using C++17 you can use this C++20 chrono preview library. It is free, open-source and header-only. Your program would look like:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace chrono;
using namespace date;
sys_time<milliseconds> tp = sys_days{2022_y/11/29};
cout << "milliseconds = " << tp.time_since_epoch().count() << '\n';
}
And the output would be:
milliseconds = 1669680000000
One of the nice advantages of using this library is that it will easily port to C++20. The C++20 version looks like:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace chrono;
sys_time<milliseconds> tp = sys_days{2022y/11/29};
cout << "milliseconds = " << tp.time_since_epoch() << '\n';
}
And outputs:
milliseconds = 1669680000000ms
Demo:
|
74,614,005
| 74,614,511
|
How to get class member variable that require lock without manual lock and unlock?
|
[EDIT]
Does anyone know how to get a class member container that require lock from outside properly?
Writing to a class member can be done as below if critical section is used for locking.
EnterCriticalSection(&m_cs);
// write
LeaveCriticalSection(&m_cs);
However, if it is necessary to lookup this container to find data from current data that the container holds. What I could think of was defining Lock, Unlock member function for a class containing the container. And calling them before and after Get.
void Lock(){ EnterCriticalSection(&m_cs); }
std::map<unsigned long long, CObject>& Get() { return m_mapObject; }
void Unlock(){ LeaveCriticalSection(&m_cs); }
This doesn't seem right as far as it is open to error.
What I'm looking for seems to be collaboration of these.
Class variables: public access read-only, but private access read/write
Return locked resource from class with automatic unlocking
Perhaps I'm having difficulty in finding relevant keyword to search.
Below is a small example code for detail.
#include <iostream>
#include <Windows.h>
#include <map>
class CObject
{
private:
int m_nData;
public:
CObject()
: m_nData(0)
{
}
~CObject()
{
}
void Set(const int _nData) { m_nData = _nData; }
int Get() { return m_nData; }
};
class CObjectManager
{
private:
CRITICAL_SECTION m_cs;
std::map<unsigned long long, CObject> m_mapObject;
public:
CObjectManager()
: m_cs{}
, m_mapObject{}
{
InitializeCriticalSection(&m_cs);
}
~CObjectManager()
{
DeleteCriticalSection(&m_cs);
}
bool Add(const unsigned long long _key, const CObject _object)
{
bool bReturn = false;
EnterCriticalSection(&m_cs);
if (m_mapObject.find(_key) == m_mapObject.end())
{
m_mapObject.insert(std::pair<unsigned long long, CObject>(_key, _object));
bReturn = true;
}
LeaveCriticalSection(&m_cs);
return bReturn;
}
bool Delete(const unsigned long long _key)
{
bool bReturn = false;
EnterCriticalSection(&m_cs);
std::map<unsigned long long, CObject>::iterator iter = m_mapObject.find(_key);
if (iter != m_mapObject.end())
{
m_mapObject.erase(iter);
bReturn = true;
}
LeaveCriticalSection(&m_cs);
return bReturn;
}
void Lock(){ EnterCriticalSection(&m_cs); }
std::map<unsigned long long, CObject>& Get() { return m_mapObject; }
void Unlock(){ LeaveCriticalSection(&m_cs); }
};
void DoSomething(CObject* _pObject)
{
int a = 10;
}
CObjectManager objectManager{};
DWORD Thread(LPVOID _pParam)
{
for (unsigned long long i = 0ull; i < 100000ull; ++i)
{
CObject object{};
object.Set(i);
objectManager.Add(i, object);
}
return 0;
}
int main()
{
CObject object0;
object0.Set(1);
CObject object1;
object1.Set(2);
bool b = objectManager.Add(3ull, object0);
bool b1 = objectManager.Add(3ull, object1);
bool b2 = objectManager.Add(4ull, object1);
bool b3 = objectManager.Delete(3ull);
CreateThread(nullptr, 0, &Thread, nullptr, 0, nullptr);
Sleep(0);
// Need to get current COject map of CObjectManager
CObject object2{};
std::map<unsigned long long, CObject>::iterator iter;
while (true)
{
objectManager.Lock();
std::map<unsigned long long, CObject> mapObject = objectManager.Get();
iter = mapObject.find(90000ull);
if (iter != mapObject.end())
{
object2.Set(iter->second.Get());
objectManager.Unlock();
break;
}
objectManager.Unlock();
}
DoSomething(&object2);
Sleep(2000);
return 0;
}
Any comment or answer will be appreciated.
|
If what concerns you is caller potentially missing lock/unlock calls, then a RAII pattern might be of help:
class CObjectManager
{
private:
CRITICAL_SECTION m_cs;
std::map<unsigned long long, CObject> m_mapObject;
public:
CObjectManager()
: m_cs{}
, m_mapObject{}
{
InitializeCriticalSection(&m_cs);
}
~CObjectManager()
{
DeleteCriticalSection(&m_cs);
}
auto LockAndGet()
{
EnterCriticalSection(&m_cs);
struct LockAndGetResult
{
private:
CRITICAL_SECTION& m_cs;
public:
std::map<unsigned long long, CObject> m_mapObject;
LockAndGetResult(CRITICAL_SECTION& cs, std::map<unsigned long long, CObject>& mapObject) : m_cs(cs), m_mapObject(mapObject) {}
~LockAndGetResult() { LeaveCriticalSection(&m_cs); }
};
return LockAndGetResult(m_cs, m_mapObject);
}
};
// usage:
CObjectManager co;
{
auto maplock = co.LockAndGet();
doSomethingWith(maplock.m_mapObject);
} // maplock dtor releases lock
|
74,614,564
| 74,614,831
|
Input Handler not working as intended C++
|
I am trying to make a program that reads from the keyboard a number corresponding to an index of an answer for a question and returns an error message if the type of date entered is wrong.
float Handlers ::InputHandler(string Question, unsigned short int Number_of_Answers)
{
float Answer;
cout << Question << endl << endl;
while (!(cin >> Answer) || Answer < 1 || Answer > Number_of_Answers || Answer - floor(Answer))
{
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
ErrorHandler(InputErrorNumber);
}
}
return Answer;
}
The program worked perfectly until I entered the value 1ddga (and other cases that respect the form 1 or 2 + string, 1 and 2 are the answers that the person can choose from). After I entered the respective value, the program continues with answer 1 and then if I try to ask for an answer using the same function, it returns the error message, after the question and then asks for my input. It is as if from 1ddga it read 1, and the rest was stored somewhere, and on the next reading, this save was checked and then it continued to ask for another input.
Is there any solution? For example, can I return to that while after it has read such a value, or at least stop the error message on the next reading?
|
It is as if from 1ddga it read 1, and the rest was stored somewhere
That's completely correct, if by 'stored somewhere' you mean that it remains in the console buffer waiting to be read next time around. This is how operator>> on an float is defined to work. It reads characters until it finds a character which cannot be part of a float, at that point it stops.
When you have precise input requirements then the only way to handle that is to do the error checking yourself. Read the input as a string, using getline for example. Then check if the input matches your expectations and then convert the string read into the value you want.
In your case, for example, you might read a string using getline, remove any leading or trailing whitespace, check if all the characters left are digits, and finally check that there is at least one digit. If all of that is true convert the string into an integer, otherwise do some kind of error handling.
|
74,614,615
| 74,625,693
|
How can I make single object larger than 2GB using new operator?
|
I'm trying to make a single object larger than 2GB using new operator.
But if the size of the object is larger than 0x7fffffff, The size of memory to be allocated become strange.
I think it is done by compiler because the assembly code itself use strange size of memory allocation.
I'm using Visual Stuio 2015 and configuration is Release, x64.
Is it bug of VS2015? otherwise, I want to know why the limitation exists.
The example code is as below with assembly code.
struct chunk1MB
{
char data[1024 * 1024];
};
class chunk1
{
chunk1MB data1[1024];
chunk1MB data2[1023];
char data[1024 * 1024 - 1];
};
class chunk2
{
chunk1MB data1[1024];
chunk1MB data2[1024];
};
auto* ptr1 = new chunk1;
00007FF668AF1044 mov ecx,7FFFFFFFh
00007FF668AF1049 call operator new (07FF668AF13E4h)
auto* ptr2 = new chunk2;
00007FF668AF104E mov rcx,0FFFFFFFF80000000h // must be 080000000h
00007FF668AF1055 mov rsi,rax
00007FF668AF1058 call operator new (07FF668AF13E4h)
|
Use a compiler like clang-cl that isn't broken, or that doesn't have intentional signed-32-bit implementation limits on max object size, whichever it is for MSVC. (Could this be affected by a largeaddressaware option?)
Current MSVC (19.33 on Godbolt) has the same bug, although it does seem to handle 2GiB static objects. But not 3GiB static objects; adding another 1GiB member leads to wrong code when accessing a byte more than 2GiB from the object's start (Godbolt -
mov BYTE PTR chunk2 static_chunk2-1073741825, 2 - note the negative offset.)
GCC targeting Linux makes correct code for the case of a 3GiB object, using mov r64, imm64 to get the absolute address into a register, since a RIP-relative addressing mode isn't usable. (In general you'd need gcc -mcmodel=medium to work correctly when some .data / .bss addresses are linked outside the low 2GiB and/or more than 2GiB away from code.)
MSVC seems to have internally truncated the size to signed 32-bit, and then sign-extended. Note the arg it passes to new: mov rcx, 0FFFFFFFF80000000h instead of mov ecx, 80000000h (which would set RCX = 0000000080000000h by implicit zero-extension when writing a 32-bit register.)
In a function that returns sizeof(chunk2); as a size_t, it works correctly, but interestingly prints the size as negative in the source. That might be innocent, e.g. after realizing that the value fits in a 32-bit zero-extended value, MSVC's asm printing code might just always print 32-bit integers as signed decimal, with unsigned hex in a comment.
It's clearly different from how it passes the arg to new; in that case it used 64-bit operand-size in the machine code, so the same 32-bit immediate gets sign-extended to 64-bit, to a huge value near SIZE_MAX, which is of course vastly larger than any possible max object size for x86-64. (The 48-bit virtual address spaces is 1/65536th of the 64-bit value-range of size_t).
unsigned __int64 sizeof_chunk2(void) PROC ; sizeof_chunk2, COMDAT
mov eax, -2147483648 ; 80000000H
ret 0
unsigned __int64 sizeof_chunk2(void) ENDP ; sizeof_chunk2
This looks like a compiler bug or intentional implementation limit; report it to Microsoft if it's not already known.
|
74,616,199
| 74,616,331
|
Why is my compiler "optimizing" this for loop into an infinite loop when compiled with -O3 in C++
|
I am trying to understand what optimization process causes the following code to produce an infinite loop when compiled with the -O3 optimization flag. To get it out of the way, I understand that the real root cause of the issue is the lack of a return in this non void function, I happened on this interesting behavior while part way through implementing this code on an embedded system and had not yet added the return as I was not using the return value at that point.
My question is more about the optimization process and how whatever it's doing could help in other cases/what the 'optimized' logic looks like.
For a little more context, I see this behavior when using both the c++ compiler in ubuntu (c++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0) as well as the aarch64-linux-gnu-g++ compiler shipped with Xilinx Vitis 2020.2 (and running on their respective platforms of course).
Minimum reproducible example (that I have so far created):
#include <iostream>
int broken_for_loop(){
for (int i = 0; i < 10000; i+= 1000){
std::cout << i << std::endl;
}
}
int main(int argc, char const *argv[]){
broken_for_loop();
}
When compiling with c++ ./broken_loop_test.cpp -o test_local -O3 or the ARM equiv. the output of the loop is infinite and I have run it until the 32b int wraps around. Without optimization, it works as I would expect. If I simply return 0 after the for loop, it also works with optimization.
My naive suspicion is that because there is no return outside the loop, the compiler expects that I will return from or break out from inside the loop, and therefor removes the check/branch that would test the loop condition, but I was wondering what I could look into to get more information on this specific topic (and optimization in general, it's been a while since my last course in compiler design) and I am not comfortable enough with ASM to confidently identify the issue there.
Any help would be appreciated, thank you!
Because this section is required, I will note that I have tried declaring volatile i as well as using different types of integer as well as casting the constant value and doing more/less in the loop. All lead to the same behavior without a return statement.
|
Undefined behaviour results in time travel.
Your code is a good example of it.
You have undefined behaviour after the loop (a function that must return a value doesn't). Since the compiler is allowed to assume that UB never happens, it assumes that the loop never terminates, and compiles it accordingy.
|
74,616,783
| 74,619,790
|
SWIG: Passing a list as a vector<double> pointer to a constructor
|
Trying to use swig to pass a python list as input for c++ class with a (one of many) constructor taking a std::vector<double> * as input. Changing the C++ implementation of the codebase is not possible.
<EDIT> : What I am looking for is a way to "automatically" process a python list to a vector<double> * or say for example:
fake_class.cpp
class FakeClass
{
public:
std::vector<double>* m_v;
FakeClass(std::vector<double>* v) : m_v {v} {}
void SomeFunction(); // A function doing some with said pointer (m_v)
[...]
};
and then using this in python (say the compiled extension is fakeExample:
import fakeExample as ex
a = ex.FakeClass([1.2, 3.1, 4.1])
print(a.m_v)
a.SomeFunction()
without crashing. </EDIT>
What I've tried:
Code:
example.hpp
#include <vector>
#include <iostream>
class SampleClass
{
public:
std::vector<double>* m_v;
SampleClass(std::vector<double>* v) : m_v {v} {
std::cout << "\nnon default constructor!\n";}
SampleClass() {std::cout << "default constructor!\n";}
void SampleMethod(std::vector<double>* arg);
void SampleMethod2(std::vector<double>* arg);
void print_member();
};
example.cpp
#include "example.hpp"
#include <iostream>
void SampleClass::SampleMethod(std::vector<double>* arg)
{
for (auto x : (*arg)) std::cout << x << " ";
};
void SampleClass::SampleMethod2(std::vector<double>* arg)
{
auto vr = arg;
for (size_t i = 0; i < (*vr).size(); i++)
{
(*vr)[i] += 1;
}
for (auto x : (*vr)) std::cout<< x << "\n";
}
void SampleClass::print_member() {
for (auto x : (*m_v)) {
std::cout << x << " ";
}
}
example.i
%module example
%{
#include "example.hpp"
%}
%include "typemaps.i"
%include "std_vector.i"
%template(doublevector) std::vector<double>;
/* NOTE: Is this required? */
%naturalvar Sampleclass;
/* NOTE: This mostly works but not for constructor */
%apply std::vector<double> *INPUT {std::vector<double>* };
%include "example.hpp"
A Makefile (s_test.py is a simple test script I am not including here).
all: clean build run
clean:
rm -rf *.o *_wrap.* *.so __pycache__/ *.gch example.py
build:
swig -python -c++ example.i
g++ -c -fPIC example.cpp example_wrap.cxx example.hpp -I/usr/include/python3.8
g++ -shared example.o example_wrap.o -o _example.so
run:
python s_test.py
build_cpp:
g++ example.cpp example.hpp main.cpp -o test_this.o
And finally after compiling etc :
>>> import example as ex
>>> a = ex.SampleClass()
default constructor!
>>> a.SampleMethod([1.2, 3.1, 4.1])
1.2 3.1 4.1
>>> a.SampleMethod2([3.1, 2.1])
4.1
3.1 # Works fine(or at least as expected) until here.
>>> b = ex.SampleClass([1.2])
non default constructor!
>>> b.m_v
<example.doublevector; proxy of <Swig Object of type 'std::vector< double > *' at SOME_ADDRESS> >
>>> b.m_v.size()
17958553321119670438
>>> b.print_member()
>>> [... Lots of zeroes here ...]0 0 0 0[1] <some_number> segmentation fault python
And exits.
Thank you :)
|
The Python list passed into the non-default constructor gets converted to a temporary SWIG proxy of a vector<double>* and that pointer is saved by the constructor into SampleClass's m_v member, but the pointer no longer exists when the constructor returns. If you create a persistent doublevector and make sure it stays in scope, the code works.
I built the original code in the question for the following example:
>>> import example as ex
>>> v = ex.doublevector([1,2,3,4])
>>> s = ex.SampleClass(v)
non default constructor!
>>> s.m_v.size()
4
>>> list(s.m_v)
[1.0, 2.0, 3.0, 4.0]
As long as v exists, s.m_v will be valid.
|
74,616,809
| 74,622,173
|
"imwrite" within CC Dynamic Android Library not found when beeing called from C-Code
|
I am using OpenCV 4.6.0 Android SDK which I downloaded from sourceforge and use it within my shared library/.so. This library is called from within my android app (aarch64). Building works fine using my android.toolchain.cmake :
...
set(CMAKE_C_COMPILER /home/username/Android/SDK/ndk/25.1.8937393/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-clang)
set(CMAKE_CXX_COMPILER /home/username/Android/SDK/ndk/25.1.8937393/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-clang++)
set(CMAKE_SYSTEM_NAME Android)
set(CMAKE_SYSTEM_VERSION 21)
set(CMAKE_ANDROID_ARCH_ABI arm64-v8a)
set(CMAKE_ANDROID_NDK /home/username/Android/Sdk/ndk/25.1.8937393)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
...
And CMakeLists.txt:
...
set(OpenCV_DIR ${CMAKE_CURRENT_LIST_DIR}/opencv-4.6.0-android-sdk/OpenCV-android-sdk/sdk/native/jni/abi-arm64-v8a)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR}/opencv-4.6.0-android-sdk/OpenCV-android-sdk/sdk/native/jni/include)
find_package(OpenCV REQUIRED)
...
target_link_libraries(${PROJECT_NAME} PRIVATE opencv_highgui)
...
My .h
#ifdef __cplusplus
extern "C"
{
#endif
bool imwriteC(Bitmap *bitmap, const char *filename);
#ifdef __cplusplus
}
#endif
And .cpp
#include <opencv2/opencv.hpp>
#include "myheader.h"
...
bool imwriteWrapper(Bitmap *bitmap, const char *filename)
{
Mat mat;
// ...
// bitmap to mat conversion here
// ...
return imwrite(filename, mat);
}
bool imwriteC(Bitmap *bitmap, const char *filename) {
return imwriteWrapper(bitmap, filename);
}
I call my imwriteC from C-Code.
My error message looks like name-mangling
Unable to load library 'testlibrary':
"_ZN2cv7imwriteERKNSt6_ndk112basic_stringlcNS0_11char_traitslcEENS0_9allocatorlcEEEERKNS_11_InputArrayERKNS0_6vectorliNS4_liEEEE" referenced by ... "/path/to/testlibrary.so"...
So it seems like OpenCVs imwrite can't be found due to name mangling issues(?).
|
It's not about mangling, you just didn't link with all the OpenCV libraries that you need.
You're using OpenCV version 4.6.0. I see that you're calling imwrite, and you're linking with the highgui module. Well, once upon a time (in 2.4.x) that would have worked, but IIRC since 3.x (and definitely in 4.x) this function resides in imgcodecs module. So you should change that target_link_libraries statement to something like
target_link_libraries(${PROJECT_NAME} PRIVATE opencv_imgcodecs)
Furthermore, since you're using a Mat there, you might need the core module. Often you can figure out the name of the module from the documentation (best look at the URL -- for imwrite there's group__imgcodecs.html in the middle, and the module name is after the two underscores).
Of course, as you found out, since you find_package(OpenCV REQUIRED), you can also take the shortcut and link with ${OpenCV_LIBS}, which ends up trying all the OpenCV modules. I guess that's good enough choice, although personally I prefer to explicitly specify exactly what I need and no more.
|
74,617,047
| 74,617,113
|
How to use the type mentioned in input for creating an object?
|
Say I have a templatized class
template<class T>
class MyClass
{
...
}
Now let's say for the sake of simplicity, that the input explicitly mentions that the following data shall be of what type:
for example
int
1 2 3 4 5
or
float
1.5 2.3 4.2 5.9
Now I want to create an object based on the type mentioned in the input
Something like
MyClass<type_mentioned_in_input> obj;
How do I achieve this?
Based on my lesser understanding of C++, here is what I tried:
Create an abstract base class for the MyClass
Mention all the member functions of MyClass as pure virtual functions in the abstract base class
Dynamically initialize an object of the base class at runtime
Clearly this method not only increases the complexity, but also fails with templates.
What should be the desired what to execute this?
|
You can't:
template are compiler time, the specific content between < .. > is replaced when you build, and that can not be modified runtime based on the input.
The solution to your problem (about having different types defined runtime) is to use an other mechanism, like std::variant.
|
74,617,148
| 74,621,289
|
How do I register my Clang Static Analyzer checker
|
I am fully aware that this question has previous answers. However, those answers are old and don't reflect what is happening in the current code base.
I have followed the steps in this guide for developing the checker, registering it with the engine, and testing it.
After some work, I was able to compile the code but when running clang -cc1 -analyzer-checker-help my checker is not visible. I Have noticed that a lot of the checkers aren't visible.
Do I need to explicitly enable the checker on the command line? If not what have I missed?
When I run clang --analyze test.cpp of clang -cc1 -analyze test.cpp my checker does not raise a warning. But others do, even those "not visible" in the clang -cc1 -analyzer-checker-help command.
Please do not point me into the direction of 6 year old documentation that is outdated. I want to know how to get this done.
My code:
MainCallChecker.cpp
using namespace clang;
using namespace ento;
namespace {
class MainCallChecker : public Checker<check::PreCall> {
mutable std::unique_ptr<BugType> BT;
public:
void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
};
}
void MainCallChecker::checkPreCall(const CallEvent &Call,
CheckerContext &C) const {
if(const IdentifierInfo *II = Call.getCalleeIdentifier()) {
if(II ->isStr("main")) {
if(!BT) {
BT.reset(new BugType(this, "Call to main", "Example checker"));
ExplodedNode *N = C.generateErrorNode();
auto R = std::make_unique<PathSensitiveBugReport>(*BT, BT->getCheckerName(), N);
C.emitReport(std::move(R));
}
}
}
}
void ento::registerMainCallChecker(CheckerManager &mgr){
mgr.registerChecker<MainCallChecker>();
}
Checkers.td
def MainCallChecker : Checker<"MainCall">,
HelpText<"MyChecker">,
Documentation<NotDocumented>;
CMakeLists.txt
add_clang_library(clangStaticAnalyzerCheckers
.
.
MainCallChecker.cpp
.
.
)
test.cpp
typedef int (*main_t)(int, char **);
int main(int argc, char** argv) {
main_t foo = main;
int exit_code = foo(argc, argv);
return exit_code;
}
|
UPDATE: A Clang contributor provided me a helpful answer that fixed my problem. via the llvm discorse
|
74,618,586
| 74,625,453
|
Can you mock C functions with Googlemock without creating a global mock instance?
|
The generally used approach of wrapping free C functions in a "Mockinterface" class with a child class "Mock"(that calls MOCK_METHOD) results in the need of a global mock variable in order to use it in a TEST.
Is there another design approach that does not need a global Mock object/pointer so we could use a local Mock object in TEST?
|
It doesn't matter whether the mock object is globally static, locally static, or locally dynamic. You just need to make sure that it exists when the mocked C function is called and wants to call the method of the mock object.
The important part is that the per-se static C functions need to access that mock object. In consequence you need some kind of static variable. It does not need to be the mock object.
I realized this with a class variable (in contrast to a member variable) that stores a pointer to the single mock object. If you are sure that at most one mock object exists at a time, you can even save some effort because of possibly multiple instantiations.
For example:
class FunctionsMock
{
public:
static FunctionsMock* instance;
FunctionsMock()
{
instance = this;
}
~FunctionsMock()
{
instance = nullptr;
}
MOCK_METHOD(int, function1, (int p));
MOCK_METHOD(void, function2, ());
};
An implementation can look like:
FunctionsMock* FunctionsMock::instance = nullptr;
extern "C" int function1(int p)
{
if (FunctionsMock::instance == nullptr)
{
ADD_FAILURE() << "FunctionsMock::instance == nullptr";
return 0; // some sensible value
}
return FunctionsMock::instance->function1(p);
}
extern "C" void function2()
{
ASSERT_NE(FunctionsMock::instance, nullptr);
FunctionsMock::instance->function2();
}
Note: Since you cannot use ASSERT_NE in a function that returns a value, you need to check the condition explicitly and in case call ADD_FAILURE.
Now you can define a local mock object and check that expected functions are called:
TEST(SuiteName, TestName)
{
FunctionsMock mock;
EXPECT_CALL(mock, function1(...
EXPECT_CALL(mock, function2())...
// ...
}
If you want multiple concurrent mock objects, the C functions needs to know which mock object has to be used. I did not dive into this since we did not need it. All our tests run sequentially. You might want to do some research, depending on the kind of multitasking you do.
If you just want to use the latest instance, you can provide a static stack of mock object pointers instead of the single pointer.
|
74,618,642
| 74,619,396
|
Can runtime and constexpr nan comparisons disagree?
|
I was writing a constexpr bool isfinite(Float) function because I'm not on C++23 yet and so my std::isfinite isn't constexpr. But CI said MSVC didn't like something.
In general, nan should compare false with anything with all comparisons other than != which should always be true: https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN
After some digging, here's the simplest form of the problem:
#include <cassert>
#include <limits>
// Stating assumptions:
static_assert(std::numeric_limits<float>::is_iec559);
static_assert(std::numeric_limits<float>::has_quiet_NaN);
static_assert(std::numeric_limits<float>::has_infinity);
static_assert(std::is_same_v<decltype(NAN), decltype(INFINITY)>);
static_assert(std::is_same_v<float, decltype(INFINITY)>);
int main() {
static_assert(INFINITY == std::numeric_limits<float>::infinity()); // Obviously!
assert(INFINITY == std::numeric_limits<float>::infinity()); // Obviously.
assert(not (NAN < std::numeric_limits<float>::infinity())); // Nan always compares false, so good.
assert(NAN < INFINITY); // What?! This shouldn't pass!
static_assert(NAN < INFINITY); // Neither should this!
static_assert(NAN < std::numeric_limits<float>::infinity()); // Neither should this!
}
https://godbolt.org/z/dsqhcz18E
What the heck is going on? Am I into implementation-defined behavior?
With clang I get the errors I'd expect: https://godbolt.org/z/cvKv8ssax and same with gcc: https://godbolt.org/z/Moen3x1ov
|
Am I into implementation-defined behavior?
From C++ perspective: Yes, sort of. The non-finite floating point comparisons are not defined by the C++ standard. That said, static_assert(std::numeric_limits<float>::is_iec559) brings in another standard into consideration.
From IEC 559 aka IEEE-754 perspective: No, the comparisons are defined by this standard, so they aren't implementation defined.
What the heck is going on?
Looks like a bug in the language implementation.
|
74,618,780
| 74,618,825
|
how to create specialization of method inherited from class template instantiation
|
I have a base class template and a class deriving from an instantiation of it:
template<typename T>
class Bar
{
template <T t>
void Foo();
};
class Derived : public Bar<int> {};
How should one implement Derived::Foo<0>() for example?
when trying this out:
template<>
void Derived::Foo<0>() { /* impl.. */}
i get the following compile error:
template-id 'Foo<0>' for 'Derived::Foo()' does not match any template declaration.
|
You cannot specialize it in the descendant; you can only add a signature that'll serve as an overload and delegate as necessary:
template<typename T>
class Bar
{
template <T t>
void Foo();
};
class Derived : public Bar<int> {
using Base = Bar<int>;
template <int t>
void Foo()
{
if constexpr(t == 0) {
/* impl... */
} else {
Base::Foo<t>();
}
}
};
Since the ADL / Koenig lookup of a class does not include template base class(es), I'd not expect any issues during overload resolution if you do it this way.
|
74,618,938
| 74,619,026
|
inspecting 2D array inner type
|
I am trying to check if the type of an array element is a specific type. See the following.
#include <type_traits>
#include <cstdint>
#include <iostream>
int main() {
using arr = std::int32_t[2][2];
std::cout << std::is_same_v<decltype(std::declval<arr>()[0][0]), std::int32_t> << std::endl;
}
>>> 0
Why is the above code printing zero? I also tried getting some other data about the type. See the following.
#include <type_traits>
#include <cstdint>
#include <iostream>
#include <typeinfo>
int main() {
using arr = std::int32_t[2][2];
std::cout << typeid(decltype(std::declval<arr>()[0][0])).name() << std::endl;
std::cout << sizeof(decltype(std::declval<arr>()[0][0])) << std::endl;
}
>>> i
>>> 4
As can be seen above, the type is an integer and 4 bytes, just like an std::int32_t. What am I doing incorrectly? Am I misinterpreting the typeid output? Thanks.
I'm using g++ 12.1.0 compiling for c++ 17.
|
The type of the expression is lvalue reference to std::int32_t. You can use remove_reference to get the expected std::int32_t:
#include <type_traits>
#include <cstdint>
#include <iostream>
int main() {
using arr = std::int32_t[2][2];
std::cout << std::is_same_v<decltype(std::declval<arr>()[0][0]), std::int32_t&&> << std::endl;
std::cout << std::is_same_v<std::remove_reference_t<decltype(std::declval<arr>()[0][0])>, std::int32_t> << std::endl;
}
Live
Concerning your usage of typeid, first note that the name is implementation defined, it could be anything, you shouldnt assume that the name for int32_t is i (it is, but nevertheless ;).
Then (from cppreference on the typeid operator):
(1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the referenced type.
You are comparing two somewhat unrelated tools. typeid is to infer the type of an polymorphic object. For that usually reference or not does not matter, you just care about the dynamic type of the object. decltype on the other hand is to deduce the type of an expression where references do matter.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.