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 |
|---|---|---|---|---|
4,444,853 | 4,444,879 | In C++, is it possible to use a string literal as a macro name? | Here's my scenario: I have a set of source files that I'd prefer to not modify, but I'd like to replace some of the string literals with other values. Here's an example:
#define "oldString" "newString"
| No, that's not possible. If you had already used macros in place of the strings, it would have been simple to change the macro definition to use a different string -- better late than never, you might want to do it now.
|
4,444,930 | 4,446,836 | C++ exception in WSA listen() call | I'm getting the same error as this user. My code is very similar.
Socket Exception: "There are no more endpoints available from the endpoint mapper"
I tried all that he did and my listen() call still generates an exception but no error code is reported. WSAGetLastError() also does not give me any errors. It seems to pa... | The answer in the cited thread stating that you should ignore the first-chance exception is correct. This is not a sockets problem and it certainly doesn't require fiddling with registry entries, or SO_LINGER. Your backlog will be adjusted upwards to 50 so you may as well set it to that.
|
4,445,108 | 4,446,189 | How can I convert a native (NT) pathname into a Win32 path name? | I'm working on reporting some information gleaned from native system APIs. (I know this is bad.... but I'm getting information that I can't get otherwise, and I have little issue with having to update my app if/when that time comes around.)
The native API returns native pathnames, as seen by ob, i.e. \SystemRoot\System... | We do this in production code. As far as I know there is no API (public or private) that handles this. We just do some string comparisons with a few prefixes and it works for us.
Apparently there is a function named RtlNtPathNameToDosPathName() in ntdll.dll (introduced with XP?), but I have no idea what it does; I wo... |
4,445,176 | 4,445,207 | Using base class methods to initialize derived class members | Is it legal? If so, do you consider it as good coding practice?
I want to do something like this (nonessential details are not shown):
class ItemStorage {
int size() const;
};
class SpecialStorage : public ItemStorage {
public:
SpecialStorage (...) : ItemStorage(...), items(ItemStorage::size()) {...}
private:... | The general rule is that, during initialization, you must not access uninitialized parts of the object. As ItemStorage is already initialized when items gets initialized, calling size is indeed fine.
Even if size was virtual, and even if it was overwritten, it still would be fine: it would just call the base version (i... |
4,445,203 | 4,445,241 | Protected data members and data functions | when i declare a protected data member in a class that means its not accesible to the outer world but the derived class. My question is
will it be accesible to a class that is derived from the derived class?
| Yes, protected data members are accessible all the way down the inheritance hierarchy.
Protected data is usually better avoided. An alternative is to write protected methods that access the private data. This keeps the data encapsulated within a single class. It also makes it easy to set a breakpoint for changes to th... |
4,445,303 | 4,445,325 | `short int` vs `int` | Should I bother using short int instead of int? Is there any useful difference? Any pitfalls?
| What Ben said. You will actually create less efficient code since all the registers need to strip out the upper bits whenever any comparisons are done. Unless you need to save memory because you have tons of them, use the native integer size. That's what int is for.
EDIT: Didn't even see your sub-question about const. ... |
4,445,332 | 4,445,341 | How do you "Drop down to Assembly"? | Sometimes when I'm reading stuff, usually in C++ / Ojective-C, I see people say that for speed increase (etc), if necessary, you as the programmer can drop down to Assembly. How do you actually do that? Do you write some Assembly and compile it, and then... ? How do you link the two together? Do you have to link the ob... | It differs by compiler, but in Visual C++:
__asm
{
int 3;
}
Which triggers the debug-interrupt. Everything enclosed in that __asm block is, well, assembler.
|
4,445,418 | 4,446,085 | How to add additional libraries to Visual Studio project? | Allergro is an open souce C++ addon library for graphics manipulation. How do I add this library to my compiler?
The instructions don't work for me as I have Windows 7. I don't know if the OS matters. I have the Visual Studio Express Edition. The library is a .dll file. How do I add it to my projects?
| For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.
Next open Configuration Properties and then Linker.
Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,
Linker -> Input you'll add the actual library file... |
4,445,485 | 4,445,503 | C++: Should I use constants as much as possible in function arguments? | Or is it pointless?
Thanks.
Edit: I have seen char arrays often constant in function arguments... is there a reason for that?
Edit 2: Nevermind my edit. See 'In silico's answer.
Edit 3: TO CLARIFY, this is an etiquette question, not a "what is going to happen" question. I understand what const does.
| Use const whenever you are dealing with references (&) and do not intend to change the argument. This is, to clearly identify them as input arguments. Performance should be better, too. And thousands of other reasons. It is probably useless on arguments handed over by value, but doesn't hurt either.
|
4,445,509 | 4,445,734 | C++ memory alignment question | A line of code is worth a thousand words :) Here is my problem:
/* Platform specific 16-byte alignment macro switch.
On Visual C++ it would substitute __declspec(align(16)).
On GCC it substitutes __attribute__((aligned (16))).
*/
#define ALIGN_16 ...
struct ALIGN_16 A {...};
A* ptr = new A;
A* ptr2 = new A[20];... | Is there any guarantee of alignment of address return by C++'s new operation?
In other words, you can use the standard to justify your assumption that it should work, but in practice, it may blow up in your face.
Visual C++ 6 did not align doubles allocated via new properly, so there you go.
|
4,445,524 | 4,445,549 | measure time difference | I want to measure in milliseconds how much time there is between when I start my application and another time, for example 16:00 o'clock. What is the best way to do this?
I looked around "clock" function but it's not what I need.
Operating system: Win NT and above
| Look up gettimeofday for POSIX systems, and timeGetTime for Windows.
Edit: Seems the OP was asking for code to compare current time/date against another time/date. The following snippet demonstrates how to get current date and time on Windows:
#include <Windows.h>
#include <stdio.h>
void main()
{
SYSTEMTIME ... |
4,445,593 | 4,445,615 | C++ partial template specialization syntax | for primary template:
template<typename A, typename B> class MyClass {...
with template specialization, what is the difference between
template<typename A, typename B> class MyClass<int, float> {...
and
template<> class MyClass<int, float> {...
| template<typename A, typename B> class MyClass<int, float> {... should be not allowed. Indeed, if you specify the formal parameters A and B, your template should be using them.
The second case is just normal: you say that you are making specialization with no "free" parameters.
An intermediate case could be
template<ty... |
4,445,654 | 4,445,772 | multiple definition of template specialization when using different objects | When I use a specialized template in different object files, I get a "multiple definition" error when linking. The only solution I found involves using the "inline" function, but it just seems like some workaround. How do I solve that without using the "inline" keyword? If that's not possible, why?
Here is the example ... | Intuitively, when you fully specialize something, it doesn't depend on a template parameter any more -- so unless you make the specialization inline, you need to put it in a .cpp file instead of a .h or you end up violating the one definition rule as David says. Note that when you partially specialize templates, the pa... |
4,445,706 | 4,445,841 | Post-increment and Pre-increment concept? | I don't understand the concept of postfix and prefix increment or decrement. Can anyone give a better explanation?
| All four answers so far are incorrect, in that they assert a specific order of events.
Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.
So.
For the built-in C++ prefix operator,
++x
increments x and produces ... |
4,445,720 | 4,445,938 | How to plot graphs in Gnuplot in Real time in C++? | I'm trying to plot a graph in real time using GNUplot and C++.
Does anyone know of any good libraries that does this?
Thanks
| gnuplot supports input via pipes (on windows, there's a separate executable for this, pgnuplot). Then your program can send new commands to gnuplot, such as replot, just as if you were typing them into the gnuplot interface directly.
How you set up the pipe connection and write to the sending end of the pipe from your... |
4,445,844 | 4,445,855 | Why do I get invalid data in my CString formatted using Format()? | LRESULT CFlashWnd::OnScannerProgress( WPARAM wParam, LPARAM lParam )
{
ScannerProgress *pEvent = (ScannerProgress *)wParam;
CString scannerAreaText = _T("");
scannerAreaText.Format(_T("<B>Scanning%3A</B> <font face='Arial' size='10'>%s</font>"), pEvent->pszScanner);
CString scanProgressText = _T("");
... | I'm not sure but you should double check the %3A in your format strings. The percent sign, as you know, indicates a placeholder.
|
4,446,093 | 5,161,989 | Memory debugging tools for Android NDK C++ code | Does anyone know of memory debugging tools (like Valgrind) for native C++ code under Android NDK?
| We have a project that uses quite a bit of native code. As hinted in one of the comments for the question, the best approach is to test that code on another environment.
We have a separate project that builds in Linux and calls the C/C++ functions we use in our Android code. Once you are at that point, all the nice too... |
4,446,151 | 4,446,495 | search for "servers" and shortist path | I can't come up with a solution for this problem.
I have list of components(servers):
2 - 8
8 - 3
3 - 9
.....
so this mean that theese servers are linked and you can visit all servers starting from any other - all are linked through other servers.
The question is how to find out which one/ones servers has the shortest ... | What you want is what is called the center of the graph. Your algorithm text probably discusses it along with all pairs shortest path algorithms (Floyd-Warshall and Johnson's algorithm). Here is a brief discussion
|
4,446,181 | 4,446,429 | PATH Environment Variable has no Effect? (VS2010) | From what I can tell from this MSDN walkthrough, the PATH environment variable should point to the location of a DLL when the DLL isn't in the same directory as the source.
I have set this variable through Property Pages > Configuration Properties > VC++ Directories > Executable Directories (which does correspond to th... | The PATH directory that the "Executable Directories" page refers to are the directories that are searched for compiling your code, not the directories that are searched at run time to execute your program.
If you don't want to set your path every time in your command prompt, you can update your PATH environment variabl... |
4,446,246 | 4,446,572 | How do I force the size of a 'bool' under GCC | I'm currently porting some code from another platform and bools on the new platform are 1-byte sized. This is breaking our loading code as the values are stored as 32-bit values. Furthermore, speed is a critical issue on our platform and we would like to use 32-bit bools as the processor runs at 32-bits natively and re... | You could create your own class that uses int32_t internally but behaves like a bool. It does mean you'd have to rename the fields you specifically want to use that type, which is more work but affords better control and isolation, and you can still use real bools elsewhere. I'd personally prefer that to any #define ... |
4,446,484 | 4,446,852 | A line-based thread-safe std::cerr for C++ | What is the easiest way to create my own std::cerr so that it is line-by-line thread-safe.
I am preferably looking for the code to do it.
What I need is so that a line of output (terminated with std::endl) generated by one thread stays as a line of output when I actually see it on my console (and is not mixed with some... | This:
#define myerr(e) {CiriticalSectionLocker crit; std::cerr << e << std::endl;}
works on most compilers for the common case of myerr("ERR: " << message << number).
|
4,446,497 | 4,446,527 | Does Firefox 4 implement any addon architectural changes | There is an open source firefox addon that I have attempted to test with firefox 4. The installation fails with an error advising that the addon is incompatiable with firefox 4.
From the best of my research I have determined that this is because the install.rdf file contains the following code.
<em:minVersion>1.5</em:... | You should start with this guide at MDC.
|
4,446,620 | 4,446,911 | Returning Strings from DLL Functions | For some reason, returning a string from a DLL function crashes my program on runtime with the error Unhandled exception at 0x775dfbae in Cranberry Library Tester.exe: Microsoft C++ exception: std::out_of_range at memory location 0x001ef604...
I have verified it's not a problem with the function itself by compiling the... | Since your error message indicates you're using Microsoft C++ I'll offer an MS specific answer.
As long as you compile both the EXE and the DLL with the SAME compiler, and both link the the SAME version of the runtime DYNAMICALLY then you'll be just fine. For example, using "Multi-threaded DLL" for both.
If you link a... |
4,446,709 | 4,447,173 | Pass unicode string from VB.net to C++ dll | I have tried a lot of things but I cannot get this to work. I can pass and receive ordinary strings (char*) to C++, but I cannot receive Unicode strings (w_char_t *) in C++.
Here are some bits of the code on c++
__declspec(dllimport) int __stdcall readFile(const w_char_t *file_path)
on VB.net
Public Declare Function ... | Public Declare Unicode Function readFile Lib "MyDll.dll" Alias "_readFile@4" (ByVal file_path As String) As Integer
Also, your C++ code has dllexport not dllimport, right?
|
4,446,731 | 4,446,787 | When does a thread exit? | I have code in Qt that goes like this:
void doSomeStuff()
{
...
if(blah blah)
someObj.start();
...
}
and then someObj.run():
void someObj::run()
{
blah blah blah, do some stuff
doSomeStuff()
}
What I was intending is for the new thread created at someObj.start() to end and then the functio... | doSomeStuff() is currently called when the thread is exectured ego the thread will still be alive otherwise it would not be called at all ^^ only when doSomeStuff is finished then your Thread will exit
By glancing at the QT doc (I'm no Qt expert) I found
http://doc.qt.io/qt-5/qthread.html
bool isFinished () const
y... |
4,446,968 | 4,447,405 | Template specialization, multiple defined symbols | I know I'm missing something easy here but I've got a templated member function of a class which I've specialised.
class MyClass
{
template<typename T> T GetTFromVariable(shared_ptr<TOtSimpleVariable> v, string s);
}
template<typename T>
T MyClass::GetTFromVariable(shared_ptr<TOtSimpleVariable> v, string s)
{
... | As Alf noted, the full specialization is no longer a template.
However, I am not sure it has to be defined inline.
You should also be able to split the declaration and definition.
I.e. In your header have:
template<>
int MyClass::GetTFromVariable<int>(shared_ptr<TOtSimpleVariable> v, string s);
and in the implementat... |
4,447,008 | 4,447,362 | Do additional function/method definitions increase a program's memory footprint? | In C++, does defining additional methods or functions that don't get used result in a larger memory footprint or slower execution speed?
Basically, I have several utility debugging methods in a class, none of which are required for the normal use of the class. Would it make a difference in terms of memory footprint or ... | Note that most OSes don't always keep all the code in the memory. Since the code is constant data the OS can always load it from file on demand like it would load dynamic data from swap. But it doesn't mean that unused code is never loaded since the OS loads it not by separate methods but by pages. In other words, it i... |
4,447,009 | 4,447,060 | What does the "&0xFFFFFFFF" do in this HIDWORD macro | I needed the HIDWORD macro for a program I'm making and found this one here: http://gnuwin32.sourceforge.net/compile.html
What I'm confused about is why there is a &0xFFFFFFFF at the end of it?
#define HIDWORD(l) ((DWORD)(((DWORDLONG)(l)>>32)&0xFFFFFFFF))
How does that modify the output of this macro in any way?
| I don't think it has any real effect - the (DWORD) cast that
the final operation of the expression will force the result to 32 bits anyway.
The (DWORDLONG) cast forces the shift operation to act on an unsigned value, so no 'sign bits' will be shifted into the intermediate result. However, since the operand could be 64... |
4,447,391 | 4,447,478 | reason for memory leakage in C C++ | what are the reasons for memory leakage in C C++
(except the usual allocating memory and forget to deallocate it)
| If an exception is raised between allocation and deallocation, memory leak will occur.
void f1() {
int* ptr = new int;
// do something which may throw an exception
// we never get here if an exception is thrown
delete ptr;
}
Each time f1 terminates with an exception, 4 bytes are leaked (assuming int ... |
4,447,486 | 4,447,508 | Is it possible to partially deallocate memory? | In C (or C++) I'm wondering if it's possible to partially deallocate a block of memory.
For example, suppose we create an array of integers a of size 100,
int * a = malloc(sizeof(int)*100);
and then later we want to resize a so that it holds 20 ints rather than 100.
Is there a way to free only the last 80*sizeof(int) ... | You can use realloc, but you should definitely consider using STL containers instead of manually allocating memory.
|
4,447,816 | 4,447,843 | QT4 / C++ : no such signals problem | I have a small program to show devices and capture any packets, with GUI.I use QT Designer and Netbeans 6.9 to draw the GUI,but the problem comes when i try to implement a signal/slot.Basically when a combo box is selected, a QlineEdit would show a MAC address of the selected device.
The error:
Object::connect: No suc... | QComboBox does not have a selectedDev(int) signal. The documentation provides a handy list of signals and slots for every Qt class: QComboBox documentation
You have defined the selectedDev(int) signal in your MainGUI class so your call to connect should be like this: (the arguments to connect are: signal source, signal... |
4,447,827 | 4,447,894 | Why does ostream_iterator not work as expected? | Needless to say any more than the following code:
#include <utility>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
typedef pair<char, char> PAIR;
ostream& operator <<(ostream& os, const PAIR& r)
{
return os << r.first;
}
int main()
{
vector<PAIR> coll;
cout << coll[0]... | The problem is that the name lookup does not find your operator<<(ostream& os, const PAIR& r). The code that tries to invoke the operator<< is in somewhere inside the ostream_iterator<> which is itself inside the std namespace. The name lookup looks around for the right function inside ostream_iterator<> and the std na... |
4,447,980 | 4,448,004 | std::stringstream as parameter to a function | I have a std::vector<std::string> temp_results and I wish to use std::for_each to go through this vector and concatenate a string, so I concocted the following construction:
std::stringstream ss;
std::string res = std::for_each(temp_results.begin(), temp_results.end(), boost::bind(addup, _1, ss));
std::string addup(st... | If, by writing return ss.str; you intend to call the str member function from std::stringstream, then you are missing a pair of parenthesis :
return ss.str();
Also, your code probably won't do what you expect. If you want every call to addup to work on the same std::stringstream instance, you have to take it by refere... |
4,448,094 | 4,448,160 | Can we see the template instantiated code by C++ compiler | is there a way to know the compiler instantiated code for a template function or a class in C++
Assume I have the following piece of code
template < class T> T add(T a, T b){
return a+b;
}
now when i call
add<int>(10,2);
I would like to know the function that compiler creates for int specific version.
I ... | You can definitely see the assembly code generated by the g++ using the "-S" option.
I don't think it is possible to display the "C++" equivalent template code - but I would still want a g++ developer to chime in why - I don't know the architecture of gcc.
When using assembly, you can review the resulting code lookin... |
4,448,107 | 4,448,388 | Problems that can arise with Exception-handling | This question is inspired by this post: reason for memory leakage in C C++
What are the other kind for problem that can arise because of using exceptions?
I mean what are the problems that we should keep in mind while using exception handling
| Bjarne Stroustrup has made the chapter on exception safety (The C++ Programming Language, 3rd ed.) available.
Additionally you have to make sure that exceptions interrupting your functions mid-call will be harmless. If you use RAII (the generally recommended approach) to automatically release mutexes, for instance, yo... |
4,448,177 | 4,448,201 | Constructing std::string like an array | I want to construct a std::string object like an array:
std::string str("");
str[0] = 'A';
str[1] = 'b';
str[2] = 'h';
str[3] = 'i';
str[4] = '\0';
std::cout<<str;
But it doesnt print the string. What am i missing?
| Try
std::string (4, ' ');
instead of
std::string("");
basic_string's operator[] returns a reference to the specified character, but since your string is empty, it contains no characters.
|
4,448,236 | 4,462,030 | How could Qt apply style from an external Qt Stylesheet file? | I would like the users to be able to customize the default look of our applications by simply loading their OWN Qt Style-sheet files. How do we accomplish that? Can anybody give me a head start?
| Say the user have its stylesheet named stylesheet.qss and is located in the application folder.
You could load the style sheet when starting the application, using the -stylesheet argument :
myapp->stylesheet = stylesheet.qss;
But this require your user to know how to start an application with arguments.
What you coul... |
4,448,296 | 4,448,331 | Static variable resetting its value to 0 on it's own apparently | I have a base class called Component which has a number of classes derived from it. I want each class to have an integer associated with it (doesn't matter which component gets what value, as long as they start at 0 and are contiguous). I don't know how to do this directly, so in the same file as Component I added the ... | You've declared your identifier as static:
static unsigned int CIDCounter = 0;
which means each compilation unit will get its own copy of the variable. Instead you should declare it as extern in the header file:
extern unsigned int CIDCounter;
and initialise it in the implementation file
unsigned int CIDCounter = 0;
... |
4,448,570 | 4,448,624 | concatenate values in a while loop gone wrong | I have a boost::variant, which contains various types and I have a string which needs to look like this: type=D,S. The values in the variant are D and S respectively, the key is 'type'. It is a map<std::string, std::vector<variant> > where I'm now iterating the vector<variant> part
Now I first apply a static_visitor ... | The problem might be that, although v_accumulator is a class member, boost::bind copies its arguments by default. This means that ConcatValues is called on a copy of the helper, with its very own v_accumulator vector.
If you want a reference, you must use boost::ref :
boost::apply_visitor(add_node_value_visitor(
bo... |
4,448,598 | 4,448,686 | Why does "using namespace xxx" not take effect on template functions? | namespace ns1
{
template <class T>
void f(T)
{
cout << typeid(T).name() << endl;
}
};
using namespace ns1;
namespace ns2
{
void f(int)
{
cout << "int" << endl;
}
void test()
{
f(vector<int>()); // Error!
// Why not call ns1::f<vector<int>>(vector<i... | This has nothing to do with templates, but without name lookup.
This is what the standard says in 3.4/1 (name lookup) :
Name lookup shall find an unambiguous
declaration for the name (see 10.2).
Name lookup may associate more than
one declaration with a name if it
finds the name to be a function name;
the de... |
4,448,677 | 4,448,736 | Can a C program handle C++ exceptions? | I am developing C++ component dll that can be used by C or C++ applications.
The exposed dll functions are as follows
#include <tchar.h>
#ifdef IMPORT
#define DLL __declspec(dllimport)
#else
#define DLL __declspec(dllexport)
#endif
extern "C" {
DLL bool __cdecl Init();
DLL bool __cdecl Foo(const TCHAR*);
... | C doesn't have exceptions, therefore in general you should catch all exception and return an error code and/or provide a function that returns the information about the last error.
|
4,448,769 | 4,449,045 | How serialize a boost::function to send it in a message_queue | I am actually trying to serialize a boost::function using boost::serialize because I want to share it in a boost::interprocess::message_queue.
I only see one way to do that, it is to use the non-intrusive version of boost::serialize.
namespace boost {
namespace serialization {
template<class Archive>
... | It's not going to be possible immediately.
There are 2 problems I can think of:
pass the identity of the function
pass the context of the function (for example, if created using bind or with a lambda)
Neither is trivial, and neither can be done without instrumenting the code (think reflection / introspection).
What y... |
4,448,865 | 4,448,956 | C++ Reading a PDF file | I'm using the following code to read the content of a PDF file:
string document;
FILE * f;
f = fopen ( path , "rb");
unsigned char buffer[1024];
while(!feof(f)){
int bytes = fread(buffer,1,1024,f);
for(int i = 0; i < bytes; i++){
document += buffer[i];
cout << buffer[i];
}
}
fclose ( f );... | I don't see any errors in the way you read the file (the code actually works on my Linux box when I redirect the output to a file). Probably the issue is in the control characters that mess up with the console. Try to output to a file and compare with the input.
|
4,449,044 | 4,449,936 | Listing Unused Symbols | I want to remove dead code from a largish project and would like to start with unused symbols. Is there anyway to get the linker to list unused symbols that it has optimized out? I am using the GNU linker (LD) together with GCC.
Failing that, can any of the Binutils (readelf or objdump) perform the same function?
| Most compilers/linkers optimise out unused symbols. If you're running on a *nix system, you can try using the command "nm" on all the object files, filter it and sort it, to produce a list of all exported functions defined by those object files.
nm *.o | grep "^[0-9a-f]* T " | sed 's/^[0-9a-f]* T //' | sort -u > symbol... |
4,449,095 | 5,219,603 | How to catch exceptions with Qt platform independently? | I'm using boost::date_time in my project. When date is not valid it thorws std::out_of_range C++ exception. In Qt's gui application on windows platform it becomes SEH exception, so it doesn't catched with try|catch paradigm and programm dies. How can I catch the exception platform independently?
try{
std::string ts... | Adding answer from the comments:
aschelper wrote:
Is your Qt library compiled with C++
exception support enabled? Sometimes
they're not, which causes problems.
hoxnox (OP) answered:
@aschelper I reconfigured Qt with
-exceptions option. It fixed situation. If you'll post the answer
I'll mark it as right.
|
4,449,227 | 4,449,641 | How-to return a const std::vector<Object *const>? | I have a class with a container (containing pointer) as a member:
MyClass{
private:
std::vector<MyObject*> _VecMyObjs;
public:
const std::vector<MyObject* const> GetVecMyObj();
}
Now I try to implement GetVecMyObj(). Here is what I came up with...
const vector<MyObject *const> ACI_CALL MyClass::GetVecMyObjs()
{
... | I'm not sure std::vector<MyObject * const> (vector of constant pointers) is really what you want : I believe you mean std::vector<MyObject const *> (vector of pointer to constant objects).
The "first level" of constness (pointer constness) is naturally achieved by returning a constant reference on the vector. Only con... |
4,449,600 | 4,449,646 | Usefulness of 'delete this' in member function |
Possible Duplicates:
Is it OK to use "delete this" to delete the current object?
Should objects delete themselves in C++?
I just came across this question on programmers.stackexchange and saw the question about doing a delete this; inside a member function.
From what I understand it is generally a no-no however ther... | Generally speaking, it's a bad idea as you're technically inside a member function when you do it and suddenly every member of that class is now invalid. Obviously if you do not touch anything after the delete this; call, you'll be okay. But it's very easy to forget these things, try and access a member variable and ... |
4,449,734 | 4,449,952 | How do you send an input into a continuous loop? (C++) | I have a problem, lets say I have a continuous while loop, and inside there is a variable x that is used in some calculation. How do I send an input from the keyboard to the loop to change the variable x within the loop without stopping the loop in C++?
Thanks
| If you're running linux, your best bet is using ncurses. The S-lang library is also used by some, but I have no experience with it. Multithreading is not required.
|
4,449,792 | 4,449,825 | C++ Function Pointer as Default Template Argument | how do I write a function pointer as default template argument, I'am guessing to write it like this:
template<typename R,
typename A,
typename F=R (*PF)(A)>
class FunctionPtr { ...
my question is,
1.is it possible?
2.if it is and my guess code above is correct, what the purpose of PF here? do I nee... |
Yes
No, you don't need PF.
template<typename R,
typename A,
typename F=R (*)(A)>
|
4,449,915 | 4,450,384 | sharing a data member with the outside world in a thread-safe manner | I would really appreciate some advise on this matter.
e.g.
class Foo
{
TData data;
public:
TData *getData() { return &data; } // How can we do this in a thread safe manner ?
};
So I want to have a mechanism to make getData() thread-safe. I have come up with my own solution which involves packing the data membe... | Have you ever heard of The Law of Demeter ?
There is a similar advise (from Sutter I think): Don't share references to your internals
Both are meant to avoid coupling, because by sharing a reference to your internal, it means that your public interface leaks an implementation detail.
Now that this is said, your interfa... |
4,450,095 | 4,450,256 | Maintaining a unique set of elements on different criteria C++ STL |
I have to develop a component which
will have a more than
100,000 instances of a class. And i
want to generate a report based on the
different different criteria (members)
of the particular class. for example,
A employee class with data fields id,
names, addr, phoneno. Report
generation wiil be based o... | I have used Boost.Multi_index successfully in the past. You might find it strange from a first look but in reality it is quit interesting library. Keep in mind when using it, that you don't provide "how" but "what" in your customized container. Assume that you have the following type:
struct user_t
{
string id, nam... |
4,450,171 | 4,450,518 | Rendering fire in OpenGL | I want to render a fire effect in OpenGL based on a particle simulation. I have hundreds of particles which have a position and a temperature (and therefore a color) as well as with all their other properties. Simply rendering a solidSphere using glut doesn't look very realistic, as the particles are spread too wide. H... | If you are just trying to create a realistic fire effect I would use some kind of re-existing library as recommended in other answers. But it seems to me you that you are after a display of the simulation.
A direct solution worth trying might be replace your current spheres with billboards (i.e. graphic image that alwa... |
4,450,246 | 4,450,468 | C++ Pointer to Member Function as Template Default Argument | is it possible, like this:
template< typename C,
typename R,
typename A,
typename F=R (C::*)(A) >
class MemberFuncPtr { ...
| Actually,it seems pretty right to me, I do not get any errors for this piece of code:
template< typename C,
typename R,
typename A,
typename F=R (C::*)(A) >
class MemberFuncPtr
{
C & Cmember;
F f;
public:
MemberFuncPtr(C & c, F func):Cmember(c), f(func) {}
... |
4,450,249 | 4,450,307 | Is the value of i defined after: int i, j = 1; | Given:
int i, j = 1;
Is the value of i defined? If so, what is it?
I suspect this is a duplicate, but it's somewhat hard to search for - if anyone can find it let me know.
|
Global variables are initialized by
default to their default values (0
for int)
Local variables are not initialized
by default
For example:
#include <iostream>
int a, b=1; // a=0, b=1
int main(void) {
int p, q=1; // p=undef, q=1
return 0;
}
proof for local variables:
#include <iostream>
int main(void) {
{
... |
4,450,255 | 4,450,574 | Singleton Class Implementation Problem | There is a static pointer aSingletonClass *instance_ and a static function void deleteInstance( void ) declared in the Code 1.
I implemented the Code 2 without using a static pointer and static function(i thought Singleton can be achieved without it but I am not sure!!!)
Please advice me whether this change can be haza... | Your code should be like this:
class A {
public:
static A *getInstance( void )
{
if(!instance_)
instance_ = new A();
return instance_;
}
static void deleteInstance()
{
if(instance_)
delete instance_;
instance_ = NULL; //important as this can cr... |
4,450,291 | 4,452,118 | how to make parallel events in c++ (specific Qt 4.6) | I have a problem with the execution of multiple functions at once.
Specific , I have two classes (MyRect and space). The Idea is similar to space invaders but I stuck on the beginning. In class MyRect I have defined two rectangles :: body (ship body) and bullet (ship bullet).In the main class space is created ship as M... | You have an architectural problem. What you are doing is moving the bullet in a loop in its fireBullet method. While that loop is running, the rest of the program isn't, since a single thread can only be doing one thing at a time.
The solution is to refactor your code so that everything on the screen gets updated by... |
4,450,401 | 4,450,565 | using comparison function in stl container | Why can I do this:
stable_sort(it1, it2, binary_function);
but not this:
priority_queue<type, vector<type>, binary_function> pq;
Why can I use a function in the first case, but need an object in the second?
| If you check out the reference on std::stable_sort, you will see that the binary_function you provided, should be a function object as well... There is no difference between the two, except that maybe in the second case there is no proper "cast" or conversion made from a function to a proper function object.
I believe ... |
4,450,466 | 4,450,483 | How to get the correct number of C++ command line arguments? | I start my program with
int main (int argc, char *argv[]) {
printf("%d \n", argc);
then I compiled in Ubuntu using g++, and I ran the program using
./calc 2 3 4 + *
but the program outputs 17! I did a printf on the arguments as well, they are:
arg 0: ./calc
arg 1: 2
arg 2: 3
arg 3: 4
arg 4: +
arg 5: 1.2.c
... | The * is being evaluated by your shell to mean all of the files in the current directory. You should escape the asterisk using \*.
|
4,450,595 | 4,451,077 | Qt - Determine absolute widget and cursor position | I have a QWidget that contains multiple children. The ultimate goal is to be able to drag and drop from one widget to the other, moving something between widgets. I've got a signal being fired to my parent widget's controller and can determine when the drag is starting and ending correctly. My current problem is det... | As already said you should rather use targetWidget->geometry() instead of contentsRect() in this special case.
Next I wonder which class the code you posted belongs to. The method QWidget::mapToGlobal() should be invoked from the QWidget your coordinates are relative to. If I got you right, it should look like somethin... |
4,450,679 | 4,450,829 | c++ macro wrapped in function pointer to put into vector | I have a macro that might look as follows (from boost log library)
#define L_(lvl) BOOST_LOG_USE_LOG_IF_LEVEL(g_l(), g_log_level(), lvl )
Is it possible to wrap this into a boost::function<> object or a function pointer and stick it in a queue or vector of such items?
If it is, how would I do that?
I'm trying to write... | If you have a fixed set of logging levels, you could just call that macro from within a function and use a pointer to that function:
void log() {
L_(3);
}
void anotherlog() {
L_(13);
}
You can easily have that in a vector an then call them all:
typedef void (*LogFunction)();
std::vector<LogFunction> logFunctions;... |
4,450,808 | 4,451,869 | MFC Resizing dialog and child window paint problem | When I resize parent dialog (resizing border), child dialog is not painting correctly. Child dialog is partially hidden behind the border of parent dialog. If i make dialog bigger, revealed part of child dialog isn’t painted. But when i make it even bigger, child dialog paints to the previous border position. I tried m... | Try to add WS_CLIPCHILDREN style to the parent dialog.
|
4,450,918 | 4,451,012 | Creating my own 'data type' | I want to be able to create a type that has 3 floats (x,y,z). I have tried:
typedef struct
{
float x;
float y;
float z;
} Vertex;
But that didn't work.
Does this have to be declared somewhere where it can be seen by main? How would I go about creating getter methods and other methods for a type I have made?
|
does this have to be declared somewhere where it can be seen by main?
Yes. Typically the class or struct is declared in a header file, which you #include in whatever translation unit (c file) you use it in.
|
4,450,961 | 4,453,581 | Computation of Cpu percentage by a single process in unix by the "top" command | I would like to know how does the "top" command compute the cpu percentage used by any process.
I have tried reading the "psinfo" binary file in the /proc directory , but it didnt help in finding the result.
Please provide any information how it can be done.
Thanks in advance.
| The top command computes the CPU usage using the data in the proc file system. The actual file containing the CPU usage data can vary from one platform to another. For example, in Linux it is found in /proc/<pid>/stat and for Solaris it is found in /proc/<pid>/psinfo. The CPU usage is calculated as the difference i... |
4,451,291 | 4,451,393 | Nested if-statements C++ | I'm writing a Snake program in C++ (visualisation with JNI) and valid movement buttons are either left (move 90° counter-clockwise) or right (move 90° clockwise).
In every loop of the game loop I retrieve a key event from a GUI interface and move my snake according to that key event, this is how i do this:
if(key_event... | I would personally have another function to apply the move.
if(key_event != NULL){
if(key_event == LEFT){
moveLeft();
}
...
}
void moveLeft()
{
switch(moveDirection)
{
case UP:
case DOWN:
moveDirection = LEFT;
break;
case ...
}
}
I use switch case, in my opinion it is ... |
4,451,399 | 4,451,445 | Drawing a solid sphere with transparency in openGL | I want to draw a glutSolidSphere with some transparency, but it doesn't seem to work.
glColor4f(1, 0, 0, 0); // should be completely invisible
glPushMatrix();
glTranslatef(position.x, position.y, position.z);
glutSolidSphere(3, 5, 5);
glPopMatrix();
In my main function, I initialize with the following display mode:
gl... | You need to explicitely setup alpha blending . Another example.
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
|
4,451,444 | 4,451,818 | Boost multi_index_container, get index by tag results in compiler error | So, I'm trying to dabble with the multi_index_container and am having a rather strange compiler error, first here is the simplest example to demonstrate my problem (I'm probably missing something stupidly simple)...
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <bo... | bool addA(AType const& cA)
{
const id_index_t& os = _cSet.template get<id_index>(); // line 1: errors occur here
// .. do stuff
return true;
}
|
4,451,793 | 4,451,891 | Template class with container with pointers to itself | Is the following possible :
template<class Container>
class TreeNode
{
Container mChildren;
}
TreeNode<std::vector<boost::shared_ptr<TreeNode>> myTreeNode;
| Not like you did. TreeNode is not a class but a class template.
I am in a hurry now so this might not be the most simple or elegant way, but it is possible:
#include <vector>
using namespace std;
class Container {};
template<class Container>
class TreeNode
{
Container mChildren;
};
class TreeNodeWrapper;
type... |
4,451,829 | 4,451,929 | is windows presentation foundation available to c++ developers? | i read about window presentation foundation and i got a book
windows presentation foundation
unleashed.
But to my surprise, the code was in c#.
Question:
Is wpf available to c++ developers? if not Why. Thanks
| .NET can certainly be worked with C++/CLI, and that should extend to WPF as well.
|
4,452,136 | 4,474,458 | How do I use boost::lexical_cast and std::boolalpha? i.e. boost::lexical_cast< bool >("true") | I've seen some answers to other boost::lexical_cast questions that assert the following is possible:
bool b = boost::lexical_cast< bool >("true");
This doesn't work for me with g++ 4.4.3 boost 1.43. (Maybe it's true that it works on a platform where std::boolalpha is set by default)
This is a nice solution to the stri... | I'm posting the answer to my own question here for others who may be looking for something like this:
struct LocaleBool {
bool data;
LocaleBool() {}
LocaleBool( bool data ) : data(data) {}
operator bool() const { return data; }
friend std::ostream & operator << ( std::ostream &out, LocaleBool b ) {
... |
4,452,166 | 4,452,243 | How do I set a timer 2 seconds in to the future with boost? | So I have a function which takes "const boost::posix_time::time_duration& t" as an attribute and I can't find any information on how to do something as simple as set the duration 2 seconds (or whatever) in to the future. Lots of complex stuff explained in boost.org but I can't find any info on how to get the current ti... | time_duration doesn't hold a time as in "a specific point in time". It holds a length of time. If you want that length to be 2 seconds, you can do this:
t = boost::posix_time::seconds(2);
|
4,452,303 | 4,452,520 | Type casting a structure member | I have structure(A) and it takes another structure(B) as member.
Now i want structure C as member of A instead of B.
Both B and C are of same type
typedef struct
{
int a;
B b;
}A
typedef struct
{
int a;
}B
typedef struct
{
int a;
}C
How can i assign struct C as member instead of B. How to do typecasting
Please ... | Without knowing why you want to do this, its hard to recommend a strategy. Here are a few options though.
Option 1: Use Templates. (C++ only)
template <type T>
struct A
{
int a;
T* t;
};
struct Foo
{
int a;
};
struct B : public Foo
{
};
struct C : public Foo
{
};
struct A<Foo> A_foo;
struct B;
struct C;
A_f... |
4,452,328 | 4,452,486 | Qt Signals/Slots and Threads | I'm new to GUI programming and multithreading. I am in the process of creating a real-time app that receives information from my car and renders it in some meaningful way. My app is layed out as 3 threads, the GUI (main thread), the rendering thread and the hardware comm thread. Inbetwen the the render and the hardwar... | It gets processed in the main thread by default, but see this guide for more information.
|
4,452,840 | 4,452,926 | boost async_receive receiving unexpected random things | i'm working on an irc server but the problem it's receiving something like this:
CAP LS
NICK Fallen
USER Fallen 0 * :Fallen
where it should be:
NICK Fallen
USER Fallen 0 * :Fallen
my code: http://pastebin.com/Li3wbpvu (i'm sorry i suck at posting code here it gets messy)
EDIT: more details: and it's not even receivin... | That's perfectly valid IRC protocol capabilities negotiation.
See some references
|
4,453,084 | 4,620,938 | C++ DLL Throws Exception at Runtime | My C# application calls a function in a C++ DLL at run-time and throws an exception. The error code generated is 262. Unfortunately, the Microsoft documentation is a bit lacking for this code.
Oddly, this exception is not thrown when running the DLL from the C++ test application that is part of the same Visual Studio... | In your specific scenario, a separate thread is probably the best thing at your disposal.
Creating threads from a DLL is a messy business because a DLL doesn't own the process' lifetime; the owner is the EXE.
However... if you run it in a synchronous fashion (create the thread; initialize; wait on the thread to complet... |
4,453,244 | 4,453,289 | C++ ctors: What's the point of using initializer list in a .cpp file? | C++ has this funky quirk of supporting initializer lists for a ctor, such as:
class Foo
{
public:
Foo(int x) : m_x(x) { }
private:
SomeComplexObjectThatTakesAnIntForConstruction m_x;
}
Makes sense so far. More efficient because the member is only initialized once, rather than being default-constructed, and then o... | You have misunderstood.
The initializer list doesn't need to be visible from other translation units the same way that the constructor body doesn't need to be visible from other translation units. It affects the code which is generated for the constructor itself, not the code which is generated to call the constructor... |
4,453,372 | 4,453,404 | sqrt(1.0 - pow(1.0,2)) returns -nan | I've found an interesting floating point problem. I have to calculate several square roots in my code, and the expression is like this:
sqrt(1.0 - pow(pos,2))
where pos goes from -1.0 to 1.0 in a loop. The -1.0 is fine for pow, but when pos=1.0, I get an -nan. Doing some tests, using gcc 4.4.5 and icc 12.0, the output... | The problem is that floating point calculations are not exact, and that 1 - 1^2 may be giving small negative results, yielding an invalid sqrt computation.
Consider capping your result:
double x = 1. - pow(pos, 2.);
result = sqrt(x < 0 ? 0 : x);
or
result = sqrt(abs(x) < 1e-12 ? 0 : x);
|
4,453,425 | 4,453,523 | Why don't processes split by fork() proceed through this function identically? | I am confused by the fork() function in C/C++.
Given the following code:
void fork2()
{
printf("LO\n");
fork()
printf("L1\n");
fork();
printf("Bye!\n");
}
Lecture slides give the following diagram
______Bye
___L1|______Bye
| ______Bye
L0|___L1|______Bye
To me, this diagram doesn... | fork() creates an exact duplicate of the process that made the fork() function call. This means, that you then have two processes that are exactly the same, and are at the same point in the program. If we step through the fork2() function, the following happens.
Process A (original process):
L0 (process A forks, cr... |
4,453,586 | 4,469,398 | boost::date_time (boost-145) using a 64-bit uint with microsec calculations, without truncation | I am using date_time to abstract away platform peculiarities. and I need to produce a 64-bit microsec resolution uint64_t which will be used in serialization. I do not understand what is going wrong below.
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>
#include <iostream>
using names... | This seems to be a problem with the microseconds() not be ing able to handle such a large microseconds input. The following snippit is a fix to this problem:
#define MICROSEC 1000000
uint64_t sec_epoch = microsec_since_epoch / MICROSEC;
uint64_t mod_micro_epoch= microsec_since_epoch % MICROSEC;
ptime new_method = UNI... |
4,453,992 | 4,454,036 | error C2065: 'socklen_t' : undeclared identifier | The whole error is:
Error 1 error C2065: 'socklen_t' : undeclared identifier c:\users\richard\documents\visual studio 2010\projects\server\server\server.cpp 41 1 Server
This is the problematic line:
int iRcvdBytes=recvfrom(iSockFd, buff, 1024000, 0, (struct sockaddr*)&cliAddr, (socklen_t*)&cliAddrLen);
I ha... | The socklen_t type is defined inside of WS2tcpip.h in windows. This is not transitively included from winsock2.h (AFAICT). You'll need to include WS2tcpip.h manually in order to use the socklen_t type.
|
4,454,097 | 4,454,133 | Dependencies, Namespace, and Headers | I believe have dug myself into a hole. While breaking up my single file, couple thousand line chunk of code into multiple files I appear to have grossly screwed up the structure of the program.
I'm new to C++ and its header files and namespace management so I've been learning as I go.
I guess I don't fully understand ... | Most likely you're missing a semicolon on the end if a class or struct definition in a header file. The compiler then treats every identifier it sees as an instance of that class instead of what you're expecting. Then the compiler complains because it has no idea what to do with the stray {}s it sees.
Check the header ... |
4,454,120 | 4,454,239 | c++ & Context structure | Does anybody know where I can find some information about the fields of the CONTEXT structure in C++?
| As @bcsanches states, this is a Windows API. It's going to be completely processor dependent. Look up the structure in your own headers.
On my headers it shows as:
//
// Context Frame
//
// This frame has a several purposes: 1) it is used as an argument to
// NtContinue, 2) is is used to constuct a call frame for APC... |
4,454,406 | 4,454,445 | how to truncate width of integral types with std::ostringstream? | Say you have something like:
std::ostringstream oss;
int value(42);
oss.fill('0');
oss << std::setw(3) << value;
cout << oss.str();
OUTPUT: 042
This output is because std::setw ensures a minimum width and we told the stream to fill with 0 however how do you do the opposite and specify a maximum width so that display w... | The stream formatting capabilities are not intended as a general purpose string manipulation package. What you are trying to do does not make much sense numerically, so it is not supported - using the substring or similar functions is the way to go. You can (and should, if you need this in more than one place) write yo... |
4,454,444 | 4,455,814 | C++ libraries that implement Go goroutines or Go channels? | I'm working with a medium-sized C++ code base which is currently entirely single-threaded. The time has come, however, to pursue concurrency and parallelism for performance gains. I'm very interested in the concurrency model of Google's Go programming language, with very lightweight goroutines and a system of communica... | If your aim is primarily speeding up compute things, Intel's TBB (Threading Building Blocks) is (IMHO) a better option than rolling your own inferior version from boost::thread.
|
4,454,582 | 4,455,194 | Visual Studio C++ 2008 / 2010 - break on float NaN | Is there any way to set up Visual Studio (just upgraded from 2008 to 2010) to break, as if an assertion failed, whenever any floating point number becomes NaN, QNAN, INF, etc?
Up until now I have just been using the assert(x == x) trick, but I would rather something implicit, so that I dont have to add assertions every... | 1) Go to project option and enable /fp:strict (C/C++ -> Code Generation -> Floating Pint Model).
2) Use _controlfp to set the floating-point control word (see code below).
#include <float.h>
unsigned int fp_control_state = _controlfp(_EM_INEXACT, _MCW_EM);
#include <math.h>
int main () {
sqrtf(-1.0); // float... |
4,454,591 | 4,454,634 | Multiple copies of application accessing SQLite file? | Our application uses an SQLite database file to hold some data in it. The app opens the database in the file on startup, reads and writes to it, and closes it on exit.
Unfortunately, we can't forbid someone from running two copies of our app at once. If that happens, presumably there will be two copies of the app tryin... | Any sane database provider, including sqlite, will not corrupt your database if 2 people access it at the same time. Most will queue the requests if there's no way to run them in parallel.
Now what your app does with the data, that is your app's problem, but don't worry about the database itself.
|
4,454,640 | 4,454,675 | How do I use a variable in an argument line? | I am using SOCI to make MYSQL connections from my QT4 C++ application. I could hard code a mysql server IP, username, and password but I would rather pass this information in as a variable instead.
For example, I would like to do something like this, but there are no functions that accept these kinds of parameters:
ch... | Try using QString's arg function.
session sql(mysql, QString("host=%1 db=%2 user=%3 password=%4").arg(sqlserver).arg(dbname).arg(user).arg(password));
I know it's ugly, and Qt should come up with a prettier solution, but it works.
|
4,454,926 | 4,455,618 | How to fire property changed notifications from C# to COM using IPropertyNotifySink? | I am going crazy on this problem for the past couple of weeks. I have a C# Com object that needs to send property change notifications to a C++ Com object. An equivalent in VB would be using code that looks as follows
PropertyChanged "propertyName".
In C++ the equivalent to use the CFirePropNotifyEvent class from ATL.
... | I don't think there is some automatic gateway between .NET's INotifyPropertyChanged and COM's INotifyPropertySink.
If you want a .NET object to provide COM events, you need to provide an implementation of IConnectionPointContainer in these .NET objects.
IConnectionPointContainer already exists in .NET in the System.Run... |
4,455,065 | 4,455,166 | Safest way to extract from stream to char array or std::string | I am concerned about buffer overflows, and I need to get some characters out of a class that derives from std::istream. From what I understand there is no way to stream to an std::string directly from an istream, without my own >> operator. So I was considering streaming the contents to a char array, then putting that ... | If you've (properly) inherited from std::istream, then you don't need to do anything special and can just use operator >> (std::istream&, std::string&).
std::string s;
SomeIStream >> s;
When I say "properly," I mean overridden the appropriate virtual functions from istream.
"I know that if there is an exception befor... |
4,455,093 | 4,455,135 | Move constructor, non-const copy constructor, list's emplace in VS2010 | I'm new to move constructor and quite confused with VS2010 behavior.
I design a move constructor (of class A) which in my knowledge is like this:
A(A&& input) {some code}
When I use list's emplace and put an instance of class A:
mylist.emplace(a);
My move constructor is not called, and a non-const copy constructor is... | mylist.emplace(a);
Here a is an l-value, hence it's copied rather than moved. You need to move it explicitely:
mylist.emplace(std::move(a));
Yes, the behavior is correct.
|
4,455,177 | 4,455,244 | C++: seeding random number generator outside of main() | I was creating a simple program that simulates a coin toss for my class. (Actually, class is over this term and i'm just working through the rest of the projects that weren't required). It involves the creating and calling a function that generates a random number between 1 and 2. Originally, I tried to seed the ran... | You probably only want to seed the random number generator once. rand() returns the next pseudo-random number from it's internal generator. Every time you call rand() you will get the next number from the internal generator.
srand() however sets the initial conditions of the random number generator. You can think of it... |
4,455,234 | 4,455,478 | Passing string from C++ to C# | I am using the PInvoke, reverse PInvoke scheme as described by Thottam R. Sriram http://blogs.msdn.com/b/thottams/archive/2007/06/02/pinvoke-reverse-pinvoke-and-stdcall-cdecl.aspx
Everything seems to work well, except for passing a string from C++ to C.
( In Sriram the string is constructed in c# and passed untouched t... | When marshalling strings across a P/Invoke boundary, it is always good practice to use a MarshalAs attribute with the appropriate string type. I think putting a [MarshalAs(UnmanagedType.BStr)] on the parameter should take care of the problem.
public delegate void callback([MarshalAs(UnmanagedType.BStr)]string str);
... |
4,455,372 | 4,455,723 | how to write C++ code to handle an event raised in C# code | I would like to know how, in C++ code, can i receive and then handle events raised from C# code.
I have a C# WinForms UI module that raises an event after collecting some information. I have to handle the event in C++ code, because that's where the code to process the collected information is already implemented. I ju... | Check out delegate/function pointer interop. http://msdn.microsoft.com/en-us/library/367eeye0(v=VS.100).aspx
You could also attach a C# delegate to the event and have the C# code call the C++ code via P/Invoke.
|
4,455,655 | 4,455,762 | How do I create a bitmap using the BITMAPV5HEADER header? | This is my current code, but it causes an error when casting to BITMAPINFOHEADER:
/* Create the bitmap */
BITMAPINFO bmpinfo;
ZeroMemory(&bmpinfo, sizeof(bmpinfo));
BITMAPV5HEADER bmpheader;
ZeroMemory(&bmpheader, sizeof(bmpheader));
bmpheader.bV5Size = sizeof(BITMAPV5HEADER);
bmpheader.bV5Width = width;
bmpheader.bV5H... | BITMAPINFO isn't a true structure, it's more just documentation about how the color map follows the header. Just pass your BITMAPV5HEADER directly to CreateDIBSection:
HBITMAP result = CreateDIBSection(screen, reinterpret_cast<BITMAPINFO *>(&bmpheader), DIB_RGB_COLORS, &converted, NULL, 0);
|
4,455,736 | 4,455,820 | Is it possible to use the STL for_each algorithm using a function with independent input parameters? | At the moment I am running a for loop where I make a call on each element in an STL container, similar to the following.
void AddToUpdate(iterator iter, Update& Update) {...};
...
Update update;
for(iterator iter = container.begin(); iter != container.end(); ++iter)
AddToUpdate(iter, update);
I am looking at the... | The various std::bind1st/std::bind2nd and the Boost.bind library were created to solve your problem (that is common to almost anyone who used the STL algorithms), but often they just seem a workaround instead of a solution.
Fortunately, with the upcoming C++ standard the long-awaited addition of lambda functions should... |
4,455,768 | 4,455,931 | COM Initialization and Use in Win32 C++ DLL | I am writing a Win32 C++ DLL that uses the COM to query WMI. How can I programmatically determine if COM has already been initialized? Thanks.
| Mark Ransom is right
the straightforward, clean and simple solution is to require COM initialization by the caller.
Ugly hack
You can try your first call - likely CoCreateInstance, and if it returns CO_E_NOTINITIALIZED, run CoInitialize yourself (and don't forget to uninit in that case)
However, it is still problemati... |
4,455,775 | 4,455,789 | c++ get the last (n) char in a string | i have a string and i want to get, for example, the position of the last (.) in the string, or whatever char i want to check, but untill now i just get a headeach.
thanks
| Is find_last_of what you need?
size_type find_last_of( const basic_string& str, size_type pos = npos ) const;
Finds the last character equal to one of characters in the given character sequence. Search finishes at pos, i.e. only the substring [0, pos] is considered in the search. If npos is passed as pos whole string... |
4,456,180 | 4,459,514 | How can I immediately cancel a curl operation? | I'm using libcurl in C++, and I'm calling curl_easy_perform in a separate thread from my UI using Boost.Thread.
The main UI has a cancel button that I'd like to be perfectly responsive (i.e., when a user clicks on it, it should immediately react). I have read, write, and progress callbacks set up to read an atomic shou... | Your basic idea is right. You should detach the curl operation from the UI. However, the implementation should be changed a bit. You shouldn't be using a global should_cancel. Instead, you should have a global current_request pointer, to an object of type Request. This type should have an internal cancel flag, and a pu... |
4,456,228 | 4,456,247 | Is there a good template engine for C++ | does anyone know of a good C++ template engine? Since, my aim is to try to generate C++ and Python code, given a template and a description of what needs to be filled in that template, in short, I'm trying to do something like cayenne but for C++ and Python, using a C++ processor. Since it would be usefull for my other... | Have you had a look at Cheetah. We have been using Cheetah for a large Code generation project in QA and it has been working well for us.
|
4,456,397 | 4,456,428 | Single file non-validating xml parser/reader | I'm looking for a simple non-validating XML parser in either C or C++.
Several years back I found one that was just a single file solution but I can't find
it anymore.
I'm after some links and suggested ones that are very small and lightweight
ideally suited for an embedded platform.
| What about something like pugixml. From their site...
pugixml is a light-weight C++ XML
processing library. It features:
DOM-like interface with rich traversal/modification capabilities
Extremely fast non-validating XML parser which constructs the DOM
tree from an XML file/buffer
XPath 1.0 implementation for comp... |
4,456,776 | 4,456,811 | Variable values in Fork() child | I have already asked one question about fork(), here is another.
Given the following code:
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid1, pid2;
pid1 = fork();
pid2 = fork();
if (pid1 != 0 && pid2 != 0)
printf("A\n");
if (pid1 != 0 || pid2 != 0)
printf("B\n");
ex... | I'm about to test that for you, but let me tell you what I'd expect.
/ pid2=[child3 pid] { pid1 = child1;pid2 = child3;}
pid1=[child1 pid] fork()
/ \
/ pid2=0 { pid1 = child1;pid2 = 0;}
fork()
\ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.