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 |
|---|---|---|---|---|
66,315,736 | 66,315,796 | Definition of pure virtual method while using templated class with sfinae | I'm trying to learn and use sfinae, this is my first attemt to do so. I have following code:
template<class CoreType, typename std::enable_if_t<std::is_base_of_v<Core, CoreType>>* = nullptr>
class Window
{
protected:
std::shared_ptr<Engine<CoreType>> _engine;
public:
virtual ~Window() = 0;
};
template<class Co... | You're telling the compiler that the ~Window () function is part of the Window<CoreType> class. However, there is no such class. The class you defined takes two template parameters (the fact that one is used for SFINAE doesn't matter).
You're also using typename std::enable_if_t<...>, but the _t suffix indicates that t... |
66,316,128 | 66,318,543 | Why can't I return a reference to a unique_ptr of a derived class created with a template? | I have a compile time "plugin" system based on this link, which I want to retain ownership of the plugins, which are literally unique - there should only be one instance of each type.
There is a registrar class which owns a plugin type, and owns a unique_ptr to the plugin.
I want to return a reference to the plugin wh... | auto plugin= factory.GetPlugin("TestPlugin");
This will copy the result into a new object, which will be a IPlugin (the original derived type will be sliced). You want to use a reference instead:
auto& plugin= factory.GetPlugin("TestPlugin");
You might want to make IPlugin::DoThing() a pure virtual function (i.e. vir... |
66,316,244 | 66,318,381 | SIGPIPE handling by sigwait | I am trying to implement a graceful shutdown of a process when its output is being piped to another process. I am testing the code bellow by piping its output: ./a.out | less and pressing q when a prompt appears. Instead of expected completion of sigwait() I see invocation of signal handler instead (it is added here ju... | You'll need to contrive some other way of noticing that the write failed, for example, ignoring SIGPIPE but setting std::cout.exceptions(ios::badbit), or handling the signal within your writing thread.
Importantly, that SIGPIPE will always be generated for your writing thread, your sigwait()ing thread notwithstanding. ... |
66,316,385 | 66,316,415 | singleton and new operator - thread safety | I know that a Scott Meyers Singleton is thread-safe for C++11 and above. Is the following code also thread-safe (for C++11 and above)?
class T
{
static T* obj;
public:
T& GetInstance()
{
if (!obj)
{
obj = new T();
}
return *obj;
}
};
T* T::obj=nullptr;
| No, this code is not thread safe. Two or more different threads could all call GetInstance at the same time and since obj has no synchronization (mutex, atomic variable) guarding it, then you have a data race. Having a data race means your code has undefined behavior which is not safe.
|
66,317,054 | 66,317,342 | Uniform_real_distribution between 0.0 and 1.0 generates extremely low numbers in C++ always close to 0 | Inside a class, I am trying to implement a method that generates a random number which would end up being a property of the class. I am calling the method randomPropertyGenerator inside the object constructor.
My minimum code for reproducing the issue looks like this
#include <iostream>
#include <stdlib.h>
#include <st... | In the constructor:
Object() {
double randomProp = randomPropGen(0.0, 1.0);
}
You declare and initialize a local variable called randomProp. This local variable only exists inside the constructor. There is a member of same name, but those are two distinct objects, hence the member is uninitialzed. Members can be i... |
66,317,946 | 66,323,843 | Call c++ function in Widget blueprint | I create widget, inherited from C++ class below.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Widget_Manager.generated.h"
UCLASS()
class CRY_API UWidget_Manager : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, Category ="test")
int32 x;
... | Please make sure that your not using Hot Reload (the Compile C++ button in the Editor).
If you make changes to your C++ code, especially Headers, always close the Editor and recompile it from Visual Studio. Hot Reload cannot resolve changes to Header files, which means things like Functions and new Properties will not ... |
66,318,178 | 66,318,459 | How do I create BMP files using c++? | I'm trying to create a class that saves BMP image given the pixels.
This is my .h:
#ifndef _IMAGE_SAVER_
#define _IMAGE_SAVER_
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <bitset>
//#define _DEBUG_
#ifdef _DEBUG_
#include <iostream>
#endif
#include <stdint.h>
typedef struct B... | Certainly you miss #pragma pack. Wrap your structures with #pragma pack(push,1)/#pragma pack(pop)
When structures represent memory layout and should have no padding, even if having unaligned data, pack structures.
It is very helpful to have static_assert on expected sizeof value for such cases.
Additionally, when you p... |
66,318,815 | 66,319,990 | c++ to delphi convert | Now I'm trying to get the picture from my Dahua Terminal, and the code becomes a little trick.
In C++ sample code, I have:
//Struct
// face info
typedef struct tagNET_ACCESS_FACE_INFO
{
char szUserID[32]; // user ID
int nFaceD... |
But in the sample code, ...pfacePhoto[i] = new char[100*1024] in my limited knowledge of C++ means the PAnsiChar receiving a Delphi array [0..(100*1024)-1] of AnsiChar.
Since pFacePhoto[i] is a PAnsiChar, can I create a new array of AnsiChar and point to it?
Yes, that is exactly what you need to do. You need to allo... |
66,319,330 | 66,319,797 | Passing const char * to function | I'm trying to embedd python interpreter in C++ app using Python/C API. In my code exist something like that:
string code("python code here");
PyRun_SimpleString( code.c_str() );
Python/C API function expect const char * argument. This code is executed in loop and my app sometimes crashes on PyRun_SimpleString command.... |
Is my way of passing an argument incorrect or it is good and I should try to find memory management error in the rest of my code?
Your way of passing a raw C string is correct.
Crash inside malloc often indicates that the program has somehow damaged internal heap structures. See if the program did anything bad (like ... |
66,319,485 | 66,322,623 | C2995: template already defined | I have read this question and its answer and still don't understand why I am encountering this issue.
This code compiles in VS2017:
#include <iostream>
#include <string>
template <class T>
struct A
{
template<class U>
friend std::enable_if_t<!std::is_void<U>::value, A<void>> operator&&(A<U> a1, A<void> a2)
#if... | There is actually a rule in the standard that says this is an error, from [temp.inst.3]:
However, for the purpose of determining whether an instantiated redeclaration is valid according to [basic.def.odr] and [class.mem], a declaration that corresponds to a definition in the template is considered to be a definition.
... |
66,319,728 | 66,321,531 | How do I insert a timestamp in a prepared statement via postgres? | I'm sending records to a table in QuestDB and so far I have the following:
#include <libpq-fe.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
void do_exit(PGconn* conn)
{
PQfinish(conn);
exit(1);
}
int main()
{
PGconn* conn = PQconnectdb(
"host=localhost user=adm... | You are doing it right.
Parameters to a prepared statement can either be sent in text format, like you are doing, or in binary format. For binary format you would have to set
int binary[1] = { 1 };
and convert the timestamp to the internal PostgreSQL format. In the case of timestamp or timestamp with time zone, that i... |
66,319,757 | 66,320,171 | How to handle forward referencing when Label size is not fixed | I am trying to write 8086 Emulator in C++.
But I am facing a problem.
Suppose the code is:
MOV AL, BL
JMP X
MOV BL, CL
MOV DL, CL
.
.
.
X:
ADD AX, BX
HLT
Now the machine code for JMP X will depend on X, whether it is near location or short location
near: 8Bit Address[00-ff]
short: 16Bit Address(ff-ffff]
So if the siz... | You may have even more problems for jmp. See the following possible opcodes and their meaning:
EB cb JMP rel8 Jump short, relative, displacement relative to next instruction.
E9 cw JMP rel16 Jump near, relative, displacement relative to next instruction.
E9 cd JMP rel32 Jump near, relative, dis... |
66,319,820 | 66,319,866 | Why *this=door is correct? | Door::Door(const Door& door)
{
*this = door;
}
I am very confused with this copy constructor. For me, it does not make sense to use *this=door, but rather
Door::Door(const Door& door)
{
this->color = door.color;
this->destination = door.destination;
}
Can you explain why *this=door is correct?
EDIT
As it ... | It invokes Door::operator=(Door const &other).
If that operator is explicitly implemented, it does whatever the implementation says it does. If it's implicitly generated, it simply copies the values of all members.
|
66,320,019 | 66,324,844 | Move semantics appear to add additional overhead in the simplest possible* example | * I believe this is the simplest possible example, but if I'm incorrect please let me know.
https://godbolt.org/z/neaTse
I'm attempting to learn and understand move semantics and some of their intricacies, but I've hit a bit of a snag. When attempting to compare the following 2 code snippets, the code using move semant... | OK, the problem is inlining and effective optimization, to get around it I've annotated it with __attribute__((noinline)).
I've made a class to handle the move
class mover {
public :
int *ptr { nullptr };
__attribute__((noinline)) mover() : ptr(new int(42)) { }
__attribute__((noinline)) mover(mover & other) {
... |
66,320,281 | 66,322,724 | Why am I getting an error with MSVC when using a C++17 parallel execution algorithm on Boost zip iterators? | I have some trouble using C++17 parallel execution algorithm with Boost iterators on MSVC. Here is my code:
#include <vector>
#include <execution>
#include <boost/range/combine.hpp>
int main(void)
{
std::vector<double> const v1(20, 1);
std::vector<double> const v2(20, 2);
std::vector<double> v_out;
v_out.resiz... | zip iterators can only be input in the C++17 iterator hierarchy because their reference types are not real references.
It is undefined behavior to passing an input iterator to a parallel algorithm. MSVC's implementation happens to check the precondition more aggressively than GCC's.
|
66,320,684 | 66,321,776 | How do I design this algorithm? | In an imaginary land the people have an ability to teleport through each other if they are facing each other. I am supposed to write an algorithm to find how many teleportations will be made based on the input. If there is a 1 that means the person is facing right and if there is a 2 that means the person is facing lef... | You do check the people right behind the first person but after you checked everyone once, you stop. You need a second loop that keeps checking for teleports until no further teleports are found. Something like this:
#include <iostream>
using namespace std;
int main() {
int n, a, teleportiranja = 0;
cin >> n;... |
66,320,704 | 66,489,004 | How to disconnect a signal | I made a program to calculate the area and volume of shapes from a window. Everything works, except one thing regarding the use of Gtk::Entry::signal_activate(). In the following code:
sigc::connection c = elongueur.signal_activate().connect([this]() { calcul(); });
switch (forme)
{
case 1: //carré
cacheEnt... | First add this header. See documentation from sigc++
#include <sigc++/connection.h>
We have to disconnect signal and stop it
Declare in your own class
sigc::connection c;
then in your main programm we can do something like that
switch (forme)
{
case 1: // carré
cacheEntry();
labelForme.set_label(listeDe... |
66,320,956 | 66,325,809 | GTKmm header files seem to be missing when I try to compile my program | I am trying to compile a GTKmm C++ program using g++ (clang), however I can't seem to find the header files that I need. I have run the installation .sh file for GTK+, and I have also tried directly installing GTKmm via Homebrew, but I am still getting this error:
fatal error: 'gtkmm/button.h' file not found
I thought... | Ok, I have figured it out.
I needed to install both GTK+ and GTKmm via Homebrew. This put the library into /usr/local/include. Note that the question code still won't work, because it is using the wrong directory (I installed gtk+3 and gtkmm3). Refer to this answer for more information.
|
66,321,032 | 66,323,007 | Is there a C++ API Linux System call that tells you which shared libraries your executable has linked? | I am wondering if anyone knows a C++ system call that produces output similar to the ldd command. I am trying to get a list of all the shared libraries that the executable I am running has linked (just like ldd, but a C++ API). My end goal is to get the absolute paths of all the shared libraries my program has linked ... | You can use dl_iterate_phdr:
#define _GNU_SOURCE
#include <link.h>
#include <stdlib.h>
#include <stdio.h>
static int callback(struct dl_phdr_info *info, size_t size, void *data) {
printf("name=%s (%d segments)\n", info->dlpi_name, info->dlpi_phnum);
return 0;
}
int main() {
dl_iterate_phdr(callback, NULL);
re... |
66,321,253 | 66,321,590 | Reference at std::thread parameters | I have two functions
void f(const int &x) {}
void g(int& x) {}
I can make
int x = 0;
std::thread t1(f, x);
But I can't create std::thread t2(g, x), in this case i need make std::ref(x) instead of just x, why is it necessary?
And why it possible to create t1 without std::cref?
| Your f() function does not work as you expect without std::cref().
Although f() does not intent to change the value behind x, it does not mean that the value behind this reference cannot be mutated elsewhere.
In this example, without std::cref() a copy of the original int is put in the thread stack, and x references th... |
66,321,311 | 66,325,758 | How to get char from first bits per byte in uint? | I have uint64_t variable with some value (for example 0x700a06fffff48517). I want to get char with the first bit of each byte in the uint (so from 0x700a06fffff48517 I want 0b00011110). Is there a better way than this?
#include <inttypes>
char getFirstBits(uint64_t x) {
x >>= 7; // shift to put first bits to last b... | This is a generic solution that doesn't depend on any CPU architectures
char getFirstBits(uint64_t x) {
x = (ntohll(x) >> 7) & 0x0101010101010101; // get the first bits
return 0x8040201008040201*x >> 56; // move them together
}
This is basically the multiplication technique where bits are moved aroun... |
66,321,414 | 66,321,573 | What is the prototype for a function that takes in reference to a vector | say we have this function void sorter(vector<int> &nums). is its prototype void sorter(&vector<int>) or void sorter(vector<int> &)
| Just like how you take reference to an int.
void sorter(int &a); or
void sorter(int &);
you take a reference to a vector.
void sorter(vector<int> &b); or
void sorter(vector<int> &);
|
66,322,525 | 66,343,383 | Conversion from class to identical class with different template types | I have the simple class "vec2". I would like this class to be able to store doubles and double references in the class template, or even int and int references. Here is the desired behavior-
vec2<double> base(5, 5); //normal vec2
vec2<double&> reference(base.x, base.y); //vec2 reference to vec2 "base"
vec2<double> th... | I did a bit more research, and managed to learn a lot on template specialization. Here is the functioning vec2 class which implements everything I wanted, plus a "perpindiculate" function and a "swap" function-
template <class T> class vec2{
public:
vec2(){
x = 0;
y = 0;
}
vec2(T X, T Y){
... |
66,322,553 | 66,322,625 | How to create an unordered_map with a range of numbers as keys | C++ | int n;
unordered_map<int,int> map(1,n);
This gives me error. I want to initialize the map with keys ranging from 1 to n. How can I do that?
|
I want to initialize the map with keys ranging from 1 to 5
This would make the keys [1, 5] map to the value 0:
std::unordered_map<int,int> map{
{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}
};
If you need many keys, initializing the map with all of them may be too cumbersome and it that case you'll have to use some sor... |
66,322,763 | 66,325,500 | Recording WSASend Buffers and sending them | I'm trying to make cheat for an unpopular game. Every time the game calls the WSASend function, there is 1 buffer of some length in the lpBuffers variable. I need to make it so that while holding down my side mouse button, buffers are written to some kind of array. Then, when the button is released, check if there is s... | I see multiple issues with your code.
When the mouse button IS DOWN, you are completely ignoring the dwBufferCount parameter of WSASend() when adding the caller's new data to your list. If the caller tries to send multiple WSABUFs at a time, you will lose data.
You are not saving lpBuffers->len into your list at all... |
66,322,822 | 66,322,896 | how to write an object that contains a list to a file c++? | I'm having a problem with reading and writing a file in c++. My issue revolves around trying to save an object that has an attribute vector. While debugging, The object appears to be stored correctly but on reading it back, the vector values are 0 but the size of the vector is correct. After doing some research I'm awa... | In this simple case you don't need boost. The problem is that you are writing the object (which is meaningless) when you should be writing the floats. You will also need to write the number of floats, so that when you read back you know how many to read. Something like this for writing
// how many floats
size_t number_... |
66,322,835 | 66,324,895 | How does one declare and use vertex attributes that are an array of primitive elements in OpenGL | In a shader I want to pass an array of primitives into it as a vertex attribute.
In the shader I declare
in float FloatItems[8]
in int IntItems[8]
IN the C++ code uses:
void glGetActiveAttrib( GLuint program,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLint *size,
GLenum *type,
GLchar ... | This:
in float FloatItems[8]
Means the shader takes eight separate attributes, which the shader can access as an array of values. That's 8 attributes with 8 distinct attribute locations. The location of these attributes will be allocated contiguously, starting from the location for FloatItems[0].
Obviously, consumin... |
66,323,184 | 68,505,780 | Overriding C++ entry point to be a STATIC method of a class | Preface and the problem
I'm currently studying C++ programming language and game programming.
At the moment, I'm working on a simple game engine just to practice 'consistency' and architecture of the API, and due to this reason the idea of mimicing C# 'Program' class appeared.
C# Entry point:
class Program
{
static... |
Is it possible to somehow, using linker options, redefine entry point to be a static class method?
No. Not if you want to use the C++ runtime library, at any rate. main (or WinMain) is called by the runtime library once it has completed initialising itself, and that call is hard-coded in the runtime library itself.... |
66,323,429 | 66,323,663 | Do we need to clear a class member of type vector in beginning of the constructor function of the class? | I am trying to understand the class definition of a class in this pdf: http://finance.bi.no/~bernt/gcc_prog/recipes/recipes.pdf (Page 61-62). The part of the code where I have the question is below. The following is the header file:
#ifndef _TERM_STRUCTURE_CLASS_INTERPOLATED_
#define _TERM_STRUCTURE_CLASS_INTERPOLATED... |
The clear operation is not necessary. By the time you reach the body of the constructor, the vector objects have been default constructed. A default constructed vector is empty.
That is calling the default base class constructor. If no base class constructor call is present, the default is invoked automatically. An e... |
66,323,859 | 66,323,879 | What makes this deconstruct never be called | I am trying to understand the memory leak.
I don't understand why below MyInt deconstruct in main is never called and a memory leak happens.
class MyInt
{
int *_p;
public:
MyInt(int *p = NULL) { _p = p; }
~MyInt()
{
delete _p;
}
int &operator*() ... |
I don't understand why below MyInt deconstruct in main is never called and a memory leak happens.
Because you use an allocated pointer to MyInt.
You have to call
delete en;
to de-allocate it.
Deleting en, the destructor of MyInt is called and the memory associated to _p is de-allocated.
Suggestion: you tagged C++11,... |
66,324,297 | 66,324,826 | How add node before doubly linked list c++ | I am making a code for double linked list in C++. But, i have a problem, I dont know how add node before other node.
I have these.
template<class T>
void LinkedListD<T>::addNodeBeforeTo(Node<T> *before, T info) {
Node<T>* newNode = new Node<T>( info );
if ( isEmpty() ){
head = newNode;
last = ne... | You don't need the while loop at all. Each node knows the nodes on both sides of it, that is all you need to update the list properly. Given the input node before, all you have to do is:
set newNode->previous to point at the before->previous node
set newNode->next to point at the before node
if before->previous is n... |
66,324,609 | 66,326,331 | What would be the C++20 concept for an iterable container? | I am still on C++17. I tried to write a generic code, to retrieve the "top count" element from any iterable container. But in my opinion this looks somehow clumsy.
Is there a better way to check the type traites in C++20 with concepts? How would that look like?
The requirements can be taken from the range based for as ... | Your ValueType trait basicly is std::ranges::range_value_t, and your is_iterable basically is concept std::ranges::range:
template <typename Container>
using ValueType = std::ranges::range_value_t<Container>;
template <class Container>
auto topFrequent(const Container& data) {
if constexpr (std::ranges::range<Contai... |
66,324,876 | 66,325,127 | C++ why do capital letters effect comparison with strings (sorting names) | I am fairly new to C++, working through Bjarne Stroustrup's "Programming and Practices using C++, 2nd Edition".
I am doing an exercise where you sort three names. I did this using the tools provided up to this point, so as not to jump ahead of the book. The method is to just use greater-than and less-than in an if stat... | From an EE perspective, consider that strings in C++ (or C for that matter) are simply binary-encoded data within the machine.
Each character (letter, number, symbol) - is assigned an ASCII numeric value so the computer can interpret what character you are referencing.
The thing to understand here is that lower case (e... |
66,325,200 | 66,325,300 | Why is a constexpr local variable not allowed as a default function parameter? | I thought I understood why C++ won't allow a local variable as a default function parameter:
int main () {
auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
but it's not allowed even when that variable is a constexpr local:
int main () {
cons... | It is an issue regarding lifetimes. Lets modify your function to
auto get_functor() {
constexpr auto local{1024};
return [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
Now, at the call site of get_functor, you get a lambda whose default value is the value of an object that... |
66,325,266 | 66,325,292 | C++ Randomized string output issue's | can someone help me understand why my code is not outputting the way I expect?
main.cpp
int main() {
Test test;
test.OutPut();
return 0;
}
Test.h
class Test
{
private:
string password;
string password1;
string password2;
string password3;
public:
char GetArrayChar();
string RandomizedS... | Inside setString, this line:
string password1 = password;
creates a new local variable, it does not modify the instance variable. Hence on return from that function, the local variable is discarded and instance variable remains unchanged.
You may want to try:
password1 = password;
This is also a problem in randomized... |
66,325,376 | 66,377,265 | clang++ does not respect -isystem flag, different behavior from g++ | On my macOS system, I have the following installed:
Protobuf 3.14.0 via brew install protobuf@3.14
g++ 10.2.0_4 via brew install gcc@10
clang++ 1200.0.32.29 via XCode
When I check out Google's Protobuf repo and build a file using clang++, it seems to ignore the -isystem flag that I pass:
git clone https://github.com/... | Combining answers/comments from Anton Malyshev and Ave Milia, the apparent reason is that Apple's custom clang++ version (installed when you install XCode) always inserts /usr/local/include at the start of the system include path list, above any other entries, including -isystem options passed on the command line. (Thi... |
66,325,392 | 66,325,416 | cpp: error: 'class boost::optional<std::__cxx11::basic_string<char> >' has no member named 'c_str' | I am new to c++ and trying to fix an issue in my function -
Test::Test(const boost::optional<std::string>& name):
mName(name)
{
...
Some statements
...
}
int Test::setResult()
{
...
i=system(mName.c_str())
...
}
The error I am getting is
error: 'class boost::optional<std::__... | The mName member is of the optional type. If you want the string behind that optional, you need to dereference it with something like:
i = system(mName->c_str());
Of course, you probably want to first ensure it has a value:
if (mName) i = system(mName->c_str());
|
66,325,563 | 66,325,602 | Not updating QLabel value | I would like to read a data file and print the size of the data using QLabel. I can only call setText before reading the data so it returns 0 and does not change after I read the data. Can you please help me with how I can update the value of Qlabel once the data read?
MainInterfaceWindow::MainInterfaceWindow(QWidget *... | Add a signal to your canvas class
// Canvas.h
class Canvas : public /* base class */ {
// required in header
Q_OBJECT
// ... other class stuff ...
signals:
void dataSizeChanged(int size);
}
In your MainInterfaceWindow, connect that signal to a lambda function that updates the text:
MainInterfaceWindow::... |
66,325,949 | 66,326,160 | Compiler assumes child class is virtual before I define its functions | Here's an example program demonstrating an issue I have with a big program.
Basically, I have the declarations of a parent and child class in an .h file. Because the parent class A is virtual, the compiler assumes that the child B is also virtual, and won't let me define its function in the .cpp file. The error says:
... | Once a method has been explicitly marked as virtual, it is always virtual in derived classes, even if it is not explicitly marked as virtual in those classes. There is no way to change that.
The reason for your error is that you have 2 competing and incompatible definitions of B::print() - one inline in example.h, and ... |
66,326,489 | 66,326,971 | How do I create a duplicate of an object in C++ when working with classes and objects (Object Oriented Programming) |
Create a friend function to duplicate a Shape object. The input parameter of this function will be
a Shape object, and it will return the duplicated object. Use the compare function to show that
the duplication is successful.
In this question, we were supposed to create a "Shape" class and add two private members: le... | You're almost there... I'd just like to point out a couple of error in your code.
You can't call your function Shape(), there is a class called Shape, and you cannot declare a friend constructor.
class Shape {
private:
double length, width;
public:
Shape();
Shape(double length, double w... |
66,326,654 | 66,326,776 | why it is asking me defination is not alllowed here before token | c++
why my code is not working i am working with pointer references using classes
it is asking me a function defination is not allowed
plz told me where i am wrong**
#include <iostream>
using namespace std;
struct bigone
{
int semo;
char text[1000];
} bo = {'123', 'This is a big structue'};
//Three functions t... | #include <iostream>
using namespace std;
struct bigone
{
int semo;
char text[1000];
} bo = { 123, "This is a big structue" };
//Three functions that have a parameters
void valfunc(bigone v1); //call by value
void ptrfunc(const bigone *p1); //call by pointer
void reffunc(const bigone &r1); //call by refe... |
66,326,861 | 66,327,265 | Does a subclass need a default constructor? | I am learning about inheritance right now, and there is one thing I haven't found a solid answer on. If I have three classes one being a super and two subclass, would my subclasses need a default constructor if they inherit the same fields? Class b doesn't have a default constructor because it inherits its fields from ... |
If [irrelevant], would my subclasses need a default constructor if [irrelevant]?
That depends on how your subclasses are used. If – and only if – you need to construct an instance of your class without providing construction parameters, then that class needs a default constructor. Whether or not you need to explicitl... |
66,327,073 | 66,341,005 | How to find and link CUDA libraries using CMake 3.15? | I'm using CMake 3.15-rc3 on my Unix-like system.
I need to link a program I'm building with several of the CUDA libraries, including cublas, cufft, cusolver, curand, nppicc, nppial, nppist, nppidei, nppig, nppitc, npps.
Based on what I found online, I need to do something like this:
add_executable(test benchmark.cpp)
f... | find_package(CUDA) is deprecated for the case of programs written in CUDA / compiled with a CUDA compiler (e.g. NVCC). The documentation page says (emphasis mine):
It is no longer necessary to use this module or call find_package(CUDA) for
compiling CUDA code. Instead, list CUDA among the languages named in
the top-le... |
66,327,311 | 66,328,426 | MinGw doesn't execute the program if file name has spaces | So I use notepad++'s NppExec to directly compile and execute C++ files.
npp_save
cd "$(CURRENT_DIRECTORY)"
g++ "$(FILE_NAME)" -o $(NAME_PART) -march=native -O3
NPP_RUN $(NAME_PART)
This all works fine, now assuming I have this piece of code:
#include <iostream>
using namespace std;
int main() {
cout << "Th... | The obvious answer is to simply not use spaces in your file names. It's only asking for problems.
But in this case have you tried using " around the NAME_PART variable?
g++ "$(FILE_NAME)" -o "$(NAME_PART)" -march=native -O3
NPP_RUN "$(NAME_PART)"
|
66,327,825 | 66,327,963 | How to use a custom deleter using WinAPI with std::make_unique? | So I'm just experimenting with smart pointers and how I can manage Win32 HANDLE objects with them, so I wanted to test out this simple code I wrote.
It's supposed to provide a custom deleter for std::unique_ptr to use when the smart pointer goes outta scope.
template <typename Function>
class PtrDeleter
{
Function ... | make_unique returns unique_ptr with defaulted deleter.
To provide your custom version you have to call unique_ptr(Pointer,Deleter) version of unique_ptr ctor:
template <typename Function>
class PtrDeleter {
Function _Closer;
public:
void operator()(void* memBlock) const {
_Closer(memBlock);
}
};
in... |
66,328,468 | 66,328,497 | passing reference to constant object while the object is not updated | I wrote a toy class below.
header
class saleData{
private:
std::string isbn;
unsigned cnt;
double price;
public:
saleData(const std::string s, unsigned c, double p): isbn{s}, cnt{c}, price{p} {};
unsigned getCnt(){
return cnt;
}
double getPrice(){
return price;
}
... | Non-const member functions (getPrice() and getCnt()) can't be called on const object. You should make them const, to tell that they won't modify any non-static data members.
class saleData{
private:
std::string isbn;
unsigned cnt;
double price;
public:
saleData(const std::string s, unsigned c, doub... |
66,328,731 | 67,116,403 | SEAL: How to read Relinkeys data in forms of modulo coefficients? | When running examples in SEAL (v3.6), I can print out polynomial coefficients of secret_key, public_key data using support functions
ofstream sk;
sk.open(filename, ios::binary);
for (uint64_t i = 0; i < poly_modulus_degree; i++)
{
sk << secret_key.data()[i] << endl;
}
sk.close();
with the coefficient data layout f... | RelinKeys is derived from KSwitchKeys which contains a data member in the type of vector<vector<PublicKey>>. Since PublicKey is basically the same with Ciphertext, RelinKeys is simply a 2-dimensional vector of Ciphertext.
The first dimension enumerates the relinearization key generated for a certain power of secret key... |
66,328,789 | 66,328,998 | C++ Can't read registry value data | Was recently working for a client and need to read a value from registry. So I wanted to start off by trying something simple, reading the system Guid from the registry. This is the code that I'm using and I'm having trouble figuring out how to read certain data properly. I found out how to read DWORD's from here but t... | The value MachineGuid in the key SOFTWARE\Microsoft\Cryptography in my environment is a string longer than 4 characters, not a DWORD value.
You have to allocate enough resion to read the value. Otherwise, ERROR_MORE_DATA will be returned as documented.
#include <cstdio>
#include <cstdlib>
#include <Windows.h>
int main(... |
66,328,964 | 66,329,141 | OpenGL and GLM problem with cube rotation | I am learning OpenGL from http://learnopengl.com and I have a problem with transformation based on this chapter Coordinate Systems...
I want to render something like this Movie but I have something like this Movie2 in 5 seconds its back on the screen. Sorry for many links but I think it's easier to show this by video.
... | The order of the vertex transformations in the vertex shader is incorrect:
gl_Position = u_Projection * u_Model * u_View * vec4(a_Pos, 1.0);
gl_Position = u_Projection * u_View * u_Model * vec4(a_Pos, 1.0);
The order matters, because matrix multiplications are not commutative.
|
66,329,014 | 66,336,731 | OpenSSL RSA_sign C++ - Different sign than the command line | I am trying to develop a Digital Signature tool using OpenSSL's libs but the created sign from my code is different than the one I get from the command line.
I checked and validated that the SHA256 digest is correct.
This is an example of the command I use to validate the signatures:
openssl rsautl -sign -inkey private... | I have implemented the RSA_verify function and based on the sign my code does, RSA_verify works and it returns that it is valid. I have also added the code to save the public key as well.
My best guess is that my code doesn't represent exactly the command.
|
66,329,134 | 66,329,379 | How to serialize/encode a custom object to bytes/bytearray? | I have the following python class:
class Header:
def __init__(self, id, len):
self.id = id
self.len = len
h = Header(1, 10)
How can I serialize/encode an instance of this class, h to bytes or bytearray, which can be written, for example to a socket?
To give a little more perspective, I need to write this ob... | This is called Serialization.
In Python, you can use the standard library pickle module which performs automatically the (de-)serialization, or serialize by hand. In that latter case, you decide the individual attributes to encode and the way to encode them. Then the struct module does the actual byte conversion.
pickl... |
66,329,139 | 66,331,370 | Append image in CIMG and save in stb_image_write not working | I am using stb_image stb_image_write and CImg with following code
int width, height, bpp;
img = stbi_load(imgPath, &width, &height, &bpp, 3);
CImg<unsigned char> cimg(img, width, height, 1, bpp);
CImg<unsigned char> wimg(width, 10, 1, 3, 0);
cimg.append(wimg,'y');
cimg.display();
stbi_writ... | Ok I got it worked as mentioned by Mark Setchell in comments about interleave so I have to permute the buffer structure as mentioned in below post
CImg library creates distorted images on rotation
so if I need to used these three libs than my code would be as below
int width, height, bpp;
setHeader();
img = s... |
66,329,582 | 66,467,335 | Scrolling to the bottom of the TextView in gtkmm | The layout is the following:
There is a Gtk::ScrollWindow and inside of it is Gtk::TextView, the latter is of a derived class called TextArea.
As a test, there is a button that adds some texgt to the TextView one line at the time and attempts to immediately scroll to the bottom.
The code:
void MainWindow::onButtonPress... | I believe your problem is that you use an iterator to move across the buffer in which you are inserting text. As the documentation suggests:
Iterators are not valid indefinitely; whenever the buffer is modified
in a way that affects the number of characters in the buffer, all
outstanding iterators become invalid.
Ins... |
66,329,763 | 66,330,128 | Is there a more efficient way for storing vector<vector<string>> ? C++ | The real file I read is about 15.000 kBs. Thus I am not sure whether this is the best way of storing such a data structure.
Here is the code.
string line;
ifstream File;
vector<vector<string>> v;
string filename = "meddra.txt";
File.open(filename);
if (File.is_open()) {
while (getline(File, line)) {
string... | You are modifying an empty vector
vector<vector<string>> v;
v[c][j].push_back(line);
Instead you should do v.push_back with a vector<string>
|
66,330,703 | 66,331,155 | Count total number of pairs? | This is a HackerRank Problem ,I have written my code in c++ , but I am not getting correct output:
Here's the problem:
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
n = 10
ar... | You are just missing to take into account the last sum.
An addition += sum/2 must be added after the for loop.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
std::cin >> n;
std::vector<int> arr(n);
for(int i=0; i<n; i++) {
std::cin >> arr[i];
}
std::sort(a... |
66,330,976 | 66,331,442 | PEB_LDR_DATA on x64bit | What is the address of _PEB_LDR_DATA from the start of PEB?
Somewhere is says One of those structures is a pointer to _PEB_LDR_DATA within offset 0x0c from the start of the PEB.
and somewhere it says PVOID64 LDR_DATA_Addr = *(PVOID64**)((BYTE*)Peb+0x018); //0x018 is the LDR relative to the PEB offset. The base address... | If you look at the PEB structure, you'll see the following:
typedef struct _PEB {
BYTE Reserved1[2];
BYTE BeingDebugged;
BYTE Reserved2[1];
PVOID Reserved3[2];
PPEB_LDR_DATA Ldr;
// ...
} PEB,... |
66,331,177 | 66,331,206 | How can I solve segment error while giving values greater than 10000000 in this c++ programm? | How can I solve segment error while giving values greater than 10000000 in this c++ programm?
I was trying the practice projects in projecteuler.net and I got this error
Please help
It is showing error in this portion of the code uint64_t prime[max];
#include <iostream>
#include <unordered_set>
#include <vector>
#inclu... | Variable-length array like
uint64_t prime[max];
is not supported in C++ and it has a risk of causing stack overflow when trying to allocate a large size.
You should use std::vector instead.
std::vector<uint64_t> prime(max);
|
66,331,441 | 66,331,920 | C++ start thread with method of internal class | I have a class B that contains an internal class A. The class A has a method that needs to access some members of B, so it has as one argumet a reference to the external class and one other argument.
Now i would like to start this method in another thread from B.
I know this might be a duplicate of this question: Start... | You are trying to pass nullptr to the std::thread constructor in B::B():
myTread = std::thread(nullptr);
Rewritten it to use the member initializer list and to let std::thread be default constructed it could look like this:
B::B() : member_b{10}, myTread{}, myA{new A(5)} {}
|
66,331,667 | 66,333,092 | C++ union member object cannot be assigned to post-construction | The test code (compiled -std=c++17) below is very simple. In it, assignment to any member of the union after the constructor has run appears to do nothing at all. I instantiate a Union that contains Parent and Child class members and then assign to the child member. I have tried several Union constructors (numbered 1-4... |
Union(){ new (&parent) Parent(); }
Your constructor activates the parent member.
u.child.Print();
You access inactive member of the union. The behaviour of the program is undefined. Regardless of which constructor alternative you use, you access an inactive member at some point of the example.
To answer all of yo... |
66,331,885 | 66,332,154 | How to compose a variable name from a macro in C++? | How to compose a variable name from a macro in C++?
For example:
#define PREFIX p_
#define VAR_NAME #PREFIX#name
So, VAR_NAME must be exposed as p_name. Is it possible?
| You have to jump through some hoops with the preprocessor to do this:
#define CONCAT_(a, b) a##b
#define CONCAT(a, b) CONCAT_(a, b)
#define PREFIX p_
#define VAR_NAME CONCAT(PREFIX, name)
int VAR_NAME;
CONCAT_ combines text
CONCAT evaluates macros before combining them
|
66,333,803 | 66,335,287 | Why this function variable only works if it's static? | I'm trying to put a bunch of sounds in a std::vector because it's very convenient.
I'm using an auxiliary variable called laser, load the sound into it and, if it's everything ok, push_back into the vector.
When I try to play any the sound, nothing happens, not even error messages which should be printed if anything go... | OK, so following the advices from the comments, I've made the following changes to make ktp::SDL2_Sound class follow the rule of 0 and now it works without the need to set the laser variable to static. This solves the problem, but I'm still not sure why it worked being static.
class SDL2_Sound {
public:
//~SDL2_Soun... |
66,334,635 | 66,335,265 | C++ Linked Lists Inserting a Node, Previous Node intialization | I was looking at my C++ textbook at an example of a Linked List function for inserting a new node in the list which is below....
Void NumberList::insertNode(double num)
{
ListNode *newNode; //A new node
ListNode *nodePtr; //To transverse the list
ListNode *previousNode = nullptr; ... |
I was wondering why does previousNode get initialized to nullptr twice in the code? Wouldn't once be good enough?
Once would be fine. The second assignment is redundant.
Another thing, could anyone give me an example of how we would insert a node into the list if the data being stored was a char or a string?
You'd ... |
66,334,681 | 66,334,739 | Using a template several times | I was trying to implement max-queue
But a more general version with arbitrary Associative function and arbitrary data type.I did the following for the max_stack part:
template<typename T,class F=function<T(const T&,const T&)> >
class Stack{
F func;
stack<pair<T,T> > st;
public:
Stack(F f):func(f){};
boo... | You will have to initialize the members via member initialization list because they don't have default constructors as the message suggests.
It will be like this:
explicit Queue(F f): func(f), right(f), left(f) {}
|
66,334,838 | 66,334,904 | C++, Learning, Basic Return Primes | My goal is that: the program return the list of numbers in the vector i made, which are the primes numbers, the code is wrong,
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
vector < int > L;
bool mark[10];
void colador()
{
fill(mark,mark+10, false);
for(int i=2; i*i <=10; i++)
... | Firstly, general functions are not automatically executed just by defining. You have to call them to execute them.
Secondly, the loop in the main() is wrong. It may read out-of-range without checking.
Also your colador() function is wrong. The array mark has only 10 elements (mark[0] to mark[9]), but you are accessing ... |
66,335,266 | 66,335,990 | (Rcpp)armadillos abs() function outputs false values when used with c++ double while std::abs works | Consider this R function:
r_abs <- function(x,y,z){
2 * abs((x >= y) - z)
}
And those 2 RcppArmadillo equivalents:
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(RcppProgress)]]
#include <RcppArmadillo.h>
#include <string>
#include <progress.hpp>
using namespace arma;
// [[Rcpp::export]]
double arma_abs(c... | This is a tricky and somewhat tedious issue with C and C++ partially fixed by the corred std::abs() added more recently.
If you're on a Unix system try man 3 abs. Your use of the (unqualified) abs() is equivalent to ::abs() and it gets int abs(int) from stdlib.h.
And the cast to int makes the argument -0.5 truncate to... |
66,335,672 | 66,336,775 | Make integer sequence unique at compile time | Suppose I have:
template<int... N>
class seq
{
};
template<int... N>
struct uniq{
using type = seq<N...>;
};
I need to make the sequence unique somehow, so that
std::is_same_v<uniq<1,2,2,2,3,3,3>::type, seq<1, 2, 3>>;
ends up being true. In other words make the sequence unique then create a seq.
Is there a way ... | Using std
Using <type_traits> from the standard library, you can implement your own like this:
#include <type_traits>
namespace detail
{
template<class, auto... Ns>
struct uniq_impl;
template<template<auto...> class T, auto... Ms, auto N, auto... Ns>
struct uniq_impl<T<Ms...>, N, Ns...> : std::conditional_t<
(... ... |
66,336,043 | 66,365,548 | Thrust: Computing set_difference of multiple segments in parallel | I have written some code to compute a set_difference per segment using thrust. The idea is to use additional arrays to indicate which element belongs to which segment, and a custom comparator.
This produces the correct output sets, but the output segment sizes are wrong if an input segment is empty. Reduce-by-key is us... | The following approach is working now. Instead of discarding the unique segment ids and storing the reduced values in the output array, both outputs are saved to temporary storage. Then, the output array is initialized with zero to account for any empty segments, and the key-value-pairs are used to set the segment size... |
66,336,390 | 66,336,473 | Removing a file using remove(); | Trying to remove/delete a file using the function below. Unfortunately, it fails every time.
Had cut many lines of code that seemed unrelated to the question.
int main()
{
Login();
}
the function below checks the existence of the file. if exists, it can remove it.
void Login()
{
char name[20], password[20], fi... | "jackson.txt" fits within an array of 12 chars. ID is an array of 10 chars. If you use that filename, you will access outside the bounds of the array and behaviour of the program is undefined.
Conclusion: Don't read unconstrained user input into constant size array. Also don't strcat unless you can prove that that the ... |
66,336,924 | 66,337,045 | How to get element from parameter pack? | #include <iostream>
#include <tuple>
#include <utility>
template <typename... T>
decltype(auto) getParameterPackVals(T&&... Args) noexcept {
return std::get<1>(std::forward_as_tuple(std::forward<T>(Args)...));
}
int main() {
std::cout << getParameterPackVals(2, 1.0, 2.0, 3.0, 4.0, 5.0) << std::endl;
//pri... | Wow this is a first I solved it on my own!
So while brainstorming I remembered that if I named a template argument such as size_t V I could pass it in with <V> when I called the argument. So I took V n out of the function arguments and called the function as getParameterPackVals<2>(1.0, 2.0, 3.0, 4.0, 5.0). The final c... |
66,336,958 | 66,356,341 | Safe way of creating new QDialog object | I am writing a Qt application where I have QListWidget filled with QListWidgetItems and I want to create a new dialog on double click on QListWidgetItem. So I created a new dialog class as in this qt tutorial. Now, I added on_listWidget_itemDoubleClicked(QListWidgetItem* item) slot where I should create an instance of ... | Yes what you are doing is fine. There are some minor issues you may want to address:
Closing the dialog does not free the memory. The memory will be consumed until the unique_ptr is destroyed.
The unique_ptr is not cleared when the dialog is closed. This may be fine now, but if you try to use that unique_ptr later it... |
66,337,016 | 66,337,108 | Conditional operator mis-matching | When I execute in python following code
print(0<5<2)
It gives False as output
but same thing in C++
std::cout<<(0<5<2);
returns True
Why this contradiction?
| In Python, 0 < 5 < 2 is equivalent to 0 < 5 and 5 < 2.
In C++, it is equivalent to static_cast<int>(0 < 5) < 2.
The Python shorthand is originally inspired by mathematics, but has been so generalized that you can write really strange stuff, like
>>> 1 < 5 in [2,3,4]
False
>>> 1 < 5 in [2,3,5]
True
and confuse all your... |
66,337,091 | 66,337,592 | Is there a container for modeling publisher-subscriber relationship with fast lookup for either? | I have a publisher-subscriber relationship I want to model. Publishers can have multiple subscribers, but each subscriber can only get data from a single publisher. I thought a map of vectors would be good for this:
std::map<publisher, std::vector<subscriber>>
Publisher lookup, insertion, and deletion is fast, subscri... | I would suggest:
struct SubscriptionRecords {
std::unordered_map<publisher, std::unordered_set<subscriber>>
subscribers;
std::unordered_map<subscriber, publisher>
subscriptions;
};
Then some example methods:
void add_subscription(publisher p, subscriber s) {
auto res = self->subscriptions.i... |
66,337,100 | 66,337,174 | How many variables can be in local scope | My question is pretty simple: how many variables can be in local scope to be properly translated?
I have to create a small translator (for studying purposes) from C++ to Assembly. During the translation process, there is a dynamic table of identifiers (variable names, in simple case, I suppose). How many can there be?
... |
How many variables can be in local scope
The C++ standard does not specify an exact maximum number.
It does have following recommendation (quote from latest standard draft):
[implimits]
Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process.... |
66,337,765 | 66,337,853 | Lost wake-up: What if the producer acquires the mutex first? | I'm trying to understand the lost wake-up issue when using condition variables. I believe I have used the proper design-pattern below. The consumer:
lock the mutex
while the condition is not satisfied
wait on the condition variable
consume
unlock the mutex
and the producer:
lock the mutex
produce
unlock the mutex
... |
But what if the producer acquires the mutex before the consumer? Then it could notify() before the consumer is waiting.
No problem.
Your cv.wait(ul, [this]{ return consumerReady; }); is the same as
while(not consumerReady) cv.wait(ul)
So, the actual consumerReady variable is checked first and only if it's not set do... |
66,337,882 | 66,346,638 | C++11: inconsistent warnings for out-of-order instance member initialization | The following code crashes, raising std::bad_alloc or sometimes std::logic_error.
#include <string>
class Crasher {
public:
Crasher() : value(default_value) {}
private:
std::string value;
const std::string default_value = "default is yours";
};
int main(void) {
Crasher();
}
I believe the reason is t... | Initializing one int from another performs an lvalue-to-rvalue conversion on the source. If that’s uninitialized, the behavior is undefined. Initializing one object of class type from another does not do so—it calls a constructor, which merely binds a reference to the source. That’s not undefined even if the source ... |
66,338,066 | 66,341,223 | FatFS - Cannot format drive, FR_MKFS_ABORTED | I am new to embedded development and have been tasked with implementing a file system on SPI flash memory. I am using a w25qxx chip and an STM32F4xx on STM32CubeIDE. I have successfully created the basic i/o for the w25 over SPI, being able to write and read sectors at a time.
In my user_diskio.c I have implemented all... | Here:
fresult = f_mkfs("0:", FM_ANY, 0, work, sizeof work);
The second argument is not valid. It should be a pointer to a MKFS_PARM structure or NULL for default options, as described at http://elm-chan.org/fsw/ff/doc/mkfs.html.
You should have something like:
MKFS_PARM fmt_opt = {FM_ANY, 0, 0, 0, 0};
fresult = f_mkf... |
66,338,097 | 66,340,977 | Perform best cycle sort knowing order at the end | We have list A that after sorting needs to look like list B and we have effort or "weight" of each number so when we are swapping in order effort will swap also ,they are connected.
Knowing how list should look like at the end find what is the lowest effort needed to sort list A to look like lis B
I've found answear to... | I decided to sit down a bit and try tackling this problem. If I understand correctly, we are performing swaps on list in order to get them sorted like in the destination list.
There are two types of operations we can do. Swapping two numbers to destination, which is swapping two numbers and they both land where they be... |
66,338,196 | 66,338,379 | How to put values to 3d array which is dynamically allocated in C++ | I am writing some codes to understand how dynamically allocating 3d array works in C++.
This is just a sample code I wrote.
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cstdio>
using namespace std;
int Na = 3;
int Nd = 3;
int Ny = 3;
int m... | It's a false warning, but a justified one. You should have made Na, Nd and Ny at least const or better constexpr.
As they are, they are global variables visible and modifiable by other compilation units. For the compiler the logic goes "they might change to be smaller than 3". Const-correctness also helps with that dia... |
66,338,446 | 66,338,642 | std::bind with member function and this in c++ | I'm trying to learn C++ and I'm experimenting with the std::bind function of the standard library. As a result, I understood that std::bind allows to wrap a function and to partially apply the function. This works very well with functions that are not member functions of a class. Now I try to use std::bind with class m... | Let the compiler deduce types based on passed arguments:
std::function<void(void)> function2 = std::bind(&Class2::print, this);
above is enough.
Version with explicit template arguments list looks like:
std::function<void(void)> function3 = std::bind<void(Class2::*)(),Class2*>(&Class2::print, this);
// std::bind<void... |
66,338,460 | 66,338,504 | Compiler says about redifinition error, but functions where mentiones just in header and C++ file | When I described prototypes of functions in header file and implemented functions at MoveMatrix.cpp, I got error: compiler says "error: redifinition of nc::NdArray translate(float, float, float)", although I hadnt described or even mention this functions int other files besides MoveMatrix.h. I have got error from 4 lin... | The suffixed {} means that the functions are defined in the header. Thus the one definition rule is violated, and compilation will fail. Remove them to convert the statements to forward declarations.
In other words,
nc::NdArray<float> translate(float trX, float trY, float trZ) {};
becomes
nc::NdArray<float> translate(... |
66,338,663 | 66,351,349 | getting library_error exception when trying to use boost::interprocess::message_queue | EDIT
also tried with boost 1.75
I'm learning how to use boost::interprocess message queue,
I'm using the example from the documentation here
with one different - for the other process I'm using fork()
but I'm getting
boost::interprocess_exception::library_error
when I'm trying to read from the queue;
I'm running boos... | Looking at the code here, the passed buffer to receive must be at least as big as max_msg_size (100, in your case).
|
66,338,701 | 66,338,772 | Call single public function of a class without using its name | Is it possible to invoke the function of a class based on the fact that it is the only public one ? What I mean:
Something like:
double res = MyClass().myFunction(n);
becomes
double res = MyClass()[0](n);
Ideally I would have liked to call the function using a string with its name:
double res = MyClass().reflection("... | You can overload the call operator of the class. This is commonly called a Functor:
class MyClass {
public:
int operator()(int param) const {
return functionName(param);
}
int functionName(int param) const { return param; }
};
MyClass c;
int returnVal = c(3);
Edit addressing const comment:
The fu... |
66,339,674 | 66,339,735 | LeetCode C++ Convert char[] to string, throws AddressSanitizer: stack-buffer-overflow error | I'm learning C++, and on LeetCode, converting a char[] to a string gives a AddressSanitizer: stack-buffer-overflow error.
string test1() /* Line 70 */
{
char test[] = "11";
return string(test);
}
string test2() /* Line 76 */
{
char test[] = {'1', '1'};
return string(test);
}
int main()
{
cout << t... | If you want your char * to be processed properly as a string, you must make sure it's null-terminated:
char test[] {'1', '1', '\0'};
String literals do that automatically. "11" is the same as {'1', '1', '\0'}.
Alternatively, you can pass the number of characters to read:
string str(test, sizeof test);
|
66,339,720 | 66,339,756 | Include guards for modules | This may be a ridiculous question and I'm 99% sure of the answer but I wanted to be sure.
C++20 modules do not require any type of include guards for module interface files.
Is my statement correct? Everything I've read about modules thus far leads me to believe that guards are not required as modules are only ever c... | Include guards are not needed. Modules are only imported once.
Preprocessor defines do not escape from modules, so include guards would not work anyway.
Macros, preprocessor directives, and non-exported names declared in a module are not visible and therefore have no effect on the compilation of the translation unit t... |
66,340,711 | 66,341,016 | Why can't I use google test's ASSERT_TRUE for my SFINAE check? | I have a simple SFINAE check for the existence of a static member function using C++17's std::void_t:
template <class T, class X = void>
struct has_bar {
static const bool value = false;
};
template <class T>
struct has_bar<T, std::void_t<decltype(T::bar(std::declval<int&>()))>> {
static const bool value = true... | This error occurs because has_bar::value has been declared but not defined. Somehow, the ASSERT_TRUE macro has odr-used this object. It's not necessary to understand exactly what ASSERT_TRUE is doing; you should always define your static class members.
The easiest way to do this is to inherit from std::false_type and s... |
66,341,001 | 66,341,072 | Having errors with using a header and source files | I created a header called One.h to include my class of a 3d vector, and then I use a source file called main.cxx to input the class into an int function. However, I keep getting these errors, and I have been trying for days to fix it but I can't. I am new to C++.
/usr/include/c++/4.8.2/bits/stl_iterator_base_types.h:1... | You have a collision between std::distance and your float distance(Vector3d v1, Vector3d v2) function.
Removing using namespace std; and qualifying with std:: where necessary will resolve that.
This is an example of why it is recommended to use rarely, if ever, using namespace std;.
|
66,341,228 | 66,356,087 | Show help for my Gtkmm application without Autotools or Meson | I have written a small application using Gtkmm for which I would like to provide documentation for users. For this, I would like to launch the Gnome help system from my application's menu (For a working example, one can look at gedit).
First, I wrote a minimal Mallard index.page file:
<page xmlns="http://projectmallard... | The help files have to be somewhere Yelp can find them. Usually you would install them to /usr/share/help/LANG/APPID/, where LANG is a language identifier (or just C for the untranslated docs), and APPID is some identifier for your app (matching the basename of your .desktop file is a good best practice).
If you use au... |
66,341,843 | 66,341,930 | Is it allowed to leak pointers of thread local variable? | I am currently trying to better understand thread local storage in C++. To this end I wrote the following example:
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
thread_local int thread_index;
std::vector<int*> pointers;
std::mutex mutex;
void show_index()
{
{
thread... | It's precisely the same as any other local object. All threads share the same view of memory and a function or thread can pass a pointer to a local object to another thread or function if it wants to. If you do this, it's you responsibility to ensure there are no race conditions and an object isn't accessed outside of ... |
66,342,183 | 66,342,410 | Reconstructing Control Flow of Decompiled Program | I am writing a very simple decompiler (in C++) for a basic compiled bytecode (an entirely different language). The executor uses a stack-based machine, and most instructions are fairly easy to piece back together.
I have run into an interesting predicament with conditions and looping constructs. One of the opcodes in t... | Reko is a decompiler that tries to reconstruct C-like code from machine code. It has a pass that reconstructs high-level constructs like if, while and switch statements. The code is based on the paper "Native x86 Decompilation using Semantics-Preserving Structural Analysis and Iterative Control-Flow Structuring" by Edw... |
66,342,428 | 66,342,734 | Make decision depending on variadic types | I know I have made the title as blurry as possible, but the sample will hopefully set the goals.
I have a Base class and families of Derived classes (classy OOD, nothing more).
Furthermore I have a function which takes variadic templates and I want to make decision depending on those templates.
template<typename... Ts>... |
And to complicate the matters, my compiler is limited with C++14 support.
C++14 ... so you have to simulate template folding...
What about something as follows?
template<typename... Ts>
void do_smth (std::vector<std::shared_ptr<Base>>& vec) {
using unused = bool[];
for ( auto&& ptr: vec)
{
bool ... |
66,342,652 | 66,342,740 | CMake fails to link nested library | im trying to build my first CMake project and it fails on CXX executable NeuralNetLibrary.
I get the undefined reference to FFLayer::test() error when building.
The full project is in here
https://github.com/JRazek/ConvolutionalNetLib.
Please help me how can I solve this issue.
| The reason is that you're missing dependencies between the different library projects. For example, the Net library uses a function defined in FFLayer in Net.cpp, but the corresponding target_link_libraries(Net PRIVATE FFLayer) is missing.
This causes CMake to link against the static libraries in the wrong order, as it... |
66,343,076 | 66,345,554 | Call a member function with lock? | I design a queue like below, and one question is if the member function have a lock in it, I want to call it in another member function, which have a lock in it too. This will cause the problem of reentrant locks?
class MyQueue {
public:
bool Empty() {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.si... | If a public member function needs to call another public member function, both of which lock the same mutex, then it's better to split them so that they call a private member function that doesn't lock. The private member function assumes that a lock is already held. This way you avoid having to use a recursive mutex, ... |
66,344,091 | 66,345,672 | How to correctly use smart pointers in OOP | I am wondering what is the correct way to use std::unique_ptr in an Object-Oriented Programming. Let's say I have a class that contains an member object that can be passed by pointer
class B
{/*Some code here*/};
class A
{
public:
A();
B* getMember();
private:
std::unique_ptr<B> member
};
First: Should th... | shared_ptr implies a complex ownership rule where the object in question is owned by multiple co-equal parties, and its lifetime cannot be determined easily. Deciding to go with shared_ptr because it is simpler or easier is like using a bazooka to kill a fruit fly bothering you because it is more powerful than a fly s... |
66,344,389 | 66,344,610 | Downcasting non-polymorphic types? | Please consider the following C++20 program:
struct B { B(); private: int whatever; }; // non-aggregate
struct D : B { D(); int x; private: int whatever2; }; // non-aggregate
int main() {
D* d = new D;
d->x = 42;
B* b = (B*) d;
D* d2 = (D*) b;
return d2->x;
}
Is this program ill-formed or have undefine... |
Is this program ill-formed or have undefined behaviour?
This program is well formed. You can cast a pointer from a base type to a subtype without any issues.
If so, would one of the *_cast functions be more appropriate than the C-style cast?
Certainly! The default cast to use is static_cast<T>(...). It will avoid c... |
66,344,490 | 66,344,747 | How to calculate Matrix efficiently in C++? | I am new to C++ and programming so I think I am making inefficient codes.
I was wondering whether there is any way I can speed up the matrix calculation process.
For example, this is the sample code I write which finds the maximum differences(in absolute value) between 3d array 'V' and 'Vnew'.
First, I take subtraction... | There's not much you can do with the for loops, as the maximum difference can locate at all possible places. You have already succeeded in iterating the array in the correct, linear, order.
Compilers are generally quite efficient in optimising, but they apparently fail to flatten a contiguous array, such as float V[Na]... |
66,345,219 | 66,345,287 | Why is it ok to declare a class name in template param list | This Chromium doc offers a weird code snippet:
using ForReload = base::StrongAlias<class ForReloadTag, bool>;
^^^^^^^^^^^^^^^^^^
it compiles, though not declared anywhere
where StrongAlias is defined as (source code):
// TagType is an empty tag cl... | Due to the way C++ grammar works, instead of something like foo, you can say class foo:
foo f1; // valid
class foo f2; // also valid
This can be used to disambiguate when there is a variable of that name in the scope:
int foo; // variable
class foo f1; // class, not the variable.
And a weird thing is, wh... |
66,345,726 | 66,345,902 | Dev Cpp shows wrong percentage in this cpp program | What I have tried
I tried to make percentage static
I don't understand why this percentage variable in setData displays wrong value
I made percentage variable public. But that's allowed in cpp.
Program description
This is a very simple program. I was doing it to learn how we can define function outside class.
Expecte... | There are several problems.
percentage=(total/500)*100;
This line accesses total. However, you never set total to a value. It is uninitialized and will contain garbage value if you try to access it.
You have a function int result::sum() which calculates total, you
have to call it before you calculate percentage. clas... |
66,345,784 | 66,346,797 | How to input different numbers as different elements of array? | This program basically reverses a number like 4568 to 8654.
It is not taking proper input. I know of other ways to do this but could you suggest me how to make this program work.
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int num[25];
int a, b, c, d;
cout<<"Enter the no. which... | Your code has a few errors.
a = (int)sizeof(c) / 4; will initialize the value of a to be 1 (in platforms where sizeof(int) is equal to 4).
The for loop iterates infinitely. This is because b is initialized to zero (as stated above and 1 - 1 = 0) and the stop condition is set to b <= 0 and since your doing b-- in ever... |
66,345,792 | 67,572,480 | How do i open the default application using DelegateExecute? | I want to open a jpg file using the default application the user has set in his/her computer.
The prog id for jpg file from :
Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.jpg\UserChoice
is "AppX43hnxtbyyps62jhe9sqpdzxn1790zetc". When i check the shell command for the same fro... | To open a file in the users default program, use ShellExecute. Use ShellExecuteEx if you want to force a specific ProgId.
You are not supposed to read the registry yourself. DelegateExecute is one of 5(ish) ways file type commands can be registered (others include ShellEx extension, DDE and DropHandler).
If you still w... |
66,345,884 | 66,345,970 | std::vector vs std::array vs normal array | I give online coding contests, where the speed of the program is everything. Over the time I have come across 3 ways to use the concept of array in C++. The questions of the contests usually require us to create a dynamic array of the given size. So its just a one time creation of the dynamic array as per the input and... |
push_back takes a long time compared to arr[i]=x;.
Sorry but you are showing your lack of experience with vectors here, because your examples do two different things.
You are comparing something like this code
vector<int> vec; // vector created with size zero
for (...)
vec.push_back(x); // vector size incr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.