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
6,935,406
64,851,639
Traversing a directory tree in C++
This is been a curiosity of mine for a while: how do you traverse a directory tree without using boost or any third-party library? Just plain ol' C++ (examples in 98, 99, 01, 0x and 1x specs are okay.)? It was done back in the day before boost existed so there's got to be a way to do it.
As of the adoption of the C++17 standard there exists a <filesystem> header included in the language that does exactly this. See your compiler's documentation to determine if it's supported.
6,935,418
6,941,554
Newbie question regarding submatrix manipulation using BOOST uBLAS
This has been puzzling me for a few hours, so maybe someone here can help. I am trying to translate the following simple Matlab program into C++ using uBLAS: >> R = eye(4); >> R(:,3) = R(:,4); >> R R = 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 This is my atte...
An example: MATLAB >> m = [0 1 2 3 4; 5 6 7 8 9; 10 11 12 13 14; 15 16 17 18 19] m = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 >> m(:,3) = m(:,4) m = 0 1 3 3 4 5 6 8 8 9 10 11 13 13 ...
6,935,465
6,935,499
What is the lea instruction before a method call doing?
In looking at my disassembled code I see a lot of the following: 00B442E9 push 4 00B442EB push 3 00B442ED lea ecx,[ebp-24h] 00B442F0 call Foo::Bar (0B41127h) I understand pushing the parameters before the call, but what's the lea doing here?
In the thiscall calling convention used by Visual C++ for x86, the this pointer is passed in the ecx register. This lea instruction copies the this pointer into the ecx register before calling the member function. You can read all about the lea instruction in the Stack Overflow question "What's the purpose of the LEA ...
6,935,491
6,935,503
C++ void prefixed to a function call. eg. `main() {void func();}`
void func() {assert(0);} int main () {void func();} The above code does not call func(), or at least does not reach the assertion. Not that I really need to know, but I'm just curious, what is going on here?
You're declaring a prototype for a function named func which returns nothing and takes no arguments. That's (one of) the subtle difference between function calls and function prototypes. Notice that the line above main, the void func() {assert(0);}, has no effect on whether this is a prototype or a call. You could remo...
6,935,851
6,935,897
Vector C++ with your own Class
I tried searching in google but it just shows what I'm not looking for. I have this class called Student and in my main class I instantiated it to be a vector. I tried adding this line in my main class vector<Student> students; students[0].setFirstName("Test"); and it throws an error on my Student class void Student::...
As I'm sure you know, the expression students[0] means that you are trying to access to first item in the vector. But in order to access the first item, you must first add a first item. Quite simply, add a call to vector::push_back before trying to use anything in the vector. Alternatively, declare the vector by vector...
6,936,030
6,937,482
Do we really need "enum class" in C++11?
When we have, struct E { enum E_ { HELLO }; }; // 'E' is inheritable then why do we need, enum class E { HELLO }; // 'E' is not inheritable IMO 2nd version doesn't offer more features than the 1st. I don't think that enum class is introduced just to save 2 curly braces {};! Am I missing any important aspect ? As a m...
Besides what was already mentioned, an advantage of enum class is better type safety - the enum class enumerators don't convert implicitly to integers.
6,936,124
6,936,532
Why does C++ not have a const constructor?
(Edit: Heavy change because previous example was flawed, which may make some answers/comments seem odd) This might be an overly contrived, but the following is legal because of lack of const constructor: class Cheater { public: Cheater(int avalue) : cheaterPtr(this) //conceptually odd legality in const Chea...
It would not be a const method itself If this constructor were not a const method itself, then the internal pointers and such would also not be const. Therefore, it could not set const values into those non-const members. The only way to make it work syntactically is for this constructor to require member initializat...
6,936,299
6,936,409
Problems with casting a void** to a T**
TL;DR: I have a Derived** that I store as a in Lua as a void* userdata. Then I try to get it back as a Base** and stuff breaks. Is there anything I can do or is this all madness that's doomed to failure? Details: I'm passing some data back and forth between Lua and C++, and Lua requires the use of void* to store userda...
The code is not safe. When you cast Base * to void *, you should always cast void * back to Base * first and then cast it again to Derived *. As so: Derived *obj = ...; Base** ud = reinterpret_cast<Base **>(lua_newuserdata(L, sizeof(Base*))); *ud = obj; // implicit cast Derived -> Base ... Derived *obj = static_cast<...
6,936,543
6,936,582
Do I need to do something special to get my C++ program to compile using gcc?
Why does my program compile nicely with no warnings when I type g++ program_name but when I type gcc program_name I get screenfuls of undefined reference errors... I am using the standard library quite a bit, here are my includes: #include<string> #include<vector> #include<fstream> #include<sstream> #include<iomanip> #...
gcc doesnt link in the standard c++ libraries by default. Either add -lstdc++ to the link line, or just compile with g++.
6,936,720
6,937,829
Why lifetime of temporary doesn't extend till lifetime of enclosing object?
I know that a temporary cannot be bound to a non-const reference, but it can be bound to const reference. That is, A & x = A(); //error const A & y = A(); //ok I also know that in the second case (above), the lifetime of the temporary created out of A() extends till the lifetime of const reference (i.e y). But my qu...
The standard considers two circumstances under which the lifetime of a temporary is extended: §12.2/4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object...
6,937,384
6,937,413
Method taking two default parameters
I have a method with the following definition: void foo(int i = 0, bool flag = false) {} I want to call foo() by passing only the second argument: foo(true); But like this it will always pass it to the first parameter (i). Is there any other solution I can pass my argument to the second parameter ? Or the only way is...
Technically no. But you can fake it with overloads, thusly: void foo(bool flag) { foo(0,flag); }
6,937,654
6,937,696
Is there a way to instruct a C++ compiler to skip rest of current file?
Once in a while some functionality has to be conditionally compiled. For example, there's class Logger that is only used when WITH_LOGGING macro is #defined: // Logger.cpp #ifdef WITH_LOGGING #include <Logger.h> // several hundred lines // of class Logger // implementation // follows #endif which is not very convenien...
An easy way to clarify this would be to put the implementation in another file which is included: file Logger.cpp: #ifdef WITH_LOGGING #include <Logger.h> #include "logger.impl" #endif file logger.impl: // several hundred lines // of class Logger // implementation // follows
6,937,758
6,938,364
C++ casting a base pointer to an interface pointer
Here is some pseudo code of my setup: class IMyClass { ... }; // pure virtual class class CMyBaseClass { .... }; class CMyClass : public CMyBaseClass, public IMyClass { ... } Then I have collection of CMyBaseClass*. I have custom RTTI that allows me to find out if a class implements given interface. So I can find whic...
Well, if you insist in not using the language RTTI, you can use just like the old COM: make all your classes or interfaces derive from the following interface: class IMyCast // similar to IUnknown { public: virtual void *CastTo(interfaceId_t id) = 0; //Similar to IUnknown::QueryInterface }; Now in your CMyClass: ...
6,938,029
6,938,058
Function pointer object forward declaration in C++
I have a group of function pointer objects in a header C++ file, I include this file in the main header file and then trying to use these objects in another C++ file (initialize function pointers and then use these pointers through another part of code) but I always get a "multiple defined" error. Is there a way how to...
You can do this in your main header. (Assusming you're using a typedef called FnPointer) extern FnPointer fn; Then in your implementation file FnPointer fn; ( extern means this variable will exist but I'm going to allocate space for it later in some other compilation unit. )
6,938,069
6,938,090
How do I get mouse WM_MouseMove Message on SCREEN?
Now I'm working on a project which require me to get mouse moving message from all time. My app only have a tiny windows for configuration purpose and it will not even appear on the desktop for most of the time. What I need is I need to be able to record mouse moving on desktop. meaning people moving their mouse on the...
Yes, you need a global hook, and as far as I know you should use C or C++. See the docs about function SetWindowsHookEx() & co. (WH_MOUSE hook). But beware! You must write a global hook in a DLL, and it will get injected in every process with a window, so any bad thing you do will likely crash any other program in your...
6,938,219
6,938,437
How to check whether all bytes in a memory block are zero
I have a block of memory with elements of fixed size, say 100 bytes, put into it one after another, all with the same fixed length, so memory looks like this <element1(100 bytes)><element2(100 bytes)><element3(100 bytes)>... In some situations I need to determine whether all bytes of a certain element are set to the ...
The obvious portable, high efficiency method is: char testblock [fixedElementSize]; memset (testblock, 0, sizeof testblock); if (!memcmp (testblock, memoryBlock + elementNr*fixedElementSize, fixedElementSize) // block is all zero else // a byte is non-zero The library function memcmp() in most implementations wil...
6,938,222
6,938,243
Is it possible to "add" to the default copy constructor?
Is it possible to "add" to the default copy constructor? Eg. For this class: class A { public: int a; int* b; }; I want to just write A::A(const A& rvalue): a(rvalue.a), b(new int(*(rvalue.b))) {} without the a(rvalue.a) part. (Ignore the bad/ugly code and possible memory leaks)
What you ask for is impossible. Once you declare your own copy constructor the compiler will not generate a copy constructor for you. That means you won't be able to simply add or augment the default copy constructor because it won't exist. It's all or nothing, so to speak.
6,938,347
6,938,382
errors about overload new operator in a template class
I want to overload new operator in a template class. But something wrong happends. In file test4.h, I defined a class #include <stddef.h> #include <iostream> template <class T> class lei{ public: T me; static void* operator new(size_t size); }; test4.cpp implement the new ope...
You need to put the template implementation in the header file also. The implementation needs to be visible to the compiler when it needs to instantiate the template. This the C++FAQ 35.12 to learn why this is necessary, and the following entries for ways to fix it. (Also, your implementation of operator new should ret...
6,938,640
6,939,040
What might cause an infinite loop error
I am working on a network programming and I have this code void WorkHandler::workLoop(){ . . . while(1){ if(remainLength >= MAX_LENGTH) currentSentLength = send(client->getFd(), sBuffer, MAX_LENGTH, MSG_NOSIGNAL); else currentSentLength = send(client->getFd(), sBuffer, remainLength,MSG_NOSIGNA...
With blocking IO send will block if the kernel buffer is full and will block untill the clients have read the data. Do you send large chunks? If so, check your client. If you don't trust clients (they can abuse this to do denial of service attacks) there are a couple of ways to do this properly: poll (with timeout) on ...
6,938,679
6,941,751
Mac OS X: detect already opened app reopen
I have a mac os x app with a window which can be hidden. When the user clicks on the app icon in the dock (or open -b com.mycompany.myapp in the terminal), I would like this window to be shown again (it's a Qt app, so the setVisible(true) thing is known). How do I catch the app activation event? Thanks for any help.
It's an Apple Event, so you'll want to use the Apple Event Manager to register a handler for the core suite's reopen-application event. That's how you do it in Carbon. You tagged the question as [carbon] and not [qt], so I assume you want a Carbon solution rather than a Qt solution.
6,939,020
6,939,059
Compiler Error: "expected specifier-qualifier-list"
int main() { typedef struct a { static int w; char *p; } a; } on compiling it gives error:expected specifier-qualifier-list before 'static' could u please tell me what this error means and how to remove it?
Local classes cannot have static data members in C++. To quote the standard (Paragraph 9.8.4) A local class shall not have static data members. In the unlikely case that you don't know, a local class is a class, struct, or union defined in function scope. 9.8.1 A class can be defined within a function definition; su...
6,939,103
6,941,680
How could my code tell a compile-time constant versus a variable?
Here's my problem. I have a BINARY_FLAG macro: #define BINARY_FLAG( n ) ( static_cast<DWORD>( 1 << ( n ) ) ) Which can be used either like this ("constant" scenario): static const SomeConstant = BINARY_FLAG( 5 ); or like this ("variable" scenario): for( int i = 0; i < 10; i++ ) { DWORD flag = BINARY_FLAG( i ); ...
It's not possible to pass an argument to a macro or function and determine if it's compile time constant or a variable. The best way is that you #define BINARY_FLAG(n) with compile time code and place that macro everywhere and then compile it. You will receive compiler-errors at the places where n is going to be runtim...
6,939,121
6,939,401
Scrolling a Scroll Area in Qt
I just have a Scroll Area widget that consists of several Qlabels . take a look at the situation: I tried to to do the following but it didn't work out, its doesn't scroll ... #include "form1.h" #include "form.h" #include "ui_form.h" #include "ui_form1.h" #include<QScrollArea> #include<QScrollBar> Form::Form(QWidget...
Did you apply a layout to the QScrollArea? In the designer, select the QScrollArea and then click on one of the layout buttons (or press CTRL-L). This may not give you exactly what you want, but if things can then scroll, you know that the layout is the problem.
6,939,129
6,939,278
How to use std::find/std::find_if with a vector of custom class objects?
I have a class representing a user called Nick and I want to use std::find_if on it, where I want to find if the userlist vector has an object included with the same username I pass in. I did a few attempts by trying to create a new Nick object for the username I want to test and overloading the == operator and then tr...
You have to define operator== with two Objects outside your class, as a tool function, not a member. Then to make it friend just put the declaration of the function inside the class. try something like this: class Nick { public: friend bool operator== ( const Nick &n1, const Nick &n2); }; bool operator== ( cons...
6,939,182
6,992,938
gprof issue with output
The question is: Why is my gprof output only displaying "Index by function name" ? I have compiled my application with the support of this tutorial : http://ececmpsysweb.groups.et.byu.net/cmpsys.2004.winter/citizenship/Bryan_Wheeler/Profiling_Tutorial.html So my application is compiled with -p -pg After i run my appli...
The Problem was that putty was somehow hiding the output, after opening vi and exiting it, it would actually show the output from the program.
6,939,239
6,942,482
Is something wrong with wrapper classes for C string functions?
I have some C++ code written in C-style. For some reasons I can't use C++ string and IO libraries, so for strings handling I should use only functions like sprintf, itoa, etc. I want to replace C-style which requires temporary buffers char buf[12]; itoa(x, buf, 16); set_some_text(buf); by the following code...
ATL and MFC String Conversion Macros are also written in this way. Calling the constructor directly like i2a(x) will create a temporary object that will live until the function to which it is passed is complete. So here: do_some(i2a(x)), the temporary object will be there until do_some() is complete. Refer the Example...
6,939,260
6,939,317
Convert String to Int with Stringstream
have a little problem here: int IntegerTransformer::transformFrom(std::string string){ stream->clear(); std::cout<<string<<std::endl;; (*stream)<<string; int i; (*stream)>>i; std::cout<<i<<std::endl; return i; } I by calling this function with the string "67" (other values dont work too) i ...
Did you notice there are two std::cout in the function itself? Beside that also add this: stream->str(""); //This ensures that the stream is empty before you use it. (*stream)<<string; By the way, why don't you use boost::lexical_cast? int IntegerTransformer::transformFrom(std::string s){ return boost::lexical_ca...
6,939,373
6,939,405
C++ set -- number of elements with a key less than x
I have a set<int> and I want to see how many elements in it are less than x. (x is also int) What should i do?
Use lower_bound to compute std::distance(s.begin(), s.lower_bound(x)). (If x is a key, this counts the number of elements strictly before x.)
6,939,422
6,939,933
How do I create a color bar (TV test pattern)
I need to create a colorbar like THIS I use a scaled array of floats between 0 and 1. Now I want to compute the RGB color from this float. How to do it? Want to write it in C/c++ so I think I need 2 functions. The first function to build the colorbar with one parameter like STEPSIZE and the second function need the val...
RGB uses bytes, so assuming your array of floats is something like float scaledColor[3]; // 0 = R, etc., all 0.0 < scaledColor[x] < 1.0 then you can do: unsigned char r = (unsigned char)(255 * scaledColor[0]); unsigned char g = (unsigned char)(255 * scaledColor[1]); unsigned char b = (unsigned char)(255 * scaledColor[...
6,939,470
6,939,527
how to clear the content in the String stream.?
can any one tell me how to clear the content of the stringstream..? i tried the following but it didnt work. stringstream ss; ss<<"bala"<<"murugan"; cout<<ss.str(); //Output balamurugan ss.str().clear(); ss<<" hi"; cout<<ss.str(); // output is balamurugan hi my required output is " hi" alone.. Pls tell me
What you're doing is clearing the string that is returned from the stringstream, not the internal string. You'll have to actually do the ss.str("") See here: How do you clear a stringstream variable?
6,939,663
6,939,689
Assigning function to variable
Why assign a function to a variable? What's the point in assigning int x, y to ReadNumber() ? Is it for storing return value of function in a variable? Or is this just a way to pass arguments? #include <iostream> int ReadNumber() { using namespace std; cout << "Enter a number: "; int x; cin >> x; r...
Yes, it is storing the return value of the function. The code calls the ReadNumber function twice first. ReadNumber reads a string from the console then returns it as an int. The code stores the two function returns. It then adds these two numbers together and passes it as an argument to the WriteAnswer function. The W...
6,939,693
6,945,649
Windows 7 or Windows 2008 how to launch a process in Local System Account or System Context (from desktop aplication)
In C++ I want to launch a process from my Desktop Application in "Local System account" or "System Context". My application executes with admin privileges. Is it possible? How? Thanks in advance.
You can do what SysRun does: install a system service and launch the app from the service.
6,939,711
6,940,327
Embedding Python: How to help the scripter?
I'm using Boost to embed Python in my application. For example, I want to check that the following function receives an integer and a string as the first and second parameters (the function is defined in C++). someFunction(123, 'words') If I find that the parameters are incorrect, how can I notify the scripter about w...
Raise an exception with all the information you want them to know, just like you would in Python. In fact, that answer seems so obvious, it makes me think I'm missing something in your question.
6,939,805
6,940,066
Using C++ classes in objective-c
I have an application written in C++. I've read some articles on how we can use C++ classes in objective-c. My question is will it work if I use my application, which is designed for windows, for iPhone? What I mean to say is can I use the classes used in this application for an iPhone app?
Yes, you will be able to use classes that don't rely on platform-dependent libraries.
6,939,809
6,940,805
Bind Texture in Repeat Mode
I am trying to store an octree in a 3D texture in OpenGL for use on the GPU using Cg, from a chapter in GPU Gems 2 found here http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter37.html. However the results I am getting are incorrect. I think this is because of how I create the octree. In the appendix of that cha...
The filters can't be repeat, that will generate a GL error, only the wrap mode can be GL_REPEAT, and that's probably what the book means.
6,939,890
6,939,929
Class implementation in multiple files
I am trying to implement a class in different cpp files. I understand it is a legitimate thing to do in C++ if the member functions are independent. However one of the member function uses another member function such as in this case: In function1.cpp #include "myclass.h" void myclass::function1() { function2(); }...
As long as myclass.h contains the definition of the class with the declarations of the member functions, you should be fine. Example: //MyClass.h #ifndef XXXXXXXX #define XXXXXXXX class MyClass { public: void f1(); void f2(); }; #endif //MyClass1.cpp #include "MyClass.h" void MyClass::f1() { }; //MyClass2.cpp...
6,939,986
6,940,123
C++ nested constructor calls vs. function declaration
What is the difference between the code snippets labeled "version 1" and "version 2" in the following code section: int main() { using namespace std; typedef istream_iterator<int> input; // version 1) //vector<int> v(input(cin), input()); // version 2) input endofinput; vector<int> v(input(cin), endofin...
why Because the Standard says, more or less, that anything that can possibly be interpreted as a function declaration will be, in any context, no matter what. what the arguments... are You might not believe this, but it's true. input(cin) is treated as input cin; in this spot, parentheses are allowed and simply mea...
6,939,989
6,940,372
Global C++ object initialization
Many C++ programmers have suffered from the fierce clashes with the global C++ objects initialization/cleanup. Eventually I've found a good enough solution to this problem, I've been using (and anjoying) it for years now. My question is: does this solution fully comply to the C++ standard, or it's "platform/implementat...
I don't think you have a formal guarantee that your solution works on every compliant implementation, because the C++ standard doesn't guarantee that statically allocated arrays of char are aligned as would be required by any object of the same size.
6,939,993
6,940,151
How to efficiently implement graph with a lot of big complete subgraphs?
I'm currently dealing with a performance issue of graph implementation. Used technologies It is programmed in C++. For the moment, the graph is implemented thanks to the BGL. About the graph The managed graph is dynamic and undirected. It has two kinds of structures: a lot of complete subgraphs and few of single edges....
Your final solution is the one I would have gone for myself. It sounds as efficient as it can be.
6,940,006
6,940,618
Nt* api headers for user mode app
I'm looking for header files for C/C++ which will contain ntdll.dll function definitions. I know those apis are for internal use and undocumented. There is such thing for pascal, I can't beleive there is no for C/C++, though I couldn't find any. thanks
It should not be too hard to convert the ones for Pascal back to C. With a compiler like Embarcadero's C++Builder, you could have it done by the Delphi compiler that comes with it. Just ask someone with C++Builder to add the .pas file to a C++ project and a .hpp file will be generated, which is simply a .h file with a ...
6,940,024
6,940,047
Is partial class in C# and in C++ defining functions in multilple CPP files are same?
In C++ we can declare a class in a .h file and can have the definitions for functions across multiple files. Is this concept same by using partial keyword with classes in C#?
No it's not. The partial keyword in C# allows you to add new methods and members to a class. In c++, once a class is defined in a header, you need to change that header in order to change the class, you can't just declare new methods/members in a different header. C#: class A{ public void f(){} } //other file: part...
6,940,088
6,940,190
How do I fix this blocking issue?
119 while(remainLength > 0){ 120 if(remainLength >= MAX_LENGTH){ 121 log("WorkHandler::workLoop, remain %d > max %d \n", remainLength, MAX_LENGTH); 122 currentSentLength = send(client->getFd(), sBuffer, MAX_LENGTH, MSG_NOSIGNAL); 123 log("...
If you don't want send to block, you'll need non-blocking I/O. There's no way around that. You don't have to put the socket in non-blocking mode though, the MSG_DONTWAIT flag can be used on a per-call basis. But you will need to deal with EAGAIN/EWOULDBLOCK error codes. From the man page linked above: The flags argume...
6,940,284
6,948,657
how can i delete all items under selected item in treeview
i have treeview as the view and QStandardItemModel as the model. now i each node in the model has child nodes . my question is how can i delete all the child nodes under selected item ? all i found is this but this is for one row . i need all the rows under item. bool TableModel::removeRows(int position, int rows, cons...
If you remove a row from a model, the child rows of that row will also be removed. So you don't need to do anything. However, it looks like you're implementing your own row storage using QList. In this case, it depends what you've set up--what type your QList is storing.
6,940,382
6,941,032
Boost Serialization - No archive_exception when deserializing corrupt data anymore?
Months ago I implemented a component which receives data via UDP-network, deserializes it via Boost::Serialization and starts working with the incoming objects. After some time of using this component random crashes occured, which I could solve when finding out that someone else is sending data to my UDP-Port. I solved...
My answer is not directly related to boost serialization but it is always a good idea to do some validation on incoming data from network before entering deeper logic. Before diving deep into boost serialization I suggest you : Check the size of UDP packet If you are using some kind of header do some validation Whate...
6,940,428
6,940,585
Best practice: Validate conditions for method calls?
I guess in almost every programm sometimes methods don't need to be called all the time but under specific conditions only. It it very easy to check if a method must be called. A simple if-statment can do the trick. if (value == true) { DoSomething(); } But if you have many conditions the validation can get compli...
Clean Code — A Handbook of Agile Software Craftsmanship promotes not to write methods accepting a single boolean parameter because each method should do one thing and one thing only. If a method takes a boolean parameter to decide what to do, it automatically does two things: deciding what to do and actually doing some...
6,940,856
6,941,911
What's faster: down-cast from virtual base or cross-cast?
This is somewhat hypothetical as I'm not too worried about performance - just wondering which option is actually the fastest/most efficient in general, or if there is no difference whatsoever. Suppose I have the following code for a visitor template that supports overloading: #define IMPLEMENT_VISITOR_WITH_SUPERCLASS(s...
Well, it looks like the cross-cast method is faster than the virtual base method. With a visitation that requires 1 fallback to a superclass, over 100000000 iterations, the cross-cast method took 30.2747 seconds, and the virtual base method took 41.3999 - about 37% slower. With no fallback to an overload for a supercla...
6,940,918
6,941,025
How to forward declare a structure used as a member variable
I have a struct called CardState defined in Application.h: #ifndef APPLICATION_H #define APPLICATION_H #include <Session.h> // Note that both files include each others struct CardState { bool property1; bool property2; }; class Application : public QApplication { Q_OBJECT public: explicit Applicat...
As per Oli Charlesworth's comment, this should work as it is. In general case, you would want to either: Put CardState in its own header and then #include it in all "client" headers, thus avoiding any complications that might arise from include order of these headers. Declare Session::cardState_ as a (smart) pointer a...
6,941,212
6,941,267
Counting "new" and "delete" bytes
I have a .net project that uses C++ project and is eating a lot of memory. I wonder if there is quick and easy way to count inflow bytes allocated by new and outflow bytes freed by delete operator. Add some logging or something. Source code for both operator is provided by Visual Studio so I can hack it. The problem is...
Usually memory profiling tools like Valgrnid or Rational Purify can help you profile the memory utilization of programs. In case you still want to have your own implementation, You can Replace the global new and delete operators by overloading them and inside your own overloaded operators you can maintain count of the ...
6,941,315
6,941,685
What's the best way of finding a heap corruption that only occurs under a performance test?
The software I work (written in C++) on has a heap corruption problem at the moment. Our perf test team keep getting WER faults when the number of users logged on to the box reaches a certain threshhold but the dumps they've given me just show corruptions in inoncent areas (like when std::string frees it's underlying ...
The best tool is Appverifier in combination with gFlags but there are many other solutions that may help. For example, you could specify a heap check every 16 malloc, realloc, free, and _msize operations with the following code: #include <crtdbg.h> int main( ) { int tmp; // Get the current bits tmp = _CrtSetDbgFlag(_C...
6,941,332
8,018,225
Anticipate "kernel too old" errors between 2.6.16 and 2.6.26 kernel versions
I build an application on a machine running Linux (Debian) with kernel 2.6.26-2-amd64 and I want to run this application on another machine running Linux (Suse) with kernel 2.6.16.60-0.21-smp but I get the error "FATAL: kernel too old". I know from research on the internet that this can happen when building against a g...
One way you can determine the minimum kernel version for a given ELF file is to run file on it, like so: $ echo 'int main(){}' > test.c $ gcc -o test test.c $ file test test: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.38, not stripped The important par...
6,941,478
6,941,516
C++ static compile error using templates
I have template < typename threadFuncParamT > class ThreadWrapper { public: static int ThreadRoutineFunction(void* pParam); int ExecuteThread(); ThreadWrapper(ThreadPool<threadFuncParamT> *pPool); }; template<typename threadFuncParamT> int ThreadWrapper<threadFuncParamT>::ThreadRoutineFunction(void* pPar...
You're missing the ">" It's pWrapper->ExecuteThread() not pWrapper-ExecuteThread()
6,941,548
6,943,336
How to customize watch window formatting
I have a class something like: class TimeSpan { ... private: __int64 m_ticks; }; When debugging in VS, TimeSpan variables show up as unreadable huge numbers, and I need to use some kind of utility to make it readable. I would like to be able to see TimeSpan variables in a sensible way in the watch window, like "01...
You can find information about this here. It also applies to VS2008. It is a bit underground and unstable. Take care ! Another option is to modify your class to include the formatted string and update it in all your non-const method. class TimeSpan { ... private: __int64 m_ticks; #ifdef _DEBUG std::string m_str;...
6,942,098
6,951,395
Qt QTreeView: Only allow to drop on an existing item
I've got a custom model inherited from QTreeView. I've enabled drag and drop and can currently drop an item onto the tree. However, you can currently drop onto either an existing item or between items. I would like to restrict this so that you can only drop onto existing items. I've set DragDropOverwriteMode to t...
You'' need to catch the drag enter events by reimplementing the dragEnterEvent method in your custom view. The example from the Qt docs is: void Window::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/plain")) event->acceptProposedAction(); } In your case, you would probably...
6,942,163
6,942,363
VC++ 9 QT Project, Convert To Eclipse CDT
Their is a project I would like to start working on but the problem is I use Linux and the project is based off windows. (VC++ v9) I would like to convert it to Eclipse CDT but qmake and different includes are driving me mad. Project Repo 1 - I downloaded Eclipse Indigo CDT 2 - Downloaded the latest QT ( qt.nokia.com /...
Here's a tutorial to do exactly what you're asking. It's geared for OS X, but the same principles would apply.
6,942,244
6,942,290
Iterating through all the members of a vector
I have two structs defined as in the following: struct vertex { double x; double y; double z; }; struct finalVertex { int n; vertex v; }; I use the following code to iterate through the list and print all the members: vector<finalVertex> finalVertices; vector<finalVertex>::iterator ve; for ( ve = fin...
The problem is operator precedence: write (*ve).v.x or simpler, ve->v.x. Apart from that, I would advise you to override operator << for your vertex structure to make your code vastly more readable: std::ostream& operator <<(std::ostream& out, vertex const& value) { return out << value.x << " " << value.y << " " <<...
6,942,273
42,484,107
How to get a random element from a C++ container?
What is a good way to get a [pseudo-]random element from an STL range? The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) and then take my random element from c.begin(). However, I might want a random element from a const container, or I might not want the cost of a full shuffle. Is there ...
C++17 std::sample This is a convenient method to get several random elements without repetition. main.cpp #include <algorithm> #include <iostream> #include <random> #include <vector> int main() { const std::vector<int> in{1, 2, 3, 5, 7}; std::vector<int> out; size_t nelems = 3; std::sample( in....
6,942,488
6,942,592
Casting a pointer to an int / Storing pointers to type T
I'm hoping to count how many times a pointer is being used. I have a map: static std::map<unsigned int, unsigned int> counters; When I want to insert a new value to it i'm using it like this: template<class T> MyClass::addPointer(T * tPtr){ counters[((unsigned int) tPtr)]++; } Is it OK and safe to do a cast like ...
IMO, you really don't need to cast it to unsigned int. You can have the map with void*: static std::map<void*, unsigned int> counters; Also a null check is important here: template<class T> MyClass::addPointer(T * tPtr){ if(tPtr != 0) counters[tPtr]++; } Rest is fine.
6,942,567
6,942,814
Trouble with iterating through std::set (c++)
I am having problems with sets all day. Some I can solve, others not. This one is bugging me since the morning, and I have run out of patience. Please help, mighty stackoverflow! So, I have a set which contains a custom object of mine, its called "vect" and is based on eigen::matrix. That means, I get values from vects...
There are a few possibilities as to why this is happening to you: Are you reusing the set. If yes, do you clear() it between reuses ? You are storing pointers to vectors in the set, are you changing the vectors inside the set ? Perhaps you want to store the pointer to the vector because otherwise the compiler gives y...
6,942,696
6,943,299
pthread_mutex_lock error
#include "MutexCondition.h" bool MutexCondition::init(){ printf("MutexCondition::init called\n"); pthread_mutex_init(&m_mut, NULL); pthread_cond_init(&m_con, NULL); return true; } bool MutexCondition::destroy(){ pthread_mutex_destroy(&m_mut); pthread_cond_destroy(&m_con); return true; } b...
I wonder if your mutex instance is being trashed due to a copy or assignment operation (that you may not even be aware of). Mutexes aren't copyable - you should make sure the wrapper classes you have for the can't be copied by making the copy-ctor and operator=() private and unimplemented (or similar technique): #ifnde...
6,942,745
6,943,083
Transform upper right triangular matrix given the columns in C++
I have a vector containing something like {1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 } So the vector represent the columns of an upper right matrix 1 2 4 7 0 1 5 8 0 0 1 9 0 0 0 1 How could I use the vector and get from {1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 } to 1 2 4 7 2 1 5 8 4 5 1 9 7 8 9 1 as a vector { 1,...
int k=0; for(int i = 0; i<4; ++i) for(int j = 0; j<=i; ++j) v[i][j]=v[j][i]=w[k++]; Assuming source vector is w, dest is v. If it should be 1D, not 2D, then [i][j] should be changed to [4*i+j]. EDIT This can be done 'in-place', but it is a little tricky. In order not to overwrite values you haven't used ye...
6,942,762
6,942,862
initialization list question, with emphasis on std vector
newbie here, in order to help sort out problems in my C++ project, I am compiling with the -Weffc++ option in g++. It's giving me hundreds of warnings about "warning ... should be initialized in the member initialization list" Is this really necessary seeing as it will a) take a bit of time to write them all in, and b)...
You can do this the way you did it, but there is no point -- the default constructor does exactly the same job. It is better to use initializer lists, but if it leads to unreadable or unnecessarily complicated code, it's perfectly fine to initialize (to be more precise, reset them from their default values) the member ...
6,942,791
6,942,921
How to convert a void * to CString
Not much of a C++ developer and the multiple ways to handle strings always confuses me. int Mine_SSL_Read(SSL* ssl, void* buf, int size) { int length = Real_SSL_Read(ssl, buf, size); CString msg = ??? } However I need to write a hook for SSL_Read function (OpenSSL) and that requires some C++ code. I need to c...
Assuming the void* is simply one-byte (ASCII or similar) characters: If you know it is NULL terminated, you can simply cast it: // ASCII CString msg = reinterpret_cast<char*>(buf); // UNICODE CString msg = reinterpret_cast<wchar_t*>(buf); If it is not NULL terminated, or you don't know that fact, then you have to cop...
6,942,887
6,943,026
How to generate doxygen block for an existing method?
I remember in the days when I was developing in Java, I could hit a set of keys in Eclipse or IDEA and get a Javadoc block for the method I was in. It would already contain the @param for the parameters and so on. I am looking for the same thing for doxygen (with C++). I use Eclipse but I am open to any tool that coul...
It was so simple that I didn't see it... Put the cursor above a function and enter /** when you hit return Eclipse will fill in the doxygen comments.
6,943,055
6,943,255
Initialize ref. field with ref. parameter: Is a copy made?
I am wondering if a copy is made in the following situation, or if both references will point to the same object. Consider an class with a single const ref field which is initialized from const ref parameter: class Foo { public: Foo(const vector<double>& the_doubles) : my_doubles(the_doubles) {} private: const ve...
A reference merely introduces an alias for an existing name (or, sometimes, value). Consider: int a = 42; int& b = a; b is now an alias for a. If we furthermore write int& c = b; then c is an alias for b and hence in turn for a. The same applies in your situation: no copy is ever made.
6,943,124
6,943,198
C++ Getters-Setters in Implementation File
I'm relatively new to C++ and I think that my question may be understood best by example. In my header file, suppose I have class myClass{ public: double getVar1(); void setVar1(double newVar1); void copyVar1(myClass* dat); private: double var1; }; In my implementation .cc file...
Best practices? Overload the assignment operator instead of writing a method. myClass & myClass::operator=(const myClass & dat) { var1 = dat.var1; // or dat.getVar1() return *this; } As for using the field or calling a setter... it's all a matter of personal taste. If your getter has some side effect, then you p...
6,943,229
6,943,272
C# equivalent of C++ vector, with contiguous memory?
What's the C# equivalent of C++ vector? I am searching for this feature: To have a dynamic array of contiguously stored memory that has no performance penalty for access vs. standard arrays. I was searching and they say .NET equivalent to the vector in C++ is the ArrayList, so: Do ArrayList have that contiguous memory...
You could use a List<T> and when T is a value type it will be allocated in contiguous memory which would not be the case if T is a reference type. Example: List<int> integers = new List<int>(); integers.Add(1); integers.Add(4); integers.Add(7); int someElement = integers[1];
6,943,262
6,943,480
What's a better way to detect negative numbers without using a literal?
Normally to detect a negative number, you just do if(x < 0) .... But what's the best way to do this without the hard-coded literal? It's not the value that I need to avoid, it's the datatype. I am looking for something in the style of <algorithm>. I have the following solution, but is there a better way? Something tell...
What's wrong with if (x < T(0)) ? Since you are seemingly interested in numeric types, a very natural requirement for such types is that they provide a constructor which takes a fundamental type (int, or double). I find it more natural that default construction, which may not exist, or have different semantics (undefi...
6,943,284
6,943,452
How to set default for a vector in a method
I'm having a scenario where I need to add a vector as an input/output [reference]parameter to existing legacy code. And in order to avoid any errors, I need to make it a default parameter. Could someone please suggest how to add a vector as a default parameter to a method. I'm actually dubious if this is possible. Als...
I suggest overloading the method: void foo(double otherParameter); void foo(double otherParameter, std::vector<int>& vector); inline void foo(double otherParameter) { std::vector<int> dummy; foo(otherParameter, dummy); } An alternative design, which explicitly says that vector is an option in/out parameter, ...
6,943,569
7,054,600
LMAX's disruptor pattern: is there a port to C++?
There are open source Java and .NET versions of LMAX's Disruptor pattern, as described in the video LMAX - How to Do 100K TPS at Less than 1ms Latency. Here is more links to information on the Disruptor pattern. Is anyone aware of a port of the Disruptor pattern to C++, either finished or in beta? Update Apparently oth...
Yes, there is already a functional C++ port. See http://www.2robots.com/2011/08/13/a-c-disruptor/.
6,943,619
6,943,669
What does static mean when applied to a class at namespace scope?
I know that static at namespace scope means "internal linkage". Now consider the following code: static class Foo {} foo; Does the static apply to Foo, foo or both?
It applies to the variable declared after the class definition. In C++, there is no such thing as static class. There are only static objects and static functions.
6,943,805
6,944,127
Are moved-from objects required to be destructed?
If I move-construct a from b, is it still necessary to destruct b, or can I get away without doing so? This question crossed my mind during the implementation of an optional<T> template. Excerpt: ~optional() { if (initialized) { reinterpret_cast<T*>(data)->~T(); } } optional(optional&& o) : initial...
Yes, it is still necessary to destruct b. A moved from object is a valid, constructed object. In some cases, it may even hold resources that still need to be disposed of. In generic code such as you show, T may not even have a move constructor. You may invoke a copy constructor instead in this case. So you can def...
6,943,829
6,943,924
Reading Values from fields in a .csv file?
Yesterday I made a small script with some help to read .csv files. I though I found a way to read the first value and store it, but for some reason it stores the last value instead. I store what I thought should be the first value under value1, and re-display it to make sure it displays properly and is in fact being st...
Your error seems to be in pure code formatting. while (myfile.good()) There is no {} after the loop. So only next line is repeated. The following code is executed after reading of the whole file. cout << string ( value) << endl; Thus value stores the last line of the file.
6,943,892
6,944,997
Difference in memory layout of pointer to base and pointer to derived object
If I have the following classes: class A { public: A(int val) : m_valA(val) {} private: int m_valA; }; class B : public A { public: B(int val) : A(0), m_valB(val) {} private: int m_valB; }; B* pb = new B; if I have a function which takes a A*, eg: void func(A* pVal) {} and pb is passed to this funct...
Doesn't a pointer point to the beginning of the object? In which case how will the two pointers be different? If you pass a pointer to a B object to func(A* pVal), then inside the func() implementation the pVal pointer will point to the A sub-object part of the B object. It's unspecified whether they will be at the ...
6,944,014
6,944,305
C++ Multiple inheritance and templates
As we all know, C++ allows multiple inheritance. Context I'm implementing a processing network where some processing nodes are link between each other to exchange different data with a sort of modified Observer pattern. A node which can send a certain type of data is a "DataSender" and then extends this abstract class....
It's not pretty, but you can tell which base class' function you intend to call node->DataSender<Text>::sendData(<my argument>);
6,944,288
6,946,500
Memcpy of native array to managed array in C++ CLI
Am I doing this right? I get a pointer to a native array and need to copy to a managed array. Use memcpy() with a pin_ptr. unsigned char* pArray; unsigned int arrayCount; // get pArray & arrayCount (from a COM method) ManagedClass->ByteArray = gcnew array<Byte,1>(arrayCount) pin_ptr<System::Byte> pinPtrArray = &Manag...
You are doing it almost right: pin_ptr<Byte> pinPtrArray = &ManagedClass.ByteArray[ManagedClass.ByeArray->GetLowerBound(0)]; Marshal::Copy is not safe and not as fast. Always use pinned pointers in managed C++. Edit: If you want to, you can check the length to make sure the memcpy won't exceed the bounds first, e.g.:...
6,944,419
6,944,618
const ints as Message IDs = Recompile Everything
I'm hoping for confirmation of what I just told someone. We have a large software project that is divided out into several libraries (.so). The message definitions are all in one library with a set of .h files for the declarations. The message ids are in the .h as const int (see below). One uses the id to subscribe/pub...
You are correct. A better design (at least in terms of mitigating maintenance nightmares like this one) would be to declare these ID objects extern in the header, and define them once in the library source. Then you'd just have had to drop in the new library.
6,944,443
6,945,140
C/C++: Why the localtime display incorrectly in respect of its timezone?
I found that a strange behavior on C language recently but no idea why this happen. when I use setenv(), set the TZ to GMT+1. the output of the local time will be one hour less than UTC time. (see the output) actually, when I set the TZ to GMT-1. the output of the local time will be one hour more than UTC time. This do...
It is indeed very confusing, but not a bug. POSIX specifies this : If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west (which may be indicated by an optional preceding '+' ). So, it's basically the reverse of what you might expect.
6,944,465
6,944,600
How can I use a few C++ files in my project without compiling every file as C++?
I have a project with a base view controller class, that is inherited by about 25 other view controllers. Now I need to use a bit of core audio in that base class, so I'm integrating an Audio class (adapted from Apple's aurioTouch example project) that uses C++. The base class imports the Audio class's header, and then...
It should actually suffice to rename the .m file that uses C++ functionality to .mm. You have to make sure that you don't include any C++ headers in the header file of your class, otherwise the other non-C++ classes will go berserk trying to include your class's header file.
6,944,486
6,946,286
DirectDraw Blt function parameters
Just a simple blt function: RECT dstRect = {dstL, dstT, dstR, dstB}; RECT srcRect = {srcL, srcT, srcR, srcB}; HRESULT hr = _surface->Blt(&dstRect,source,&srcRect,DDBLT_WAIT, NULL); My question is: let's say I have a buffer of width 'w', I specify dstL = 0. What should be dstR ? w or w-1 ? meaning is dstR included or ...
DirectDraw rectangles are like GDI rectangles in that they cover the area up to (but not including) the right column and bottom row. So it should be w. Reference: http://msdn.microsoft.com/en-us/library/aa911080.aspx : The RECT structures are defined so that the right and bottom members are exclusive: right minus le...
6,944,524
6,944,556
Inheritance C++ issue when assigning base class to sub class
This may be a silly question about inheritance, but it does not make much sense on why I am not allowed to do this. The base class I am inheriting from is std::string: class A : public std::string When I use class A, I want to do this: A text; std::string str = "hello"; text = str; The compiler complains that there i...
You cannot inherit assignment operators, they are given special treatment. You can use using to bring them up from the base class. Also, it's horrendously bad to inherit from Standard-provided classes, except iostream.
6,944,619
6,944,793
How to signal yourself (same PID)?
OK, so this may be an odd situation but please bear with me. I have a Python program which calls up a C++ class via a SWIG interface. I came to a point where I must asynchronously signal (to update a status) the Python code from the C++ library. Originally I had inefficient busy loops which polled a flag. I wanted to r...
Signals are not the right tool for the job here. Normally, this would be a job for inter-thread synchronization primitives, such as the locks from the thread module the Event objects from the threading module However, it's not easy to manipulate Python thread locks from C++. So I would use the old-fashioned, but ve...
6,944,677
6,945,293
Cite/Reference OpenMP in a Paper
I am writing a paper and implemented an algorithm using OpenMP. Since Visual Studio directly supports OpenMP, am I required to cite OpenMP in my paper?
I would cite it if only for clarity about the version used, and to point the reader to more information. My suggestion would be to cite the API reference for the OpenMP specification of the appropriate version, using whatever style your journal uses for citing manuals or technical reports. If you don't know what ve...
6,944,685
6,944,794
OpenAL's AL/al.h not found on Mac OS X Lion with XCode 4.1
I've created a project in XCode and added the OpenAL framework. Still the compiler can't find AL/al.h when i try to include it. Where do I add the include directory for OpenAL? edit: Sorry I forgot to add: I'm using C/C++
Use this: #import <OpenAL/al.h>
6,944,912
6,945,032
C++ editor of choice for Java people?
We are a group of students trying to start up a C++ project. We have the most experience in Java because that is what were taught and I personally have experience in C, so this is going to be a learning experience for all of us. I am wondering which editing tool would be a good choice. We also have access to all of the...
I guess you never know until you try them all and pick whatever you like the most. Here are some IDEs for C++ that you can pick from (in the order of my preference): Emacs Qt Creator vim CodeBlocks One particularly good IDE, but works on Mac only, is Xcode. Here are some Java IDEs that support C++: Eclipse NetBeans ...
6,944,943
6,945,153
How could a textfield respond on <Enter>
I have some problems to respond on a event like "Enter". I have a dialogbox with a CEdit field, where the user could enter some stuff. How could I respond, if the user press "Enter" in the textfield? I will submit the content in the textfield to a function, if the user press the "Enter" key.
If you're using the Visual Studio GUI editor, you can select the textbox, view the properties window, and set "Want Return" to "true". If you're creating the CEdit via code, you can pass ES_WANTRETURN to your CreateWindowEx function. Also, this is a duplicate of How can I handle the Return key in a CEdit control? which...
6,945,012
6,946,731
passing compiler flags to boost libraries (such as Thread) which require compilation
So I know that the boost libraries are primarily header-only but there are a few which require compilation, for example Boost.Thread. In Darwin, how do I compile these and pass the -m32 flag so they can be compiled into a 32-bit (i386) binary? There's this Jamroot thing which I've never heard of and I am not sure at ...
To specify what architecture to compile for, specify the architecture feature when invoking b2. To specify compiler options that don't already have built-in features, specify the cxxflags feature when invoking b2. To specify linker options that don't already have built-in features, specify the linkflags feature when in...
6,945,169
6,945,331
Refactoring advice: How to avoid type checking in this OO design
I'm looking for advice on refactoring to improve my class design and avoid type checking. I am using the Command design pattern to construct a menu tree. An item in the menu could be of various types (e.g., an immediate action [like "Save"], a toggle on/off property which displays with check/icon depending on its state...
IMO, the refactoring starting point would be these statements: 1. m_pos.push_back( MenuPlusIter( m_menu, m_menu->m_items.begin() ) ); 2. m_pos.push_back( MenuPlusIter( submenu, submenu->m_items.begin() ) ); The fact that the same kind of statement repeat itself is, IMO, the sign for the need to refactor that. If yo...
6,945,304
6,945,329
How to return true or false to for_each in this case?
In my code below I want to inform for_each if I find the item? How do that? #include <list> #include <algorithm> #include <functional> using namespace std; class widget { public: widget(int id) : m_id(id) {} private: int m_id; }; class findwidget { public: findwidget(widget* p) : m_widget(p) {} bool o...
The solution is : Dont use std::for_each. Use any from the following (whatever suits your situation): std::find std::find_if std::find_first_of Example of std::find: if(std::find(m_widgetList.begin(), m_widgetList.end(),pi) == m_widgetList.end()) m_widgetList.push_back(pi); Note if you use std::find, you don't ...
6,945,344
6,945,424
Setting a bool if a string is present
I need to set a boolean based on whether a string is present in my data dictionary, with a structure of: std::map< string, foo > dd If the string I'm looking for is there, then the boolean is true, and vice versa. Can someone help me with how do I do this in C++? Thanks.
Suppose data dictionary is std::map< string, foo > dict; bool const word_present( string str_word, std::map< string, foo > &dict) { return (dict.find( str_word ) != dict.end()); }
6,945,561
6,947,093
Open BMP to an array using Visual C++ and OpenCV 2.1
I open an image with: IplImage *img = cvLoadImage("C:\\foo.bmp",-1); And now I want to put this image to three 2D arrays. unsigned int r[img->width][img->height]; unsigned int g[img->width][img->height]; unsigned int b[img->width][img->height]; This doesn't work, because I get "expression must have a constant value"...
cvSplit splits an image into single-channel arrays (documentation).
6,945,700
6,945,761
Implementing virtual methods in other parent-branch than they are declared in
I have the following code: #include <iostream> class Grandma { public: virtual void foo() = 0; }; class Mom : public Grandma{}; class Dad { public: void foo() { std::cout << "dad's foo impl"; } }; class Me : public Mom, public Dad{}; int main() { Me m; m.foo(); } and getting : cannot instantiate a...
There is no relation between Dad class and Grandma class. Dad and Grandma are two completely different classes. Given that the method in Dad is not considered as an implementation of the pure virtual method in Grandma and has to be implemented in the Me class. When you derive from an Abstract class(class containing atl...
6,945,773
6,945,846
Run MFC program on Linux
I have a rather large MFC based program. I have been tasked to get it running on Linux. I have explained that this will require a re-write of the program either into straight C++ with STL (more work), or into Qt/C++ (less work). I am now told that I need to write wrappers to get every MFC class working in Linux and ...
If you don't want a full rewrite, you could try compiling against Winelib. Most things should just work and then since you have the source, you can work around the parts that don't.
6,945,998
6,946,226
Copy from const char* to a byte array C++/c# interop Marshal::Copy
I'm trying to send an image from C++ to C# with an interop (marshaling) of C++ managed. image->getStream() return a const char* from a string. I'm having exception with my Marshal::Copy function. An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted...
I wouldn't use Marshal::Copy. Since you have the array locally, why not just pin it and use memcpy? pin_ptr<Byte> ptrBuffer = &byteArray[byteArray->GetLowerBound(0)]; You can now call memcpy to ptrBuffer. When the scope ends the pinning is automatically undone.
6,946,012
6,946,048
Should I specialize or overload?
Suppose I have a function template: template <typename T> std::string foo(const T& x) { return some_computation_involving(x); } If x is already a string, I just want to pass it back verbatim. Should I specialize the function template? template <> std::string foo(const std::string& x) { return x; } Or should I...
Prefer overload over function specialization, says Herb Sutter. He explains this in his articles: Why Not Specialize Function Templates? Template Specialization and Overloading
6,946,079
6,946,495
Is there an async way of knowing a file has changed?
I would like to asynchronously monitor a file for any changes. That is I would like to have a call back (possibly from kernel) in my program when the file has been modified/deleted. The file is just a plain text file. I know one can do this using a polling mechanism, but I am looking for an event based solution. I read...
Inotify was merged to the Linux kernel way back in 2005, so unless you're in a very old system, you should be able to use it out of the box. I don't think there exists a POSIX compliant solution for this. Mac OS X has FSEvents. Also check the man page for inotify. EDIT: Don't know about your constraints and/or require...
6,946,217
6,946,261
How to access the contents of a vector from a pointer to the vector in C++?
I have a pointer to a vector. Now, how can I read the contents of the vector through pointer?
There are many solutions, here's a few I've come up with: int main(int nArgs, char ** vArgs) { vector<int> *v = new vector<int>(10); v->at(2); //Retrieve using pointer to member v->operator[](2); //Retrieve using pointer to operator member v->size(); //Retrieve size vector<int> &vr = *v; //Create a ...
6,946,340
6,946,421
Invalid address specified to RtlValidateHeap error with templated class
I have this class: class HIDValue{ private: void* mValue; UINT mSize; HIDElement mElement; public: HIDValue() { mValue = 0; mSize = 0; } template <class T> HIDValue(T pValue, HIDElement pElement) { mElement = pElement; mValue = 0; setValue(pValue);...
Don't use void*. You want to use Boost.Any or Boost.Variant (latter if the set of allowed types is to be restricted). Don't use memcpy. It's likely to not work correctly with UDTs. Don't use C-style casts. The error is most likely related to the fact that you're deleting void* instead of T*.
6,946,584
6,960,447
Where is spellout rule(RuleBasedNumberFormat) of ICU library?
I use ICU to spell out number to string like : "one hundred and thirty-four" // 134 using en_US spellout the out of box spellout rule for my locale(vi_VN) is seem wrong 15 become "mười năm" instead of "mười lăm" and many more wrong so I need to edit the rule but don't know where to change
ICU data comes from CLDR. Please file a bug in CLDR, http://cldr.unicode.org - If you have trouble, let me know. Ideally you would download CLDR source and rebuild ICU data from CLDR. CLDR uses a slightly different format for rules. But, if you want to make a patch, you can download ICU from Subversion, and the data...
6,946,855
6,947,716
Adding function to string class
I understand that inheriting from std::string class is a poor idea, but was just trying to add a custom function to string class for a dummy assignment, using inheritance. I want to call my function as 'add' and when I do str.add(str1,str2); it should append str1 at the beginning of the string and str2 at the end of t...
Be sure you declare your function in public section of class. Maybe you would love composition over inheritance ;) class MyString { std::string m_string; // do not inherit just composition it public: explicit MyString(const std::string& str) : m_string(str) ...
6,947,038
6,952,370
Do the C++ operators new and new[] throw std::bad_alloc on Android?
Will any exception be thrown when an attempt to allocate memory fails? I just recently learned that exceptions are supported in Android.
I downloaded the ndk and found this in the docs folder, CPLUSPLUS-SUPPORT.HTML . I. C++ Exceptions support: The NDK toolchain supports C++ exceptions, since NDK r5, however all C++ sources are compiled with -fno-exceptions support by default, for compatibility reasons with previous releases. To enable it, use the ...