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 |
|---|---|---|---|---|
62,201,643 | 62,201,793 | auto and {}-lists question regarding Stroustrup C++ book | The following appears in Stroustrup C++ 4th Ed. Page 164.
T v3 = f();
T v3 {f()}; // works if and only if the type of f() can be implicitly converted to a T
auto v3 = f(); // v3 is of some appropriate type
Does anyone have an example of what type T could be for these examples?
My understanding of assigning functions ... | Your not assign a function pointer here. f() means call the () operator of whatever f is and return the result. So if we say f is
int f() { return 42; }
then for
T v3 = f();
T needs to be something that can be created from an int. With
T v3 {f()};
T needs to be something that can be created from an int, and it als... |
62,201,644 | 62,211,500 | Runtime error occured while iterating over 2d vector | I had given a 2D board containing 'X' and 'O' (the letter O), and I want to replace all 'O' surrounded by 'X'.
Ex:
X X X X
X O O X
X X O X
X O X X
ans:
X X X X
X X X X
X X X X
X X X X
Here is my code:
class Solution {
public:
void solve(vector<vector<char>>& board) {
solution(board);
}
bool issaf... | I think that a place where the error could be occurring is at board[i+1][j] and board[i][j+1] as when i==R-1 and j==C-1, the index is out of range. I don't see any other place for runtime error to occur assuming there is always a column and row in the vector.
Maybe you could try replacing all these cases with
For Eg.... |
62,201,808 | 62,216,460 | Resolving dependencies of orthogonal modules | I have a project composed of several modules and I would like to use CMake's add_subdirectory function:
Project
+ CMakeLists.txt
+ bin
+ (stuff that depends on lib/)
+ lib
module1
+ CMakeLists.txt
+ (cpp,hpp)
module2
+ CMakeLists.txt
+ (cpp,hpp)
module3
+ CMakeLists.txt
+ (cpp,hpp)
... |
Is there a way to program the dependency on the logging module into CMakeLists of the top-level modules...
Yes, you can define a CMake library target for the logging functionality in the root CMakeLists.txt file.
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16)
project(MyBigProject)
# Tell CMake to build a sha... |
62,201,852 | 62,202,038 | Passing largest int64_t variable values from C++ to R via Rcpp and the bit64 R package | I have written a function to raise 2 to a given power. I want to use 64 bit integers. In R, the bit64 package have the following for the maximum and minimum limits:
From R:
> bit64::lim.integer64()
integer64
[1] -9223372036854775807 9223372036854775807
This is -(2^63) and 2^63.
However, for some reason, my Rcpp co... | Quick guess of mine (that was proven right): the max value itself may be the one flagged for NA. So compute the 'one minus' that value and try it.
Quick guess of mine: the max value may be the one flagged for NA. So compute the 'one minus' that value and try it
// [[Rcpp::export]]
Rcpp::NumericVector largeval ( ) {
i... |
62,202,611 | 62,208,495 | How add a private\custom Node.js module on package.json | I create a custom node.js plugins in c++ using gyp.
My plugin is not published\public yet so it's not describe on package.json.
I need copy it manually on my node_modules... It's not perfect but it works...
How describe it on package.json to allow npm to retrieve it, compile it and made it visible from my node applicat... | you can specify the dependency directy
npm install --save /path/to/your/module
for more information, consult the npm-install documentation
|
62,202,720 | 62,228,434 | API design for measure time spent in a function | Which of the following API:s would be cleanest if you want a way of measuring the time spent in a particular Callable f, in terms of composability, ease-of-use, and clean callsite.
/** Calls `f` with args and returns a TimedResult carrying
* the return value of `f`, and the real time spent in `f`.
*/
template<class Fun... | I find that option 2, with the addition of passing the result as reference-to-const, is the most useful:
It gives you the return value back, so it can be used directly
The notification callback can use the result to print something like
"Processed %zu entries in %.7f seconds\n"
For for different return types, it is po... |
62,202,811 | 62,208,246 | Explanation for problem of choosing at least two elements from array such that their GCD is 1 and cost is minimum | While reading the solution to the problem here, I noticed that during the iteration through the map (second for), in some cases some insertions are performed in the same map (the 'else'). What is the behavior of the for loop in this case? Is the new insertion omitted by the iteration? Is this correct?
Edit: here is the... | There are two parts to your question: does the insertion leave the iterator used in the for loop as a valid iterator, and if so is the newly inserted element earlier in the map or later?
Inserting into a map (via operator[] does not invalidate iterators, so the compiler generated iterator for that second for loop is st... |
62,203,329 | 62,203,934 | why is singleton working with pointers but not with references? | I want to write a Meyers Singleton class using references but it does not work. I seem to still get separate instances of the class with each call to the instance accessor method even though a print suggests the constructor is only being called once. But if I write it using pointers it works fine. Can anyone explain wh... | X x1 = X::getX(); is making a copy of the singleton instance. So is X x2 = X::getX();. That means you actually have three instances of X. Oops. How can that happen? This is supposed to be a singleton!
If a singleton class is copyable and/or moveable, then it really isn't a singleton. So enforce that by deleting the cop... |
62,203,379 | 62,205,327 | Stringstream Delimiter | Is there a default delimiter for stringstream? From my research, I understood that I can use it to split a string using space and comma as delimiters. But can I use other delimiters for stringstream?
Here is a C++ code snippet :
vector<int> parseInts(string str) {
// Complete this function
stringstream ss(str)... | There is no "delimiter" for streams at all. operator>>, on the other hand, implements its reading by delimiting on whitespace characters. For other delimiter characters, you can use std::getline() instead, eg:
vector<int> parseInts(string str) {
// Complete this function
istringstream iss(str);
vector<int... |
62,203,496 | 62,203,640 | Type trait to receive T::value_type if present, T otherwise | Required is a type trait for a type T providing a typedef type which is of type T::value_type if T has a typedef value_type, T otherwise.
I have tried the following implementation but it does not seem to work (typedef is always of type T, even if T::value_type is present):
template <class T, class = void> struct value_... | The specialization needs to match the base template.
Your base template has class = void, that means the second parameter in your specialization need to be void to match.
The way to do that is to use something like std::void_t, which will become void whatever we put in it. It's only purpose here is to allow SFINAE, if ... |
62,203,590 | 62,204,351 | C++ vector vs C# List. Why are they producing different results? | I'm translating some code from C++ to C#. The code is simple enough and most of the syntax involved is almost the same, however the C++ version uses a vector<vector<int>> structure that doesn't exists in C#, so I replaced it with a List<List<int>> which I initialized with empty "rows" since I need it to represent a tab... | In the C++ code doesn't L[i] = L[j]; make a copy of the vector at L[j] and store it in L[i] (similar thing for the variable max)? To achieve a similar result in C#, you could do L[i] = L[j].ToList() to copy the list.
|
62,203,928 | 62,209,055 | Crop and show image that i get from Haar Cascade | I have trained Haar cascade and now i need to work with founded object. How i can crop it from original image and show in new window?(or show multiple window if i found 2 object on image). There is my code (opencv ver 2.4.13):
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
using namespace std;... | Your trafficLights vector is holding each rectangle's data of found objects. You just need to take left&top coordinates, width and height of each rectangle and you already have them. All you need is cropping each rectangle by creating Mat format of them and showing in different frames.
You can check here to learn more... |
62,204,422 | 62,204,441 | no match for 'operator<<' C++ | My program won't run I get an error message saying:
`error: no match for 'operator<<' (operand types are 'std::string' {aka 'std::__cxx11::basic_string<char>'} and '<unresolved overloaded function type>')|`
On the cout << address, " ", street << endl; line
I was using VS2017 but switched to CodeBlocks mid-way thro... | Your syntax is wrong. You can't use , to chain arguments to cout like that. Instead do:
cout << address << " " << street << endl;
cout << city << " " << province << " " << country;
|
62,204,779 | 62,204,861 | Namespace alias inside a namespace | I have a following structure of namespaces
namespace a::b::c
{
class xyz{
};
using x=xyz
}
If I want to refer to x in an outside file, How should I address it? is it like a::b::c::x or just x?
To be able to refer to it as x outside my code, how can I change the above code? Can I write using x=a::b::xyz in... | The name x is introduced in the namespace a::b::c
namespace a::b::c
{
class xyz{
};
using x=xyz
}
So in the global namespace to refer to the name x you have to write
a::b::c::x
You could introduce the alias in the global namespace like
using x = a::b::c::xyz;
Alternatively you could use a using declarati... |
62,205,423 | 62,211,459 | How to execute multiple QProcess in Qt5 | I have been struggling on how to execute multiple processes using QProcess. I was able to execute a single process, e.i. opening a terminal window QProcess *openTerminal = new QProcess(this);, after that I wanted to execute additional processes but I could not find a way to do that. The order of operations I am trying ... | Each QProcess represents a new session, so you cannot use multiple QProcess objects to execute a sequence. The best way would be to create a shell script that does what you want it to, then use one QProcess instance to execute that script.
|
62,205,803 | 62,206,581 | function to simplify read from a file | I want to write a function to simplify the file_in.get process, so that I don't need to repeat the same lines when reading from a file. But I am having trouble implementing the it. The only libraries I can use are <iostream> <fstream> <cstring> and <cctype> The function I imagine will be something like:
void Link_Info... | Looks like you're really close. Here's a few things I'd do differently:
// Define an exception to throw when the file cannot be read.
// If the file can't be read, you might as well pass the buck up the call
// stack until it reaches a point that's capable of deciding what to do.
// This is a perfect time to use an ex... |
62,206,131 | 62,207,299 | Convert compile-time constant vector to heap-allocated version | I made Visual Studio's Code Analyzer mad. This line:
void Foo() {
const std::vector<uint8_t> bar{ /* 21,140 uint8_t entries */ };
//...
}
emits a C6262 warning:
Function uses 21140 bytes of stack: exceeds /analyze:stacksize`16384`. Consider moving some data to heap
The vector contains the individual bytes of ... | The stack space for a vector does not depend on its size.
The vector is being initialized with a std::initializer_list. That is what requires potential stack space. That is what you could make static.
|
62,206,390 | 62,206,444 | Defining destructor in derived class requires copy assignment operator | Take a look at this code example:
class A {
A(const A&) = delete;
A &operator=(const A&) = delete;
protected:
A() { }
virtual ~A() { } // required for inheritance
A(A&&) = default;
A &operator=(A&&) = default;
};
struct B : public A {
~B() { } // Without the destructor the code compiles... | When you do
~B() { }
in B you stop the compiler from generating a move constructor, so all it has is a copy constructor. Since A's is not acceptable it can't compile.
When you remove it, the compiler can create the move constructor automatically and you're good to go.
Note that this only applies to pre C++17. With... |
62,207,300 | 62,207,319 | Why is it a problem to get the return of unique_ptr before assigning to a member variable? | Why are the results different and the problem occurs in the second method?
1) No error.
auto person = getPerson(); // return type : std::unique_ptr<Person>
static_cast<Student*>(person.get())->foo(); // Student inherits Person
2) Segmentation fault before entering the function foo()
auto person = getPerson().get();
st... | I suppose getPerson() returns by-value, then what it returns is a temporary, which will be destroyed after the full expression immediately. Then the raw pointer person got from the temporary has been destroyed too (by the temporary std::unique_ptr<Person> who owns it), any dereference on it later leads to UB.
In the 1s... |
62,207,838 | 62,208,329 | C++ Divide and conquer algorithm problems | I have just learnt about Divide and Conquer algorithm and I'm a little bit confused about it. The question is my homework, I have tried many ways to fix my code but it did not run.
#include <iostream>
using namespace std;
void inputArray(int* a, int& n)
{
cout << "Input n:";
cin >> n;
for (int i = 0; i < n... | Try to test your programs without user input first:
#include <iostream>
using namespace std;
int sumeven(int* a, int l, int r)
{
if (r >= 6) return 0;
if (l > r ) return 0;
if (l >= r)
{
if (a[l] % 2 == 0)
{
return a[l];
}
else
{
return 0;
... |
62,208,923 | 62,209,106 | About the choice of the declations of `std::vector::push_back` | There two declarations for std::vector::push_back.I understand rvalue and lvalue to some degree. As far as i know, almost all types(T&、T&&、T) could be converted to const T&, so which one does the compiler choose when different types of object passed to std::vector::push?
I am a novice in C++.Though i thought over and o... | Lvalues cannot be bind to rvalue referneces, which implies, that when you invoke std::vector<T>::push_back with an lvalue argument, the only viable overload is that with const T& parameter.
Rvalues can be bind to both rvalue references and const lvalue references. Therefore, both overloads are applicable. But according... |
62,209,351 | 62,209,427 | Does C++ R-Value has a size? | Let's assume the largest number an int variable can hold is 10. Consider the following situation:
main()
{
int r1 = 10;
int r2 = 1;
int x = r1 + r2;
}
According to my current little knowledge, r1 + r2 expression creates a temporary variable to hold the result before copying that value to x.
What i want to know is sin... | Signed integers
Computing a value larger than the maximum value or smaller than the minimum value of an signed integer type is called "overflow" and is Undefined Behavior.
E.g.:
int a = std::numeric_limits<int>::max();
int b = 1;
a + b;
The above program has Undefined Behavior because the type of a + b is int and the ... |
62,209,371 | 62,209,796 | Why can't I use vector with mpz_t in GMP? | I don't know why this program goes wrong, because it is simple; however, if I can't use vector in GMP, the task will be so hard.
This is my code:
vector<mpz_t> elements;
cout << elements.size() << endl;
mpz_t a;
mpz_init(a);
elements.push_back(a);
This works well, but it is not as useful as vector:
// mpz_t b[... | mpz_t is a typedef to an array type. Instead of a vector of mpz_t, in C++ I would advise to either encapsulate mpz_t in your own class (that will also allow to manage memory) or use a vector of pointers to mpz_t.
As for the first option, it already exists in the name of mpz_class.
why i can't use vector with mpz_t in ... |
62,209,595 | 62,209,666 | Same hierarchy, different behaviour when accessing protected member of base class | I came across this code in a past exam:
#include <iostream>
class cls1
{
protected:
int x;
public:
cls1()
{
x = 13;
}
};
class cls2 : public cls1
{
int y;
public:
cls2()
{
y = 15;
}
int f(cls2 ob)
{
return (ob.x + ob.y);
}
};
int main()
{
cls2 ob... | The difference is, in the 1st case the protected member is accessed through the derived class. In the 2nd case the protected member is accessed through the base class, which is not allowed.
For protected members,
(emphasis mine)
A protected member of a class is only accessible
2) to the members and friends (until C++1... |
62,210,177 | 62,220,382 | How to change %(DisableSpecificWarnings) in Visual Studio 2019 | After upgrading to VS 2019 I'm trying to make the C++ warnings useful again by disabling some that I don't care about, for example C26812
I know I could go to every project's property page and add this string to "Disable Specific Warnings" but that would be too much duplication (I've got a lot of projects). So instead ... | Project defaults come from several .props files, organized by scope, language and platform. The location (and even presence) of those .props files has changed between versions, and can depend on the history of past versions installed prior to VS 2019.
One (safer) way to identify the default .props being actually used i... |
62,210,413 | 62,211,274 | How can I specify C++ standard version in DPC++ compiler options? | I stumbled upon free stuff in the form of Intel oneAPI toolkit and everything works great, the samples compile fine but I don't know how to specify the C++ standard in the compiler options. From what I understand DPC++ is built on top of Clang so I should be able to choose which C++ version it compiles for but I don't ... | This is an ongoing issue, there are reports of other users with the same issue. As far as I know it hasn't been solved yet, what you can do meanwhile is to run the program from the command line:
Go to the folder where you installed OneApi, let's say C:\Program Files (x86)\inteloneapi\ and run setvars.bat to set enviro... |
62,210,534 | 62,210,631 | how to overload << operator in c++ to use repeatedly? | Sorry for the not clear title.
Recently I started to learn C++ and I don't know how to overload operator << to make it repeatable.
Here's an example code.
class Foo{
private:
int* a;
int idx = 0;
public:
Foo(){a = new int[100];
void operator<< (int a) {arr[idx++] = a;}
What << does is basically class get integer numb... | The overloaded Foo::operator<<() takes actually two arguments:
The parameter int given as right-hand side
The implicit this from left-hand side.
To allow chaining of this operator, it should return a reference to the left-hand-side (i.e. *this) to become usable at left-hand-side itself.
Sample code:
#include <iostrea... |
62,210,558 | 62,254,606 | Debug a C++ DLL used in ASP MVC application | I have a C++ DLL in bin folder of my ASP MVC5 web application project. (I have copied and pasted it from the original C++ project as I was unable to add a reference) I am able to call some of the functions of the DLL(used DLLImport). I have a problem in one of the functions. This can only be solved when I will be able ... |
Debug a C++ DLL used in ASP MVC application
1) First, make sure that make sure that the DLL you are referring to has a PDB file or other output file in its folder.
You should open the c++ project in VS IDE and then make sure that you built it with Debug and x64 mode. If so, build it again.
Then in c# web project, use... |
62,210,960 | 62,213,122 | A C++ program to output all the numbers in a .txt file with a specific number of digits when the number of digits is entered | Using this code I can extract all the numbers of a text file to another text file. But what I want to achieve is that I want to input the number of digits of the numbers that i want to extract and then only extract those numbers containing the no. of digits I inputted.
Thank you in advance.
#include <iostream>
#include... | Considering your code, I suggest your to take a good book about programming 'good practices' and go step by step.
Here is a code that makes what you ask:
#include <iostream>
#include <sstream>
#include <cctype>
int main()
{
using std::string;
using std::stringstream;
string input="1 123 . 12 12 12345 ... |
62,211,011 | 62,416,296 | Does BOOST_DATA_TEST_CASE always require printability of the samples? | I'm trying to get some data-driven test cases running with BOOST_DATA_TEST_CASE and figured out the basics o far.
However, I noticed that the type that is used as sample input MUST be printable:
This will work:
std::vector<std::string> printable_cases = { "case1", "case2" };
BOOST_DATA_TEST_CASE(test_mvex, utdata::make... | Indeed the current implementation of BOOST_DATA_TEST_CASE requires the parameters to be printable: before the test starts, a BOOST_TEST_CONTEXT is created in the fixture with the current test parameters, such that the Boost.Test framework can log/print messages for that specific set of parameters (in particular to prin... |
62,211,078 | 62,212,044 | C++11 variadic templates calling a function inside a class | I'm learning variadic templates in C++11. How can I call test.finder as a functional argument of test.var_finder?
#include <functional>
#include <iostream>
class c_test {
public:
double finder(double a, double b = 0) {
return a + b;
};
template<typename... Args>
doubl... | I guess you're a bit mixing the variadic template part with a bit of design-flaw
Let's start.
Preamble: the correct way to deal with variadic templates is to use rvalue-reference and std::forward to achieve perfect forwarding.
1) The easy way: you don't need class at all
you're actually not referring to any member so a... |
62,211,103 | 62,211,172 | opengl not filling in polygon | I'm trying to draw a filled in circle, but when I draw this, it only shows in wireframe, here is the code I'm using to draw:
void render_circle(Vec2 position, float radius, Vec4 colour) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor4f(colour.x, colour.y, colour.z, colour.w);
glBegin(GL_LINE_LOOP);
... | GL_LINE_LOOP is a line primitive type. If you want to draw a filled polygon, then you have to use a polygon primitive type. For instance GL_TRINAGLE_FAN.
It is only possible to correctly draw convex geometry. Concave polygons may not be represented correctly, by a primitive. A possibility to deal with this, is to split... |
62,211,126 | 62,213,356 | why GRPC AsyncClient throws Segfault when waiting for the Next result in the completion queue | I am using version 1.23.1 of the GRPC library.
I have an asynchronous RPC c++ Client class, which initiates each RPC with the following method:
void Client::SendTaskAsync(const Task& task) {
unique_lock<mutex> lock(mtx_);
cout << "Sending task with id " << task.id() << endl;
ClientContext context;
S... | The code in the question is written according to this tutorial, which sends only one request and waits for a reply in the same thread.
If you want to use multiple threads, follow the client example here.
|
62,211,245 | 62,211,735 | Trouble understanding this CMakeLists.txt file | I'm absolutely new to C++/CMake and from all the tutorials I've read, there should be an add_executable() line in the top-level CMakeLists.txt file. However, in this project that I'm working on, there isn't one:
cmake_minimum_required (VERSION 2.8.11)
set(CMAKE_CXX_STANDARD 17)
set(VERSION dev)
find_package(PkgConfig ... |
there should be an add_executable() line in the top-level CMakeLists.txt file
This is a wrong assumption.
add_executable is not mandatory at all.
For example, a project that produces only library will have add_library and no add_executable.
Moreover this function could be in a subdirectory, there is no need to put it... |
62,211,339 | 62,211,480 | reference_wrapper cause "incomplete type is not allowed" | #include <vector>
#include <array>
int main() {
typedef std::array<int,2> point;
typedef std::vector<std::reference_wrapper<point>> route;
std::vector<std::vector<point>> lattice = {
{point{ {0,0} },point{ {0,1} }},
{point{ {1,0} },point{ {1,1} }}
};
route r = {&lattice[0][0],&lat... | You must #include <functional> before using std::reference_wrapper.
|
62,211,447 | 62,346,855 | Could type traits be restricted to not accept other type traits as arguments? | Question may be weird so here is a brief motivational example:
#include <vector>
#include <type_traits>
template <typename T>
// workaround for gcc 8.3 where volatile int is not trivially copyable
using is_tc = std::is_trivially_copyable<std::remove_cv<T>>;
// static assert passes compile, oops
static_assert(is_tc<std:... | Concept: Is a TransformationTrait declared in the std namespace
I wonder if is there a way C++ type traits could restrict their input types so that they do not accept other type_traits
Since metafunction traits are actually types themselves (which is kind of also the root of your problem), we can leverage this and c... |
62,211,590 | 62,212,399 | accessing private members without using friend class | I have a homework in which:
we have this code:
#include <iostream>
using namespace std;
class Test {
int x;
char y;
public:
Test() :x(0), y(0) { ; }
};
int main() {
Test t;
//Do stuff!
return 0;
}
and without adding getters and setters or using friend class we have to read x and y and also chan... |
(with pointers) why this happen?
I don't understand this one, so I will skip it.
is such thing possible in other object oriented languages?
Consider python. In python making something private is explicitly only an agreement between the author and the user, but nothing prevents a user from accessing private memb... |
62,211,848 | 62,212,509 | Constexpr Variadic Template to reorder unsigned integers | I'm working with a peripheral which sends lowest 8 bit word first. So the first word (in this case 16bit are send) has to be on the right hand side. As seen in variable v1.
I would like to have a more expressive version of this so I wanted to add a constexpr function that shifts the first parameter on the right most po... | #include <cstddef>
#include <utility>
template <std::size_t... Is, typename... Ws>
constexpr auto lower_word_first(std::index_sequence<Is...>, Ws... ws)
{
return ((ws << Is*8) | ...);
}
template <typename... Ws>
constexpr auto lower_word_first(Ws... ws)
{
return lower_word_first(std::index_sequence_for<Ws...>... |
62,211,937 | 62,212,012 | c++ implicitly convert function arguments via custom assignment operator | I'm working on a project with is part C written and partly C++ written.
I got 2 Enums which basically represent the same, however one is wrapped inside a class and the other one is located at a global namespace due to C compatibility.
//C Code File
typedef enum
{
C_Enum_first = 0,
C_Enum_Second,
} C_Enum_T
//(obvi... |
Do assignment operator not work implicitly on function arguments?
Your operator= is a member of CMyClass. It can be called like this:
CMyClass cmc;
C_Enum_t a;
CPP_Enum& x = (cmc = a);
But it will not be considered for implicit conversion from CMyClass to CPP_Enum. Consider to use a free function for the conversion ... |
62,212,261 | 62,212,659 | Sequence containers - can elements be accessed sequentially only | It is stated everywhere that the common property of all sequential containers is that the elements can be accessed sequentially. But we know that std::array, std::vector and std::deque all support fast random access to the elements. std::list supports bidirectional iteration, whereas std::forward_list supports only uni... | Sequential access has little to do with random access or iterators.
For example, std::set's iterator is a bidirectional iterator. You can iterate over elements of a std::set just like you would over elements of a std::vector.
Sequence containers have a front and a back, and all their elements are between those, in the ... |
62,212,265 | 62,213,034 | Circular dependency in C++ template methods | I've got a problem with a circular dependecy in C++ template methods. I realize there are several similar threads here but they didn't help me with my specific case. This here is a nonsensical example, but it illustrates the issue:
main.cpp
#include "A.h"
int main()
{
float f = 10;
A a;
a.foo( f );
}
A.h
#... | The problem here is that getName() in a->getName() is a non-dependent name (it does not depend on the template parameter T), and it is resolved at the point of template definition. But A is incomplete at that point.
As a simple but ugly workaround, we can introduce a fake dependency on T:
template<class T, class S>
str... |
62,212,593 | 62,213,067 | clearing an object of type 'struct ' with no trivial copy-assignment; use assignment or value-initialization instead | I am working on a module containing C and C++ codes. The problem is that I am getting the following forbidden warning. I provided the code that Is causing that warning.
warning: 'void* memset(void*, int, size_t)' clearing an object of type 'struct OtherStructure_s ' with no trivial copy-assignment; use assignment or va... | OtherStructure_s doesn't have a trivial copy assignment operator. You can't use memset. Probably the class allocates some other resources like heap memory.
You don't need TEST::TEST():_otherStructure(){}. The default constructor of TEST will default construct _otherStructure. The best solution is to remove the construc... |
62,213,115 | 62,214,463 | How to allocate memory in a DriverKit system extension and map it to another process? | I have allocated memory in my application and passed its pointer and size to IOConnectCallStructMethod. Using IOMemoryDescriptor::CreateMapping I have then mapped this memory to the DriverKit system extension process, and it is possible to write to this mapped memory location and read the data from my application.
I w... | This is what IOUserClient::CopyClientMemoryForType in DriverKit is for, which gets invoked when your user process calls IOConnectMapMemory64 from IOKit.framework. The kext equivalent, incidentally, is IOUserClient::clientMemoryForType and essentially works exactly the same.
To make it work, you need to override the Cop... |
62,213,496 | 62,232,340 | How to workaround "error C2712: Cannot use __try in functions that require object unwinding" in a foreign thread? | I am using a library (oatpp web service framework) that launches threads that call my handlers. So I have no control over the outermost code of the threads to insert __try...__except there (I need it for core dumps).
The handler implementations look like the following:
shared_ptr<oatpp::web::server::HttpRequestHandler:... | Instead of observing SEH exceptions in situ it's more conventional to set up an unhandled exception filter. The system provides the SetUnhandledExceptionFilter API to register a callback for a thread in case an SEH exception goes unhandled (C++ exceptions are built on top of SEH exceptions, too, so this callback also g... |
62,213,839 | 62,214,072 | Boost bind and 'result_type': is not a member, c++03-friendly | The latest 16.6 update to Visual Studio 2019 removed std::plus::result_type, std::minus::result_type, and related typedefs. (They're deprecated in C++17 and removed in C++20.) A greatly simplified version of the code looks like this:
template <typename FF>
struct function_wrapper {
function_wrapper(FF func, const s... | Wrap old functors with:
template <typename F>
struct functor;
template <template <typename> class F, typename T>
struct functor<F<T> > : F<T>
{
typedef T result_type;
typedef T first_argument_type;
typedef T second_argument_type;
};
Then:
function_wrapper<boost::function<int(int, int)> >
plus_func(fu... |
62,213,911 | 62,215,673 | OpenGL Fragment Shader not compiling on Intel HD 4000 graphics | This shader seems to compile fine on my Vega 8 iGPU on my ryzen 3 2200g but the same fragment shader does not compile on intel hd 4000 graphics. Is there really a shader error or something I am doing wrong? I also took steps to not refer to a uniform using an int. Please help.
#version 330 core
in vec2 TexCoord;
// I ... | Intel HD 4000 graphics only supports upto 16 texture slots or units. You are taking in a sampler2D array of size 32. Which is more than 16. It will work if you change the array size to 16 and comment out the extra cases. Here is the updated shader code :
#version 330 core
in vec2 TexCoord;
// I am using a batch rende... |
62,214,089 | 62,214,141 | Why is assignment of 0 or nullptr to std::string allowed, even when it results in a straight forward runtime exception? | std::string s = 0; // = nullptr ---> throws `std::logic_error`
Above statement results in segmentation fault. Why is it allowed?
[At least the constructor overload of nullptr should have been =delete, isn't it?]
| In that case, the constructor to a const char* is called due to the way overload resolution works.
And if that pointer is nullptr then the standard library attempts to dereference a null pointer value with undefined results.
std::string is already hideously bloated. My guess is that nobody has managed to convince the C... |
62,214,229 | 62,214,388 | C++ problem with properly writing and printing precision (cout) in complex numbers? | I have a problem. I try to print properly by using setprecision, but still, my result is wrong.
This is my input
data.txt
(1.1,2) (1.7,3.14)
This is my output result.txt
1.1, 2,
0.7, 3.1,
This is output, which I expect
1.10, 2.00
1.70, 3.14
This is my code
#include <iostream>
#include <fstream>
#include <cs... | setprecision by default affects the number of significant digits printed, not the number of decimal places printed. To make it do that you have to switch to fixed output mode. Also you need to set the precision before you output the numbers not afterwards.
return os << fixed << setprecision(2) << c.real << ", " << c... |
62,214,517 | 62,214,759 | Function overloading and inheritance in C++ | Suppose I have classes Bulldog and Labrador which publicly derive from base class Dog, and I have a function, e.g. a method of a different class, called reward, and I want it to produce different results for objects of class Dog and Bulldog, or for objects of class Bulldog and Labrador. What is the best way of doing th... | The straightforward approach would be to delegate, using polymorphism, from the reward(const Dog& dog) function (free function/other class) to a virtual function of the Dog interface, using a provided Dog reference that can dispatch virtual Dog methods polymorpically. E.g.:
#include <iostream>
struct Dog {
Dog() {... |
62,214,635 | 62,214,968 | Is the return expression treated as a temporary object in c++? | class elem
{
public:
elem()
{
}
elem(elem &)
{
cout << 222222 << endl;
}
elem(elem &&)
{
cout << 111111 << endl;
}
};
elem fun()
{
elem e;
elem f(e);
return e;
}
void main()
{
fun();
}
Output:
22222
11111
My confusion:
As I return an lvalue in fun, wh... | If you declare a local variable within a function and return it out of the function, it is an rvalue. Also there is a binding rule which says... “The r-value reference in move constructor is preferred over const l-value reference in copy constructor — these are the rules for binding expression values to references. If ... |
62,214,908 | 62,217,064 | 2D arrays with variable sizes as arguments C++ | I was going to create a function Swap() that swaps the two maximum elements of the n times m matrix A and matrix B.
But I'm having error: declaration of 'A' as multidimensional array must have bounds for all dimensions except the first
void Swap(int A[][], int B[][], int n, int m)
{
int max_A = A[0][0];
int ma... | Following you request here is a posssible implementation of your code using vector of vectors, aka 2D vector, with comments:
Live demo
#include <iostream>
#include <vector>
#include <exception>
//pass vectors by reference so the changes are reflected in the passed arguments
void Swap(std::vector<std::vector<int>>& A, ... |
62,215,204 | 62,215,660 | Class that provides thread-safe access to data of different types (Proposal, Code review) | Still on a beginner level, I am currently writing a multithreaded application for raspi 4 in C++ that performs a bunch of operations on frames coming from a time-of-flight depth camera.
Situation
My threads, as well as callbacks from the depth-camera-library, produce various kinds of data (ranging from bools to more c... | No this isn't thread safe. Consider:
ProtData::Data& data_ref = pd->getAccess().data;
Now I have a reference to the data and the mutex that was locked when creating a ProtectingWrapper is already unlocked, because the temporary wrapper is gone. Even a const reference would not fix that because then I could read from t... |
62,215,349 | 62,215,888 | Can anyone figure out how this code showing running error? It is printing infinite time -1 along with correct answer | #include <iostream>
using namespace std;
int subarraysum(int arr[],int n,int sum){
int cur_sum=0,start=0;
for(int i=0;i<n;i++){
cur_sum=cur_sum+arr[i];
while(start<i && cur_sum>sum){
cur_sum=cur_sum-arr[start];
start++;
}
if(cur_sum==sum)
{
cout<<start<<" ... | I think the problem here is indeed tricky. You declare a function int subarraysum(int arr[],int n,int sum). The problem here is the return statement. Your function must return a value, but your code does not, in this form. This leads to undefined behavior. The int main()-function in C++ is the only function in C++, whi... |
62,215,362 | 62,217,294 | How to calculate complexity if a code contains multiple n complexity loops? | I am a bit confused on the topic of calculating complexity.
I know about Big O and also how to calculate the complexity of loops (nested also).
Suppose I have a program with 3 loops running from 1 to n
for (int i=0;i<n;i++)
{
cout << i ;
}
Now if I ran my CPP code having 3 for loops, will it take 3*n time?
Will... |
How to calculate complexity if a code contains multiple n complexity loops?
To understand Big-O notation and asymptotic complexity, it can be useful to resort at least to semi-formal notation.
Consider the problem of finding and upper bound on the asymptotic time complexity a function f(n) based on the growth of n.
T... |
62,215,840 | 62,217,550 | Threads slowing eachother down | I have some expensive computation I want to divide and distribute over a set of threads.
I dumbed down my code to a minimal example where this is still happening.
In short:
I have N tasks that I want to divide into "Threads" threads.
Each task is the following simple function of running a bunch of simple mathematical ... | clock() returns approximate CPU time for the entire process.
The outermost loop does a fixed amount of work per iteration
int i = 0;
while (i++ < 100000)
{
for (int y = 0; y < 1000; y++)
{
sqrt(y);
}
}
Therefore, process CPU time reported around this loop will be pro... |
62,216,484 | 62,217,529 | Combining function parameter pack and default arguments | I have a function with a parameter pack:
template<typename... Targs>
void tprintf(const char* format, Targs... args) {}
(the implementation shouldn't matter, just the signature). I want to add source position as default argument, using the GCC/Clang builtins. Something like
template<typename... Targs>
void tprintf(con... | The solution would be to us C++20's std::source_location:
#include <iostream>
#include <source_location>
template<typename... Targs, auto location = source_location::current()>
auto tprintf(char const* format, Targs const&... args) -> void {
std::cout
<< std::format("{}:{}: ", location.file_name(), locatio... |
62,216,880 | 62,218,400 | How to pass packed structs as messages in boost::asio? (without serialization) | I am boost::asio, the messages and responses are all in the form of packed structs, and as the structs are packed I don't see a use of serialization here. I have seen similar questions and all advice serialization, but that is not what I am looking for. How can we pass and receive a objects of these structs over a tcp ... | If you mean that the "packed struct" is actually POD (so standard-layour and trivially constructible/destructible), in short bitwise serializable, then you could say that your struct is a buffer.
Indeed, you may decide that you don't need to copy into another buffer/representation and use the buffer. That's simple, jus... |
62,217,250 | 62,218,552 | C++ openCV mat initialization | I am completely new to OpenCV and I'm trying to initialize two cv::Mat matrices from two different type of data. One is simple one-channel array of uint16_t gray values, second should hold RGB values from array of uint8_t values holding RGB 565 (each pixel occupy 2 uint8_t, so it's basically array of uint16_t). I'd lik... | use cv::cvtColor to convert the mat M2 from RGB565 to RGB format.
...
cv::Mat M2 = cv::Mat(rgbHeight, rgbWidth, CV_16UC1, rgb);
// M2.depth() = 2 # CV_16U
// M2.channels() = 1 # single channel with each element having 16 bit
//convert mat format from bgr565 to rgb
cv::Mat M2_rgb;
cv::cvtColor(M2, M2_rgb, COLOR_B... |
62,217,395 | 62,217,717 | std::transform to copy one array of struct to another | I have below structures.
typedef struct
{
uint32_t aa;
float32_t bb;
float32_t cc;
float32_t dd;
float32_t ee;
}struct_1;
typedef struct
{
uint32_t hh;
float32_t bb;
float32_t cc;
float32_t ii;
float32_t jj;
}struct_2;
I have ... | You can use std::transform and supply a conversion function:
std::transform(std::begin(array2), std::end(array2), array1, [](const struct_2& val) {
return struct_1{val.hh, val.bb, val.cc, val.ii, val.jj};
});
|
62,217,470 | 62,217,830 | Merge Sort: Segmentation error Core Dumped | I read the theory of merge sort algorithm and based on that i wrote an implementation of merge sort in C++ using the STL Vector class.
I know that a copy paste from any one of the trillion articles on internet about merge sort can solve this, but I wanted to try this one on my own.
When I run the code i get segmentatio... | So your recursion is wrong. In main you have a vector of nine elements.
std::vector<int> arr({2,4,1,5,3,6,2,4,3});
and you call mergeSort like this
mergeSort(arr,0,8);
So the third parameter to mergeSort is the last valid index of the vector you are sorting (it would have been better to use arr.size() - 1). Put anoth... |
62,217,764 | 62,218,080 | Add whitespace to string at specific places | I have a string "00000000000000000000010011010010". I want to add a whitespace after every eighth char to make it represent a 32 bit integer. For example: "00000000 00000000 00000100 11010010". What would be the simplest way to do this?
| With the range-v3 library, the code is quite simple to understand:
using namespace ranges;
auto res = s | views::chunk(8) | views::join(' ') | to<std::string>;
Here's a demo.
|
62,217,867 | 62,218,122 | Deep Copy Pointer and Delete the Memory | I'm trying to create Copy Constructor.
For example, There is a class like :
#include <string>
#include <vector>
using namespace std;
class Test
{
vector<string*> name;
public:
~Test();
Test(const string& name);
Test(const Test& t);
};
Test::Test(const Test& t)
{
for (auto it = t.name.begin(); it !=... | In order to make a deep copy, you need to copy what any pointer points to.
Like this:
name.push_back(new string(**it));
You also need to implement the copy assignment operator.
|
62,218,268 | 62,218,575 | I want to memcpy directly into a struct, but none of the methods are avoiding the padding issue correctly | I'm trying to open a binary file and read the Header from it. I'm able to read it in a series of integers, but I decided to convert it into a struct to allow for n-number of objects. However, I'm facing different issues each time, and they're all about the padding that structs introduce.
When I tried
struct {
int x1;
i... | The layout of structs is always compiler-dependent, and there isn't any universal way to force a particular layout. Most compilers do have some sort of pack directive, whether via #pragma or __attribute__ or something else, but there is no single way that will work for all compilers.
If you want a more compiler-indepe... |
62,218,272 | 62,229,680 | How to define a function returning a cpp-defined type in Cython? | Overview of the problem
I'll be as brief as possible.
Suppose I have a class Bar, defined in ./cpp/Bar.h and implemented in ./cpp/Bar.cpp.
Then, I have another class, Foo, defined in ./cpp/Foo.h and implemented in ./cpp/Foo.cpp.
One of the methods in Foo returns a pointer to Bar, that is:
Bar* fubar()
{
Bar... | I think your issue is not the C++ headers, but Cython knowing of the existence of the types. You do this through cimporting pxd files.
Foo.pxd becomes:
cimport Bar
cdef extern from "./cpp/Foo.h" namespace "Baz":
cdef cppclass Foo:
Foo() except +
Bar.Bar fubar()
Note that I've also removed the text... |
62,218,555 | 62,832,603 | WebRTC std::deque iterator exception when RTC_DCHECK_IS_ON | Recently, since M83 and M84 releases of lib-WebRTC, I face a strange error when I run my host program in Windows x64 Debug configuration (RTC_DCHECK_IS_ON) on Visual Studio :
When a video channel is creating in WebRTC library I get an exception on
_Deque_const_iterator& operator++() {
#if _ITERATOR_DEBUG_LEVEL ... | The problem is from the function RegisterSendAndCheckForCycles of rtc_base/thread.cc file
for (auto it = all_targets.begin(); it != all_targets.end(); ++it) {
const auto& targets = send_graph_[*it];
all_targets.insert(all_targets.end(), targets.begin(), targets.end());
}
When all_targets.insert is called, the ... |
62,218,661 | 62,219,188 | How make qDebug to write method and class name? | I want to make the qDebug or qWarning method to write the class and method name that calling them.Now I writing like below but It is hard work for all class and method in my application.Does Any one know How can I do this?
void File::downloadingFinishd()
{
qWarning()<<"File::downloadingFinishd()";//How write this ?... | Q_FUNC_INFO is the Qt version of std pretty function.
From Qt Doc:
const char* Q_FUNC_INFO
Expands to a string that describe the function the macro resides in.
How this string looks more specifically is compiler dependent. With
GNU GCC it is typically the function signature, while with other
compilers it might ... |
62,218,832 | 62,218,989 | How to use span to wrap up command line args | Is this use of the upcoming C++20 std::span correct and with no overhead to wrap up the command line arguments?
#include <iostream>
#include <span>
int main(int argc, const char* argv[])
{
for (auto s : std::span { argv, static_cast<std::size_t>(argc) })
std::cout << s << std::endl;
}
If it is correct, coul... | If you use () instead of {} you don't need the really verbose cast:
std::span(argv, argc)
This gives you a range of char const*. You can convert those to string_view using transform. This has some overhead because you need to do a bunch of strlens:
std::span(argv, argc)
| std::views::transform([](char const* v){ r... |
62,218,876 | 62,218,924 | I am trying to do binary overloading for operator '+' but the output is wrong and I can't understand why? | I created a class named test having 2 integers. I am trying to overload operator+ for it. But the output is wrong and I can't understand why.
#include <conio.h>
#include <iostream>
using namespace std;
class test
{
int a, b;
public:
test()
{
a = 0;
b = 0;
}
test(int x, int y)
{... | You have undefined behavior because your operator+ is not returning temp. You need to do:
test test::operator+(test t)
{
test temp;
temp.a = a + t.a;
temp.b = b + t.b;
return temp; // <- return here
}
Enable all your warnings with something like -Wall, and the compiler will tell you about mistakes li... |
62,218,947 | 62,220,199 | Ran into a "'cl.exe' is not recognized" and "c1xx: fatal error C1083: Cannot open source file: No such file or directory" error | I encountered both of these errors when going through the Configure VS Code for Microsoft C++ article, here.
I had VS Code, got the C++ extension, used Developer Command Prompt(Run as Admin), made the right directories and projects using these commands:
mkdir projects
cd projects
mkdir helloworld
cd helloworld
cod... | You made your projects folder inside c:\Windows\System32\
This folder is accessible only with admin rights.
I am guessing that VS Code run build task without admin rights which causes the problem.
Try creating your projects folder in User folder.
|
62,219,000 | 62,219,081 | C++ Remove vector items that exist in another vector WHILE retaining order | std::vector<int> items = {1, 2, 3, 4, 5};
std::vector<int> removeItems = {2, 4};
I need to delete the values in items that are in removeItems, while retaining the order of items. Something like this:
items.remove(removeItems);
Output
items = {1, 3, 5}
Are there any built in vector methods that can achieve this? I ha... | The most efficient general form is to turn removeItems into an unordered set, and then remove elements from items by checking for membership.
std::unordered_set<int> removeSet(removeItems.begin(), removeItems.end());
items.erase(std::remove_if(items.begin(), items.end(), [&](int x) {
return removeSet.count(x) != 0;... |
62,219,103 | 62,219,235 | Class type for stack allocation. Why the address for both ID instances are the same? | class ID
{
public:
ID(const std::string& name) :
name_(name) {}
// explicit copy constructor as my first solution but gave me same address
ID(const ID& other)
{ name_ = other.getName(); }
std::string getName() const
{ return name_; }
private:
std::string name_;
};
ID createID(co... | In this function:
ID createID(const std::string& name)
{
ID id(name); // new stack allocation for id
std::cout << "ID addr: " << &id << "\n";
return id;
}
for the call:
ID my_id = createID("John"); // new stack allocation for my_id
it appears the compiler is doing NRVO (named return value optimization). S... |
62,219,125 | 62,219,674 | C++ best way to copy all elements from vector into map / unordered_map | Using C++, if I want to convert a vector into set or unordered_set container, it can be easily done by:
#include <iostream>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
int main() {
vector<int> vec {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
// pas... | Let's look at your set construction.
vector<int> vec {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
set<int> s(vec.begin(), vec.end());
This succeeds because the value_type of your set is int. That's not just convenient terminology. A std::set defines a member type called value_type, and I am saying that std::set<int>::value_type... |
62,220,075 | 62,220,597 | Appending map that uses Struct as a "multikey" and std::vector as mapped value | in code below it appends myList only for the first call of appendMyList(), and size stays 1, so can someone explain what is wrong here:
struct MyKey {
int accValue;
std::string name;
};
inline bool operator<(MyKey a, MyKey b){
return a.accValue < b.accValue && a.name < b.name;
}
inline bool operator==(MyKey a, ... | std::map does not allow for storing duplicates. However, it doesn't use operator== for checking equality of elements. It uses operator< for both -- ordering elements as well as checking equivalence.
That is, if !(a < b) && !(b < a) then std::map considers a and b equivalent, hence no more elements than one are inserted... |
62,220,228 | 62,220,258 | Why does switching the order of the if else statement result in an error? | Here is my code:
/*
Given a positive integer denoting n, do the following:
- If 1 <= n <= 9, then print the lowercase English word corresponding to
the number (e.g., one for 1, two for 2, etc.)
- If n > 9, print 'Greater than 9'.
*/
#include <iostream>
#include <array>
using namespace std... | This expression:
if(1 <= n <= 9)
is not checking if n is between 1 and 9. Instead the check actually becomes:
if( (1 <= n) <= 9)
which will be either 0 <= 9, or 1 <= 9, both of which are true.
You need to do:
if(1 <= n && n <= 9)
|
62,220,253 | 62,220,580 | Copy part of a matrix and paste on another one C++ | The user input a matrix, and the output must be a new matrix with an additional column of zeros. If we apply the script to a 2 square matrix like : {1,2,3,4} the new matrix output will be a 2 rows & 3 columns : {1,2,32,3,4,0}. I don't understand the number 32 output.
#include <iostream>
int main(){
int m,n;
... | Variable length arrays (VLAs) are a non-portable gcc extension and evidently don't initialise as you would expect.
One solution is to use std::vector instead which is portable and will do what you want, something like this:
#include <iostream>
#include <vector>
int main(){
int m,n;
std::cout << "Input the size... |
62,220,271 | 62,223,345 | Why is std::string::append so much faster than push_back in this benchmark? | Given the following benchmark:
const char* payload = "abcdefghijk";
const std::size_t payload_len = 11;
const std::size_t payload_count = 1000;
static void StringAppend(benchmark::State& state) {
for (auto _ : state) {
std::string created_string;
created_string.reserve(payload_len * payload_count + 1);
... | Compilers don't always succeed at optimizing a byte-at-a-time loop into something non-terrible. You're comparing a known-length append against a whole inner loop that calls push_back.
push_back includes a size check, so using it this way checks and conditionally reallocates+copies after any byte pushed, which probably ... |
62,220,588 | 62,220,690 | C++ std::cout displaying 64 | std::cout << 100 << std::endl;
I've written this code but when I go to see the result it prints 64? Anyone has any ideia why this is?
| Here you are.
#include <iostream>
#include <iomanip>
int main()
{
std::cout << 100 << std::endl;
std::cout << std::hex << 100 << std::endl;
std::cout << 100 << std::endl;
std::cout << std::dec << 100 << std::endl;
std::cout << 100 << std::endl;
return 0;
}
The program output is
100
64
64
100... |
62,220,648 | 62,220,698 | Qt5 - C++11: 'This' cannot be implicitly captured in this context | I am trying to pass the result of a qDebug() statement into a QTextEdit but without success because I am getting a compiler error of 'This' cannot be implicitly captured in this context and I have never got this error before.
Then output is coming after executing a QProcess and would like to show it on the QTextEdit I ... | Your lambda does not capture ui or this, so there's no way to call ui->textEditLidar->setText.
Change this
connect(this->executeROSLidarApp, &QProcess::errorOccurred, [script = this->executeROSLidarApp](QProcess::ProcessError error) {
qDebug() << "[EXEC] error on execution: " << error << script->errorString();
... |
62,220,663 | 62,220,807 | applying the DRY principles in makefile | Just taking a use case for this instance. I'm compiling a c++ file, and sometimes, I'd like to compile without debugging symbols i.e. the -g enabled and sometimes I would like to enable it.
So, I thought of just making two targets in which the second target would reassign a make variable(is it possible) and change ... | You can do something like this:
first@bg: gpp += -g
first@bg: first
Note that it's more idiomatic to define CXX=g++ and CXXFLAGS=-std=c++17 and then tweak CXXFLAGS, and use make DEBUG=1 for debug builds:
CXX=g++
CXXFLAGS=-std=c++17
ifeq ($(DEBUG), 1)
CXXFLAGS+=-g
endif
Then invoke the compiler as $(CXX) $(CXXFLAGS)... |
62,220,860 | 62,220,933 | How to access a pointer struct's member variables? | I haven't programmed in C++ in a while, so I've been trying to improve. I have a very simple login function, however it doesn't work. The login function calls getUserAttempts() which returns a pointer to a struct that contains user details such as username and password. However, any time I try to access the pointer's s... | In this function:
structCred *getUserAttempts() {
structCred credentialAttempt;
// ...
return &credentialAttempt;
}
you are returning an address to a local variable which dies at the end of the function. Accessing the memory is then undefined behavior.
Instead, you should allocate memory for it:
structCred... |
62,221,032 | 62,221,576 | How to determine the type of a lambda which captures a noncopyable parameter? | Given the non copyable Task class and sample code below
#include <functional>
#include <iostream>
#include <string>
class Task
{
public:
Task()
{
}
Task(const Task& other) = delete;
Task& operator=(const Task& other) = delete;
Task(Task&& other) = default;
Task& operator=(Task&& other) = ... | You can use decltype(foo) as a type when you want to refer to the type of foo. So, you could do this:
decltype(lambda) test = std::move(lambda);
However, your stated goal is to use this as a class member. In that case you need something to "steal" the type from. Note that the compiler is under no obligation (as far ... |
62,221,235 | 62,238,075 | Compiler discrepancy for out-of-line definitions of conversion operators | There appears to be some discrepancy between compilers as to whether the following code is well formed.
In particular, GCC and Clang accept this code -- whereas MSVC rejects it:
template <typename T>
class Bar{};
template <typename T>
struct Foo
{
using element_type = T;
operator Bar<element_type>();
};
temp... | The standard is very vague on the subject. In the case where you're explicitly calling a conversion function (a.operator int()), [basic.lookup.classref]/7 says
If the id-expression is a conversion-function-id, its conversion-type-id is first looked up in the class of the object expression ([class.member.lookup]) and ... |
62,221,628 | 62,221,720 | C++: printing unicode characters | I wrote a simple program to print a unicode smile emoji. Unfortunately, something else is printed. Does anyone know what the problem with this code is? Thanks
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string str = u8"\u1F600";
cout << str << endl;
re... | \u escape sequences have the format \u#### (i.e. exactly 4 hex digits). You need \U########:
auto str = u8"\U0001F600";
Or, encoding the UTF8 bytes separately:
auto str2 = u8"\xf0\x9f\x98\x80";
That works.
|
62,221,753 | 62,230,527 | Why fno-sanitize is not taken into account for a subproject CMAKE, disable sanitizer for a target | I'm working on a CMake projects with several targets.
I'm activating ADDRESS SANITIZER by CMake (ccmake . and put ADDRESS_SANITIZER=ON). It is activated correctly, although I would like to inactivate it on one of the target. To do this, I added -fno-sanitize=all to the compiler flags of the target but it is not taken ... | Instead of set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-sanitize=all I've used target_compile_options(target -fno-sanitize=all) which solved the problem.
|
62,221,993 | 62,222,025 | C++ errors with releasing Dynamic memory | Error - *** error for object 0x7ffeefbff360: pointer being freed was not allocated.
I understand its better to use vectors, but our prof wants us to use it this way.
My unwrap function is giving me errors where I want to release the memory, also when I want to print the pattern using the for loop in the display functio... |
Error - *** error for object 0x7ffeefbff360: pointer being freed was not allocated.
in wrap :
char buffer[100];
...
theGift.m_wrap[i].m_pattern = buffer;
you save in the in-out parameter theGift a pointer to the local array buffer (and you have a memory leak for the lost of the allocation done in theGift.m_wrap[i]... |
62,222,188 | 62,222,826 | Does my main window receive edit controls upon creation or when I click on the update region? | I am very new to Win32 so please be gentle as I am surely not describing my question well at all, but am extremely serious about learning more. So, I have modified my main window to include the option to edit, both write and delete, text, but in order to feel comfortable moving forward, I need to know where exactly the... | Before CreateWindow/Ex() exits, it sends a WM_CREATE message (among several other mesages) to the window that is being created. CreateWindow/Ex() does not exit until all of those messages have been processed (unless an error occurs).
So, by the time CreateWindowEx() in your main() has exited, your main window has been... |
62,222,212 | 62,223,420 | Simple example where [[likely]] and [[unlikely]] affect program assembly? | C++20 introduced the attributes [[likely]] and [[unlikely]] to the language, which can be used to allow the compiler to optimize for the case where one execution path is either much more likely or much less likely than the other ones.
Given the cost of an incorrect branch prediction, this seems like a feature that's p... | As it seems, there is a bug in gcc. If you have two functions which are the same, besides [[likely]] attributes, gcc folds them incorrectly.
But if you use just one function, and switch between [[likely]]/[[unlikely]], assembly changes.
So, this function:
void bar(int i) {
if(i) [[unlikely]] {
true_path();... |
62,222,949 | 62,223,493 | locking class members from other threads | I need to lock private class member for other threads: if i do not unlock variable, other threads can not use that variable, and wait before it unlocks. (something like mutex).
For example:
using namespace std;
class a
{
public:
a() {
//here i need to lock my variable
thread th([this] {
Sleep(10000);
... | You can't lock arbitrary variables. What you need to do is guard access to your shared variable using a mutex or other synchronization object. For example:
class a
{
public:
a() {
std::thread th([this] {
std::lock_guard lock(variable_mutex);
std::this_thread::sleep_for(std::chrono:... |
62,223,379 | 62,224,148 | How to create random name generator from input files c++ | I have two text files, firstnames.txt and lastnames.txt. There are 20 names in each, and they are all on a new line. I need to make a random name generator in my program.
I'm not allowed to use string[] so I have to use char*[]. So far, my plan is to add all of the names into the char*[] array, and then make a random n... | std::getline() only works with std::basic_string types, like std::string.
std::istream::getline() works with char*. You are just not allocating any memory for the char* to point at.
You can use a char[][] instead of a char*[] (a char[] decays into a char*), eg:
const int max_name = ...; // some limit you decide
//Open ... |
62,223,771 | 62,225,826 | C++ clean way to define table of ifloats as array | I have a table like this:
static const float scalers[NUM_Categories] = { 0.f, 0.97f, 0.92f, 0.83f,
0.94f, 0.73f, 0.9f};
What is the cleanest way to define this? It's a global.
I was thinking of something like
static const float scalers[NUM_Categories] = { [Category_A]... | If you use a std::array instead, you can initialize it with a function, in which you can specify elements one at a time.
constexpr auto init_scalers() -> std::array<float, NUM_Categories> {
auto scalers = std::array<float, NUM_Categories>{};
scalers[Category_A] = 0.f;
scalers[Category_B] = 0.97f;
return... |
62,223,778 | 62,224,460 | Debugging with GDB in VSCode on Windows | I'm at a bit of a loss here, I hadn't really expected this to be difficult. I usually work on Linux, but today I had some work that I needed to do and only had a Windows machine. I thought this would be no problem, I can install git for windows, clone my project, and get right to work. Its just been a huge mess. I'm re... | If you are using WSL to compile the project you should not use MinGW gdb.
You need to install gdb on you Linux subsystem (using native tools like apt if you are using Ubuntu WSL), reopen your project in WSL and configure the WSL path to gdb.
I was able to successfully debug using this setup on WSL.
|
62,224,066 | 62,234,096 | How to use VirtualDesktopManager interface? | I'm trying to find out if a window belongs to the current virtual desktop.
I found the VirtualDesktopManager class form the winapi, but even though it is supposed to be in the "shobjidl.h" header according to here, when I compile the code it throws this error:
85:5: error: 'VirtualDesktopManager' was not declared in t... | Apparently this interface was not included in the "shobjidl.h" header in mingw64 which I was using, running it in Visual Studio it finds it. So the issue was in the header.
|
62,224,080 | 62,224,655 | Will instance of shared_ptr<Base> and shared_ptr<Derived> with same raw pointer share reference count? | Let's say I have two classes, Base and Derived, where Derived inherits from Base. Now, let's say I execute the following code:
shared_ptr<Derived> derivedPtr = make_shared<Derived>();
shared_ptr<Base> basePtr = derivedPtr;
Will the copying of derivedPtr to basePtr result in derivedPtr's reference count being updated (... | So shared_ptr is more than just a pointer and a reference count.
It is a pointer and a pointer to a control block. That control block contains a strong count, a weak count, and a destruction function.
There are 3 ways to construct a shared_ptr.
First, you can construct it from a raw pointer. When that happens, it all... |
62,224,190 | 62,224,302 | Use class templates inside another class template | Let's say I have some classes using templates like the following in some file(s) :
// PointerTemplates.hpp
template <class T>
class Smart_Ptr_A
{
// [...]
};
template <class T>
class Smart_Ptr_B
{
// [...]
};
I would like to create another templated class that can ... | You will need to use a template template parameter.
template <template<class> class PtrType>
class ClassFoo
{
// [...]
PtrType<ClassBar> m_pBar;
};
|
62,224,612 | 62,224,688 | Variadic generic lambda and function overload | I have the following variadic generic lambda and overloaded foo() function defined.
template <typename Lambda>
auto bar(Lambda&& lambda) {
return [lambda = std::forward<Lambda>(lambda)](auto&& ...args) {
return lambda(std::forward<decltype(args)>(args)...);
};
}
void foo(std::function<void()>&& cmd, st... | std::function<void()> can store a function with any return type (void or not), its return value is discarded.
Because of that, in (4) both overloads are applicable, and the compiler can't decide which one to use.
In (1), (2), and (3) on the other hand, at least one of the two lambdas returns void, so the bool overload ... |
62,225,360 | 62,225,390 | Why are changes made to a pointer inside a function not visible outside the function? | I am implementing a linked list. There is a problem: when I change a pointer inside a function, the change is not visible outside of the function.
#include<bits/stdc++.h>
using namespace std;
//define
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
... | This function:
void add(List *head, int data)
takes the head pointer by copy, so changes to the pointer inside the function are not visible to the caller. This means the pointer head in main is not pointing to valid memory, and dereferencing it invokes undefined behavior (which could cause the crash).
Make the functio... |
62,225,834 | 62,225,964 | Overloading std::sqrt | I've tried to overload std::sqrt from <cmath> like this:
class MyClass {
...
}
MyClass std::sqrt(const MyClass& arg) {
...
}
But it failes with error
namespace "std" has no member "sqrt".
I'm using MS c++ compiler with Visual Studio
Does anyone know how to do it?
| namespace std {
MyClass sqrt(const MyClass& arg) {
// ...
}
}
|
62,226,043 | 62,226,292 | How to get the current time in c++ in a " Safe " way | I'm not new to C++, but I mostly only use the most basic standard library features like <iostream>, <vector>, <map>, etc.
Right now, I'm working on a simple game and I'm working on a logger class, but I'm stuck on getting the current time.
Don't get me wrong, I've seen a lot of ways to get the time in StackOverflow an... | The asctime() and ctime() functions are "unsafe" because they return a pointer to static buffers that may or may not be thread-safe depending on implementation, and if they are not thread-safe then they could be overwritten by other threads before you have a chance to use them.
The "more secure" asctime_s() and ctime_s... |
62,226,151 | 62,226,197 | c++ do while condition is not work as expected | I wonder why while (selection != 'q' && selection != 'Q') works but while (selection != 'q' || selection != 'Q') does not work. It will never terminate the loop. When I use else if (selection == 'q' || selection == 'Q' ) (with ||) it's working fine. Can someone help?
#include <iostream>
using namespace std;
int main... | Let's look at your proposed condition, which you are wondering why it doesn't work:
while (selection != 'q' || selection != 'Q')
In order for this while loop to terminate the loop, the above expression must evaluate to false. That's how a while loop works. In other words:
!(selection != 'q' || selection != 'Q')
must ... |
62,226,376 | 62,226,423 | Stack Smashing Detected C++ after I added new variables in my code along with some operations | I made a code for computational purpose. Everything was going well until I added these lines in my function in main code. Most of the threads I read about this issue have solution referring to cases where strings are being handled. None of them relates much closer to problem I am dealing with.
code added in main progra... | for (int a0=0;a0<4;a0++){
for (int b0=0;b0<3;b0++){
flx[a0][b0] = [...];
Note that in the outer loop, a0 takes on values 0 to 3, inclusive, but you declared your array like this:
float flx[3][4];
... which means only 0, 1, and 2 are valid indices to the first/major dimension of flx. You are therefore writin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.