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 |
|---|---|---|---|---|
7,092,199 | 7,092,453 | Is it correct that header files in C++ and abstract class/interface implementations in Java are both the same idea? | I am a little with familiar with C++ and I know that for almost every header file, I must create source file to go with it.
Now I am looking into java interfaces and implementation and it looks as the same thing.
At first you just name the variables and methods in one class and then you define them in other class.
Are ... | Java interfaces and C++ header/implementation files are different concepts.
C++ has a text compilation model. So, to use something - such as a function - in your code, the compiler must first have parsed a definition of that function. By putting things into header files that you want to use from many source files, it s... |
7,092,633 | 7,108,630 | Connect Timeout with Alarm() | Since it seems that I can't find a solution to my original problem, I tried to do a little workaround. I'm simply trying to set a timeout to the connect() call of my TCP Socket.
I want the connect() to be blocking but not until the usual 75 seconds timeout, I want to define my own.
I have already tried select() which... | signal is a massively under-specified interface and should be avoided in new code. On some versions of Linux, I believe it provides "BSD semantics", which means (among other things) that providing SA_RESTART by default.
Use sigaction instead, do not specify SA_RESTART, and you should be good to go.
...
Well, except fo... |
7,092,765 | 7,092,830 | What does it mean to have an undefined reference to a static member? | I just wrote a class with some static data members, but now I am getting errors about "undefined references". Why doesn't this work? What am I doing wrong?
_(Note: This is meant to be an entry to [Stack Overflow's C++ FAQ](https://stackoverflow.com/questions/tagged/c++-faq). If you want to critique the idea of providi... | To understand this, you should have a good understanding of compiling and linking, and the differences between declarations and definitions.
Consider the following class:
//In header file
class Example {
static bool exampleStaticMember;
};
Here, exampleStaticMember is declared but not defined. This means that if ... |
7,092,785 | 7,095,471 | how to get rid of redundant type specifiers in a bind expression | Consider the following code:
struct f{
void get(int a) {}
};
struct g1{
template <typename Arg>
void get(Arg a) {}
};
struct g2{
template <typename... Args>
void get(Args... args) {}
};
int f2()
{
std::bind(&f::get,f(),2); // (A)
std::bind(&g1::get<int>,g1(),2); // (B) redundant type specif... | Use operator() instead of a get method. It will work this way:
#include <functional>
#include <iostream>
struct g1{
typedef void result_type;
template <typename Arg>
result_type operator()(Arg a) {
std::cout << "g1()" << std::endl;
}
};
struct g2{
typedef void result_type;
template <typ... |
7,093,206 | 7,093,626 | c++ functor for deleting pointers seems to work | Elsewhere the following was suggested for a functor for deleting pointers in a vector
struct DeleteFromVector
{
template <class T>
void operator() ( T* ptr) const
{
delete ptr;
}
};
to be called using
std::for_each(aVec.begin(), aVec.end(), DeleteFromVector());
I had written something simi... | Why do both templates work?
In the first template, you pass an Obj* to a template method taking a T* so the compiler deduces that T is Obj.
In the second template, you pass an Obj* to a template method taking a T so the compiler deduces that T is Obj*.
Use of inline
The inline is redundant there, as member functions d... |
7,093,436 | 7,097,011 | Setting the label for a Windows networking mapping | Is it possible to give a network drive mapping (as created with the WNetAddConnection functions or "Map network drive..." GUI) a label other than the default "<Target Name> (<Target Path>) (<Drive Letter>:)" one?
I tried giving SetVolumeLabel a go but this always fails, and I see nothing in the WNet API's to specficy t... | This isn't a 100% solution but it's more of an answer than a comment...
If you rename a mapped network drive the the GUI (by right clicking on it and going to 'Rename') it adds a value to the registry. Reading round on various sites (notably this one) it looks like Windows may sporadically delete this value by itself, ... |
7,093,439 | 7,093,961 | Is it possible to allocate a segment using the Windows API? | I am wondering if it is possible for a Windows program to allocate a segment descriptor within the process' local descriptor table. Is there a Windows API function that can install a new segment descriptor to the running process' LDT using a provided linear offset, segment length, and combination of flags (RWX)?
| It's possible using undocumented NT API, specifically NtSetLdtEntries.
Note that Windows x86-64 does not set up an LDT so this only works on x86.
Here's some code.
|
7,093,535 | 7,094,650 | Isolating and multiply instantiating a C library in-process | We have a C library (.lib windows & .a linux) that only allows creation of a singleton and that also doesn't shut down properly (memory leaked and threads left alive) having been once instantiated.
Rewriting it and hunting down the bugs aside, is there a simple way to isolate this kind of misbehaving code in-process su... | Sorry, but there is no simple way to do this. Sandboxing badly behaving libraries is commonly done using separate processes, which you already suggested yourself. An IPC tool like Protocol Buffers might help in defining and implementing the IPC protocol.
|
7,093,700 | 7,093,816 | Default values for array arguments | Just playing around a little with C++. What I really want to do is to be able to setup a function with default values defined for an array or pointer argument. To keep things simple, let's just use an array. Like so:
void experimentA(char a[3] = {'a', 'b', 'c'});
The compiler (LLVM GCC 4.2 with GNU99) complains "Expect... | Your colleagues are wrong or maybe you misunderstood.
The first clue to understanding is that you cannot have an array as a function parameter in C or C++. The reasons are historical. So when you write void experimentA(char a[3] ...) the compiler automatically converts it to a pointer, i.e. void experimentA(char* a ...... |
7,094,108 | 7,094,323 | How to raise an int or long to a power in C++ | Trivial question: I am just wondering, if one wants to raise an int or a long to the power of another int or long, does
(long)std::pow((double)a,(double)b)
suffice, or do I need
(long)(0.5 + std::pow((double)a,(double)b))
?
| There are two considerations. The first is roundoff due to inexactness of floating point representations; this won't be a problem in this case, because integers are perfectly representable as long as the number of bits is less than the bits of significand in the floating point. If long is 32 bits and double significand... |
7,094,312 | 7,094,443 | Visual studio: question about linking functions between two projects | I guess this is a newbie question, but anyway. I've got a solution composed of two projects (1 DLL and 1 console app). The console app includes some headers from the DLL project and of course, when building it all, the linker tells me that there are some unresolved symbols.
I've already added a Reference from the app ... | I'm going to guess you use Visual Studio and don't know about dllexport.
Visual Studio by default does not export the names of your functions on the outside of your DLL. To do so you need to tell it that explicitly:
__declspec(dllexport) void f() {...}
and on the side of the one using the DLL:
__declspec(dllimport) vo... |
7,094,397 | 7,145,070 | Loader lock error with managed c++ dll, statically linked to a native c++ lib | I have a managed c++ dll with few managed classes that in turn call native c++ code in a library that I have statically linked to the dll. However, if I try to run RegAsm.exe on the dll, the tool correctly reports 'no types we registered' but then hangs. I'm very sure this is a loader lock problem and my dll hangs when... | The following page, (especially the Initializing Static Objects and Implementation in Headers sections) has the following to say:
Because the same header may be included both by a CPP files with /clr enabled and disabled, or a #include can be wrapped inside a #pragma unmanaged block, it is possible to have both MSIL ... |
7,094,407 | 7,094,500 | C++ Template Limiting Member Constructor | This is my first foray into C++ templates, and I'm trying to construct a BinaryTree template to help me with a Project Euler problem; however, I seem to be getting an error where BinaryTree class doesn't recognize all the constructors of the BinaryTreeNode! Here's a snippet of the code.
template <class T>
class Binary... | In your initialization expression _root(leftTree.Root(), rightTree.Root(), value), _root is a pointer. You can only initialize it to another pointer. Perhaps you mean to initialize it to a pointer to a new node constructed on those arguments?
This could be done like this: (updated after your edit)
_root(new BinaryTreeN... |
7,094,585 | 7,095,702 | Typical time of execution for elementary functions | It is well-known that the processor instruction for multiplication takes several times more time than addition, division is even worse (UPD: which is not true any more, see below). What about more complex operations like exponent? How difficult are they?
Motivation. I am interested because it would help in algorithm de... | First off, let's be clear. This:
It is well-known that processor instruction for multiplication takes
several times more time than addition
is no longer true in general. It hasn't been true for many, many years, and needs to stop being repeated. On most common architectures, integer multiplies are a couple cycle... |
7,094,860 | 7,094,913 | Does this cause a memory leak / How should I structure the code | I am slightly concerned that this code may have a memory leak. I would like to know if in fact there is a leak, and also what is the correct way to go about this problem.
Description: I have a base class Pet with derived classes Cat, Dog, and Bird. I am parsing lines from a file, and depending on certain contents in ... | Yes, this causes a memory leak, since you allocate a new Pet() which is never deleted and the pointer to it is overridden with either a new Dog() or something else.
I would suggest you create a so-called factory function, which reads a line from the file, and creates the type of Pet the line states.
|
7,094,903 | 7,520,999 | Is there a faster component than TMemo on CodeGear C++ Builder? | I'm using CodeGear C++ Builder 2009 and have problems with the TMemo component. It's too slow. I use it to display ASCII text from the COM serial port. I need to display every single symbol when it comes from the COM Serial port. The problem is, if there is a lot of text from the COM serial port, older text on TMemo st... | Rather than displaying the characters in real-time to the TMemo as they arrive, try saving them to an in-memory buffer first, and then have a short timer copy the buffer into the TMemory periodically, and make use of the Lines->BeginUpdate() and Lines->EndUpdate() methods when adding new text. Also, 1000 lines is a lo... |
7,095,127 | 7,095,188 | c++ memory management | Is this a good way to delete a map of longs and objects made with new
// iterate over the map
for (std::map<unsigned long, Object*>::iterator it = objects.begin(), it_end = objects.end(); it != it_end; ++it)
{
Object* temp = it->second;
if(temp)
delete temp;
}
// clear the map
objects.clear();
| Yes, although the better solution would be to use smart pointers instead of Object*, but that is a different subject.
You could shorten the content of the for to
{
delete it->second;
}
delete null is defined and is a noop.
|
7,095,139 | 7,095,160 | Array of templated type in C++ | I have the following :
QFutureWatcher<bool> *procwatcher;
procwatcher = new QFutureWatcher<bool>();
QFuture<bool> procfuture = QtConcurrent::run(this, &EraserBatch::processTile);
procwatcher->setFuture(procfuture);
QFutureWatcher<bool> *procwatcher2;
procwatcher2 = new QFutureWatcher<bool>();
QFuture<bool> procf... | As long as the template is fully specialized (i.e. all template parameters specified), then you can simply do this:
#include <vector> // required for std::vector
std::vector<QFutureWatcher<bool>*> procWatchers;
Although according to how QFutureWatcher is used in these documentation examples, you probably want to stor... |
7,095,363 | 7,827,333 | Boost shared mutex not released after exception thrown | I came across a strange Boost (v1.38) mutex deadlock in a preexisting .NET (C#, 3.5) application that makes calls to a C++ library. An exception is [properly] thrown at a point after a read lock is obtained and that exception goes unhandled all the way back to the managed .NET code (where it is handled). The next cal... | There is a bug in the 2.0 CLR that prevents the stack from unwinding when the native-born exception is handled in managed code.
Microsoft Connect: /Ehsc & /Eha & stack unwinding
Switching the managed executable to run on the 4.0 CLR corrected the problem.
As a side note, the native C++ library was being called from a m... |
7,095,581 | 7,096,331 | Actual difference between end of line and end of file under windows? | I understand EOF and EOL but when I was reading this question (second part of answer) and i got my concepts broken :
Specially the para :
It won't stop taking input until it finds the end of file(cin uses
stdin, which is treated very much like a file)
so i want to know when we do some thing like in c++ under wind... | End-of-line and end-of-file are very different concepts.
End-of-line is really just another input character (or character sequence) that can appear anywhere in an input stream. If you're reading input one character at a time from a text stream, end-of-line simply means that you'll see a new-line ('\n') character. Som... |
7,096,152 | 7,096,229 | C++ : Difference between linking library and adding include directories | Pretty much title sums it up.
I'm not sure the difference between the two if i'd like to use a library.
Thanks!
| In general, you need both.
Include files contain declarations of types, prototypes of functions, inline functions, #defines, ..., in general every information about the library the compiler needs to be aware of when compiling your files.
Static libraries, instead, contain the actual object code of the functions of the ... |
7,096,417 | 7,096,537 | What's the sizeof the virtual function table pointer? | In single inheritances, is the size of a pointer to virtual table always equal to the size of a void*? Say,
class vft { virtual ~vft(); }
assert (sizeof(vft) == sizeof(void*));
Would that assertion always be true?
| The C++ ISO Standard says nothing about virtual function table pointer in the first place. A Compiler may follow this mechanism to support runtime-polymorphism or can come up with any other which doesn't even involve vptr. Its entirely upto the compiler writers. Since the Standard doesn't say anything about vptr, how c... |
7,096,423 | 7,096,735 | Do modern C++ compilers inline functions which are called exactly once? | As in, say my header file is:
class A
{
void Complicated();
}
And my source file
void A::Complicated()
{
...really long function...
}
Can I split the source file into
void DoInitialStuff(pass necessary vars by ref or value)
{
...
}
void HandleCaseA(pass necessary vars by ref or value)
{
...
}
void Ha... | You should mark the functions static so that the compiler know they are local to that translation unit.
Without static the compiler cannot assume (barring LTO / WPA) that the function is only called once, so is less likely to inline it.
Demonstration using the LLVM Try Out page.
That said, code for readability first, m... |
7,096,637 | 7,097,609 | How can I get the file size in directory traversal? | How can I get the size of a file when I am using recursion to look at each file?
I'm getting the next error:
project.exe exited with code -1073741819
int dir_size(const QString _wantedDirPath)
{
long int sizex = 0;
QFileInfo str_info(_wantedDirPath);
if (str_info.isDir())
{
QDir dir(_wantedDi... | Its crashing because you are recursively evaluating the same folder again and again.
The statement sizex += this->dir_size(fileInfo.path()); calls the same function recursively with the same folder name.
So your stack keeps growing and eventually out of memory.
fileInfo.path() gives the same (parent) folder.
fileInfo... |
7,096,727 | 7,125,889 | Binaries for cpp-netlib | I would like to know if it is possible to get the binaries for the static library for windows (x86 and x64) now present in cpp-netlib for the version 0.9.1?
Frankly it is a pain to compile this on windows for me.
Thanks
| It seems that cpp-netlib is a header-only library, although it relies on some boost compiled libraries, such as Boost.System, Boost.Date_time, and Boost.Regex. You can easily find boost pre-compiled libraries all over the Internet. You will also need the boost headers to be in your build path as well. Even though cp... |
7,096,812 | 7,097,379 | What is the difference between valgrind and regular c++ run | I'm trying to identify a bug in I have in my code where I get seg. fault while trying to assign value to a pointer from a vector (it is describe better in the link). When I run the code using valgrind I don't get the seg.fault.
What does valgrind do differently. I think that I need to consider the memory management di... | From Valgrind FAQ:
4.4. My program crashes normally, but doesn't under Valgrind, or vice
versa. What's happening?
When a program runs under Valgrind, its environment is slightly
different to when it runs natively. For example, the memory layout is
different, and the way that threads are scheduled is different... |
7,097,457 | 7,104,437 | QuickFIX C++ library - general question regarding ThreadedSocketInitiator | I am new to QuickFIX and I have some basic question regarding QuickFix:
1)
Considering that at one time, there will be only one fix session between an acceptor and an initiator. I do not quite understand the purpose of ThreadedSocketInitiator and ThreadedSocketAcceptor classes.
Or do these classes exist to facilitate m... |
1) Quickfix uses 1 thread per session. Engine you can assume is the whole process.
ThreadedSocketInitiator is used when you want to use the engine as a client. You connect to another server and transmit messages. You initiate connections, hence the name initiator. You spawn a new thread for each session you set up w... |
7,097,679 | 7,097,793 | Simplest way to count instances of an object | I would like to know the exact number of instances of certain objects allocated at certain point of execution. Mostly for hunting possible memory leaks(I mostly use RAII, almost no new, but still I could forget .clear() on vector before adding new elements or something similar). Ofc I could have an
atomic<int> cntMyOb... | Have a "counted object" class that does the proper reference counting in its constructor(s) and destructor, then derive your objects that you want to track from it. You can then use the curiously recurring template pattern to get distinct counts for any object types you wish to track.
// warning: pseudo code
template... |
7,098,253 | 7,102,142 | Why would this give a Use of uninitialised value of size 8 | In my code I have a class named membrane with a function named exciteMod(), a function named decide() and a variable named delta_U. The first line of exciteMod() is this->delta_U = 0. In decide() I have an exponent of -delta_U (exp(-this->delta_U)). which cause an error Use of uninitialised value of size 8. What might ... | The most likely cause of uninitialized value is that at least one of b->nextU or b->U that you are adding to delta_U is itself uninitialized. That is:
foo = 0;
foo += some_uninitialized_value;
if (foo) // Valgrind warns here
You would like Valgrind to report when foo becomes uninitialized. Unfortunately, doing so pr... |
7,098,365 | 7,098,427 | Unusually low floating point accuracy when normalizing a vector | I have a short method in my code to normalize a vector (actually a PCL point) which produces results of low accuracy. The code:
void normalize(pcl::PointXYZ::PointXYZ * p){
float nf = 1/sqrt(p->x*p->x+p->y*p->y+p->z*p->z);
//nf is a normalization factor precalculated to eliminate two FP divisions.
p->x*=nf; p->y*... | According to my calculations, 0.587785244 is the correct result (I get 0.5877852727698576 using Perl). I suspect you're doing the calculation incorrectly in Mathematica.
|
7,098,369 | 7,098,539 | istream_iterator try to parse invalid data | Hi was I hoping someone would help understand this behaviour of the below code.
#include <iostream>
#include <algorithm>
#include <string>
#include <limits>
#include <fstream>
#include <iterator>
#include <stdexcept>
struct asound_stanza
{
unsigned index;
std::string name;
friend std::istream &operator>>... | If stream is in invalid state or if attempt to read from stream inside operator>> fails and sets stream to invalid state, istream_iterator sets itself to end of stream position. So iteration ends without even looking at partially parsed object.
|
7,098,432 | 7,098,540 | How can I sort a container based on std::tm? | I need to sort my custom class based on the std struct tm object. I would like to know if I am approaching this correctly and ask for suggestions for the comparison function. Originally, I was converting each std::tm member to some base number (like Ticks in .NET DateTime), but I thought that might be excessive.
I don'... | You can use mktime to convert a std::tm value to a time_t which can be compared.
|
7,098,497 | 7,098,714 | name of this c++ implementation pattern | There is certain implementation pattern in C++, that I describe below, it is used in std::iostream library and other similar libraries.
Can anybody recall name of this pattern?
The pattern is described like this:
- There is central class IO used for output of data, or for conversion of data (e.g, std::ostream).
- for e... | looks like it's the Herb Sutters' "Interface Principle"
at least I read it from one of his books
the interface must be minimal, all functions, which do not need private data (for compiling or runtime speed), should be in outer functions.
|
7,098,517 | 8,010,724 | Embed a web browser in a cross platform Gtk application | I need to embed a very simple browser ( can parse HTML, and JS Ext ) in a Gtk Widget hopefully in gtkmm. I looked into gtkmozembed, but the c++ wrapper is very out dated, so I tried to just write it in C, but I'm already committed to Gtk+ 3.0, and gtkmozembed doesn't work with Gtk+ 3.0. Is there a way to just extend Gt... | Just thought I'd come back and let anyone who cares know that our solution was to use Gtkmozembed. Only problem with it is that Gtkmozembed only runs using gtk+ 2 and I'm using gtk+ 3. The two can not exist in the same process, and I'm not migrating either project. So I'm running gtkmozembed in a child process that I u... |
7,098,737 | 7,098,777 | Should a Cache object read directly from filesystem? | I'm building a server that implement the tftp protocol. My homework requests the creation of a cache of recent requested files. What I would like to understand is about design, watch the example:
Server request file to the cache
The cache doesn't have file
The cache read from filesystem the file
The cache serves the fi... | From a complexity standpoint, I would definitely recommend that the cache reads the file from the file system. Your implementation will be much cleaner that way.
Digging deeper: you're touching on the single responsibility principle. Ideally, you want components of your system to do one thing, and do it well. What you ... |
7,098,834 | 7,127,330 | Windows service does not recognize network path. Whats the workaround? | We have a Buffalo NAS drive as a backup drive.
And when we map this drive as B:\ , our backup application seems to understand this and run as an application.
But when run as a service, it does not recognize the mapping and crashes.
I tried giving the path as \\\192.168.x.x\Backups\ as the backup path, the service runs... | You can map a network drive inside the service itself using the WNetAddConnection2 API function.
|
7,098,876 | 7,098,894 | Formatting multiple char* strings to an std::string | I have two char* strings and a char* literal that I need to combine into a single std::string. Below is what I am doing. It works, but I don't like the way it looks (3 lines to accomplish it). I am wondering if there is a better way to do it...
std::string strSource = _szImportDirectory;
strSource += "\\";
strSource... | std::string strSource = std::string(_szImportDirectory) + "\\" + _szImportSourceFile;
Is one obvious way.
Another way is to use std::stringstream:
std::stringstream s;
s << _szImportDirectory << '\\' + _szImportSourceFile;
std::string strSource = s.str()
That's the most flexible and maintainable way to do it but it s... |
7,098,904 | 7,099,004 | Stack overflow error when adding a member to a class in huge solution | Please look at this code:
class A
{
int a;
};
Then add one more member to class A:
class A
{
int a;
int b;
};
In my huge solution when I add one more member to a class (like member b in class A) I get stack overflow error. I assume that this is somehow related to writing to not reserved data adresses.
Is there any w... | Well, first question: Are you really adding an int? If yes, then this answer is applicable.
This can happen when:
Your class is so enormous that it's constructor will cause a stack overflow because it can not allocate enough memory on the stack to allocate memory for all members.
You are doing pointer arithmic somewhe... |
7,099,138 | 7,099,190 | Case insensitive find() method in string class |
Possible Duplicate:
Case insensitive std::string.find()
I want to make use of the std::string::find() method in a case insensitive way. I have come across various solutions suggesting the Boost library, but that solution is not applicable in my scenario.
Are there other ways to accomplish this?
| If you can't modify the string, make a copy of it. Convert all chars to lowercase in the string and then use find() with a lowercase string.
|
7,099,232 | 7,099,307 | Decompress bzip2 byte array | How would I decompress a bzip2-compressed byte array using boost? I found an example here, but the input is a file hence the use of ifstream. The documentation isn't very clear for me :(.
Edit: I'll accept alternatives to boost.
| Here's my code using DEFLATE compression in the boost.iostreams library; I'm sure you can hook in the corresponding BZip2 compressor instead:
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filter/bzip2.hpp> // <--- this one for you
#include <boo... |
7,099,505 | 7,100,449 | how set the windows clock using c++ | I'm trying set the windows system clock using C++.
I'm trying with the following code(not working):
#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
SYSTEMTIME st;
st.wDay = 1;
st.wMonth = 5;
st.wYear = 2011;
st.wHour = 12;
... | st is incompletely initialized and contains invalid values. Initialize it fully and the code works. If you had called GetLastError(), it would have clued you in right away because it was returning 87, which is ERROR_INVALID_PARAMETER. The day of week, seconds and milliseconds fields undoubtedly contain invalid valu... |
7,099,753 | 7,100,067 | How to store fixed length strings inside a std::vector | I want to mimic a structure:
char [][40] = { "Stack", "Overflow", "Exchange", "Network" };
using a std::vector, so I can populate it at runtime and dynamically change the size of the vector, but keeping the member elements located inside fixed size blocks.
Static initialization is not my question - I can do that using... | I'd use something like Boost.Array:
typedef boost::array<char, 40> arr_t;
std::vector<arr_t> vec;
{
arr_t arr = { "Stack" };
vec.push_back(arr);
}
{
arr_t arr = { "Overflow" };
vec.push_back(arr);
}
{
arr_t arr = { "Exchange" };
vec.push_back(arr);
}
{
arr_t arr = { "Network" };
vec.push... |
7,099,769 | 7,099,881 | Logging, How to get command end? | So I use such Log class:
#include <stdio.h>
#include <iostream>
class Log
{
public:
int i;
Log()
{
i = 0;
}
template <class T>
Log &operator<<(const T &v)
{
i++;
std::cout << i << ":" << v << ";" <<std::endl;
return *this;
}
Log &operator<<(std::ost... | Make operator<< return a temporary value which will place endl upon destruction and forwards all operator<< calls to the main object. This way, endl is guaranteed to be called exactly once.
class Log
{
struct EndlOnDeath {
Log* log;
EndlOnDeath(Log* ptr)
: log(ptr) {}
template<typename T> EndlOnDeat... |
7,099,776 | 7,099,804 | Memory visualisation for C++ linux app | I am looking for a tool that would help visualize the memory usage of an application and show what's using up most of the memory - i.e. what classes, how many objects, etc. There's a similar thread that discusses the same issue for windows but I need to do this on linux.
| Valgrind would be okay for Linux, too.
|
7,099,947 | 7,100,008 | namespace either undefined or redefined, why? | just a very small program to test how to use the namespace. I divide it into 3 files, since in large product, ns.h is the namespace interface and ns.cpp is the implementation. I cannot put all these stuff into one file.
Here is the code:
//ns.h
#ifndef MY_H
#define MY_H
namespace my
{
int a=1;
int b=0;
void... | Headers are for declarations, not definitions. That's nothing to do with the namespace problem.
//ns.h
#ifndef MY_H
#define MY_H
namespace my
{
extern int a, b; // declared, not defined thanks to 'extern'.
void test();
}
#endif
//ns.cpp
#include <iostream>
#include "ns.h"
int my::a=1; // now we provide the ac... |
7,099,957 | 7,100,055 | Implicit VS Explicit Conversion | The C++ Standard Library by Nicolai M. Josuttis states:
There is a minor difference between
X x;
Y y(x) //explicit conversion
and
X x;
Y y = x; //implicit conversion
Following to say: "The former creates a new object of type Y by using an explicit conversion from type X, whereas the latter creates a new object of typ... |
one uses a Y's constructor and one uses the assignment operator though.
Nope. In the second case it's not an assignment, it's an initialization, the assignment operator (operator=) is never called; instead, a non-explicit one-parameter constructor (that accepts the type X as a parameter) is called.
The difference bet... |
7,100,019 | 7,100,094 | Updating records in a binary file with C++ | I encountered a problem and my current knowledge of C++ is not enough to solve it. I looked for the answer in books of Stroustrup, but a full understanding of what I'm doing wrong for me not now.
So the essence.
I write to the file:
int i = 1;
int j = 2;
ofstream ofs("file", ios::binary);
ofs.write(as_bytes(i), sizeof(... | By default the file will be truncated (ios:trunc, i.e. the content is lost upon opening the file for writing).
For the second write operation explicitly add the flags ios:in AND ios:out despite the fact you're writing only. So essentially I'd use the following:
ofstream ofs("file", ios::binary | ios::in | ios::out | io... |
7,100,044 | 7,100,141 | Inserting and removing elements from an array while maintaining the array to be sorted | I'm wondering whether somebody can help me with this problem. I'm using C/C++ to program and I need to do the following:
I am given a sorted array P (biggest first) containing floats. It usually has a very big size.. sometimes holding correlation values from 10 megapixel images. I need to iterate through the array unti... | Change the data structure. Repeatedly accessing the largest element, and then quickly inserting new values, in such a way that you can still efficiently repeatedly access the largest element, is a job for a heap, which may be fairly easily created from your array in C++.
BTW, please don't talk about "C/C++". There is n... |
7,100,126 | 7,100,191 | C++ Multidimensional array | I have a 3D array
double values[30][30][30];
I have a loop where I assign values to the array;
Something like:
for(int z = 0;z<30; z++)
for (int y = 0;y<30; y++)
for (int x = 0;x<30; x++)
values[z][y][x] = intensity;
end
So this is how I am filling the array. The problem is that I want to create col... | This is really dependant on your datatypes. The easiest solution is using a struct:
struct data {
float intensity; // or replace 'float' with whatever datatype you need
float distance;
};
Use this struct instead of the datatype you're using now for the array, then later on set the values:
values[z][y][x].inten... |
7,100,225 | 7,100,328 | C# call method from C++ class | I'm trying to integrate with a windows based api using c-sharp and I've run into this issue.
The api sends me a pointer to a struct that holds a bunch of virtual methods
struct CApiInterface
{
virtual int __stdcall Version(void);
...
}
My question is, how can I call methods off this in C#? I'd like to do somethi... | Check out this question for an example of someone else who did the same thing. It seems to revolve around using delegates marked with the UmanagedFunctionPointerAttribute.
|
7,100,441 | 7,100,492 | How can you get the return value of a Windows thread? | I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return v... | GetExitCodeThread is the correct function. Here is the MSDN description of what it does:
This function returns immediately. If the specified thread has not
terminated and the function succeeds, the status returned is
STILL_ACTIVE. If the thread has terminated and the function succeeds,
the status returned is one... |
7,100,529 | 7,100,552 | Why is memset() incorrectly initializing int? | Why is the output of the following program 84215045?
int grid[110];
int main()
{
memset(grid, 5, 100 * sizeof(int));
printf("%d", grid[0]);
return 0;
}
| memset sets each byte of the destination buffer to the specified value. On your system, an int is four bytes, each of which is 5 after the call to memset. Thus, grid[0] has the value 0x05050505 (hexadecimal), which is 84215045 in decimal.
Some platforms provide alternative APIs to memset that write wider patterns to ... |
7,100,559 | 7,100,594 | Wordlist transfer for an anagram program | I'm almost finished with my program, but there's one last bug that I'm having problems ferreting out. The program is supposed to check about 10 scrambled words against a wordlist to see what the scrambled words are anagrams of. To do this, I alphabetized each word in the wordlist (apple would become aelpp), set that as... | Prevent issues, use normal functions:
getline(str, 30);
strncpy(strInit, str, 30);
Prevent more issues, use standard strings:
std::string strInit, str;
while (std::getline(myFile, str)) {
strInit = str;
// do stuff
}
|
7,100,593 | 7,100,614 | Null terminating int arrays | If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?
int *array = new int[x];
..do some stuff..
delete array;
I know for a char array it deletes up to a null character ... | The block of memory used by your array has some extra data in there, that isn't directly visible to your program, that tells delete how big the block is.
What you say about char arrays is not true, by the way - the presence of a NUL terminator isn't relevant to delete - it uses the hidden block size just like any other... |
7,100,634 | 7,640,855 | LevelDB asserts when deleting the LevelDB instance | I get some super annoying asserts when I try to delete the leveldb instance and I'm not sure why it's happening!
The assert is happening in the version_set.cc file:
void VersionSet::AppendVersion(Version* v) {
// Make "v" current
assert(v->refs_ == 0); // <---??? how do I avoid this assertion?
// the rest of the... | I got rid of the nested references, but that didn't solve the problem. As it turns out, the issue causing this problem was not quite where I was looking at. The issue occurs when a user gets an iterator to the database and fails to delete the iterator prior to deleting the database. This was discussed in a google group... |
7,100,733 | 7,100,761 | Scan for processes and do something when a specific is found | I want my C++ program to scan for processes and when a certain file.exe is running, I want my program to do something (irrelevant here). Could you help me with this task?
I found something on the internet. Is this ok ?
CreateMutex(NULL, FALSE, NAMEofTHEprocess_exe);
if (GetLastError() == ERROR_ALREADY_EXISTS)return 0;... | Here's a basic enumeration of running processes in Windows:
#define WINVER 0x0500
#define _WIN32_WINNT 0x0500
#define PSAPI_VERSION 1
#include <windows.h>
#include <tchar.h>
#include <psapi.h>
#include <sddl.h>
void ListProcesses()
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
MEMORYSTATUSEX statex;
... |
7,100,889 | 7,100,899 | How can I access local variables from inside a C++11 anonymous function? | I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):
float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return... | You need a closure.
float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});
In this case tot is captured by value. C++11 lambdas support capturing by:
value [x]
reference [&x]
any variable currently in scope by reference [&... |
7,100,919 | 7,100,944 | How to define attribute aliased name to a c++ function? | in my cpp file i have the following:
int A()
{
}
void B_A() __attribute__((alias ("A")));
and i am getting the error:
B_A() aliased to undefined symbol A;
however, as u can notice, A is being defined just before that.
so whats the problem!?
| From the docs:
In C++, the mangled name for the target must be used.
So, you need the mangled name of A, or you need to give A C linkage so its name doesn't get mangled in the first place.
|
7,101,013 | 7,101,049 | Strange "invalid conversion from <type> to <type>" error | Here is output:
g++ -DDEBUG -DUNITTEST -IC:/Users/Steven/Dropbox/Programming/entropy_p5_makefile/cpp/game/../include/ -O0 -g3 -Wall -c -fmessage-length=0 -o Input.o ..\Input.cpp
..\Input.cpp: In function 'void mousehookCustomRoutine(E_thread*, void*)':
..\Input.cpp:78:93: error: invalid conversion from 'LRESULT (*)(in... | First, don't cast function pointers to void *. It is never safe to invoke a function of one type after casting it to another, and so there's rarely, if ever, a need to make them void *.
Second, probably you're seeing a difference in calling conventions. The type of the hook parameter is, properly stated, (LRESULT (CALL... |
7,101,068 | 7,109,461 | Tftp protocol implementation and difference between netascii and octect | I'm building an application that is a server that implements the tftp protocol. I'm having hard times in understand what's the difference between ASCII format and binary format (netascii and octect) in tftp, and how should I read files differently as the protocol states.
I know that an ASCII char can be rapresented wit... | There are two passages which can help clarify what the purpose of netascii is in RFC-1350/TFTP:
netascii (This is ascii as defined in "USA Standard Code for Information Interchange" [1] with the modifications specified in "Telnet Protocol Specification" [3].)
The "Telnet Protocol Specification" is RFC-764, and it des... |
7,101,433 | 7,101,541 | C++ converting string to time_t question | Im trying to convert a string such as "12 August 2011" into time_t or that seconds elapsed, or whatever so I can use it to compare a list of dates.
At the moment, I have tried the following but the output seems to equal false! Also, the seconds elapsed seem to keep changing?
Is this correct?
#include <iostream>
#includ... | You should initialize the structs before use. Try this:
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>
using namespace std;
int main()
{
struct tm tmlol, tmloltwo;
time_t t, u;
// initialize declared structs
memset(&tmlol, ... |
7,101,862 | 7,103,289 | Want to make standalone program with cmake | My program uses giblib and Imlib2 library and it is built with cmake.
It works perfectly in my computer but not in other's.
I guess the reason is I installed every library what my program needs but other's doesn't.
My goal is making standalone program. (don't need to install any other library addtionally)
What should I... | Try starting with this options in your root CMakeLists.txt:
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
BUILD_SHARED_LIBS is only needed if your project has its own libraries (add_library).
With the -static linker flag, you need static libs for ALL your additional librar... |
7,101,875 | 7,101,900 | Function pointers and functors | Are function pointers functors ? Is there a virtual functor in use that helps sibling functors compile silently ?
| At least as the term is normally used in C++ (Warning: it's used entirely differently relative to other languages such as Haskell), a functor is a class (or an instance of a class) that overloads operator() so it can be invoked like a function.
Since they use the same syntax, a template can be written to accept either ... |
7,101,950 | 7,109,239 | opencv cvblob render issue | I just installed cvblob for object detection.
When I tried to run the program, the image would not show up and it gives me an error:
"VIDIOC_QUERYMENU: Invalid argument"
Here is the code.
#include "highgui.h"
#include "cv.h"
#include "cvaux.h"
#include "iostream"
#include <stdio.h>
#include <ctype.h>
#include <cvblob.... | That error is coming from the video capture system, not cvBlob.
I see a few issues:
You must test capture after creating it to make sure you have successfully opened a camera.
Your while loop should be testing frame, not capture to make sure you've successfully received a frame of video.
Are you sure you have a camera... |
7,102,087 | 7,105,966 | How to enhance the speed of my C++ program in reading delimited text files? | I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save with “#” delimited text.
When I execute C++ program, the time elapsed is 169 seconds.
UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the... | As Constantine suggests, read large chunks at a time using read.
I cut the time from ~25s to ~3s on a 129M file with 5M "entries" (26 bytes each) in 100,000 lines.
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
int main ()
{
ifstream input("in.txt");
ofstream... |
7,102,166 | 7,104,231 | CUDA Convex Hull program crashes on large input | I am trying to implement quickHull algorithm (for convex hull) parallely in CUDA. It works correctly for input_size <= 1 million. When I try 10 million points, the program crashes. My graphic card size is 1982 MB and all my data structures in the algorithm collectively require not more than 600 MB for this input size, ... | There is no out of bounds memory access in your code (or at least not one which is causing the symptoms you are seeing).
What is happening is that your kernel is being killed by the display driver because it is taking too much time to execute on your display GPU. All CUDA platform display drivers include a time limit f... |
7,102,354 | 7,102,390 | Is it possible to check if a function with a string as its name exists?(C++) | I want to be able to do something like this:
if (Is_Function("helloworld")
// Run code
| Simple answer: no
Complicated answer: yes if debugging symbols are turned on and you write some helper functions to look through the debug symbols. But this is really horrible, buggy (functions can be automatically inlined and will be magically absent from your symbol table), and most of all stops working as soon as yo... |
7,102,379 | 7,103,299 | Is there a way to not inherit "virtualness" of a function in a subclass? | Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?
The reason for ... | In C++03, no.
As others said, it is a compiler optimization (and a frequently used one) to de-virtualize he call whenever it can assess that the runtime type of the object.
However, in C++0x we get two new keywords: override and final and both can be applied to member functions (final can also be applied to a class).
... |
7,102,458 | 7,102,562 | Would this class have a Strict Weak Ordering | Say I had class/struct Foo
struct Foo {
int a, b;
bool operator< (Foo const& r){
return a < r.a;
}
bool operator== (Foo const& r){
return a==r.a&&b==r.b;
}
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };
Now bar == baz is false but so are bar < baz and baz < bar.
Note that here the order... | Technically yes, you are ordering them by the a member directly, which should be fine for eg. std::set. Basically they behave like integers, ie. if a < b and b < c then a < c, etc. I don't think operator == affects the validity of the ordering implied by operator <.
However - it is a bad idea to define two operators on... |
7,102,551 | 7,102,831 | Code standard (not style) enforcer for Eclipse | Is there some coding standard enforcer for use with Eclipse (a plugin or something)? I know I can use "Window > Preferences > [Language] > Code Style" to suggest conventions, but these are not enforced.
In other words, I want Coding standard violations to be marked as "Errors" and Coding style violations as "Warnings"... | You got several options to do that :
PMD http://pmd.sourceforge.net/eclipse/
Eclipse Checkstyle http://checkstyle.sourceforge.net/
Findbugs http://findbugs.sourceforge.net/
You can also integrate these plugins with your CI Server, for example Sonar For Hudson. Note that since 2011, Hudson has changed it's name to Jen... |
7,102,606 | 7,104,177 | SIGILL in Android NDK code | I have an NDK app out on market and got a native crash report about a SIGILL signal. (I use google breakpad to generate native crash reports.) Here are the details:
My app is compiled for armeabi-v7a, with NEON support.
It crashed on a NVIDIA Tegra 2 Processor, which is ARM-7 (Cortex-A9).
It happens every time. (conta... | Ok, I got it: the NVIDIA Tegra 2 only has 16 64-bit GPU registers, and therefore to target it you must compile using -mfpu=vfpv3-d16. The instruction in question uses register d16, which is "just too many". :(
Here is a reference to an NVIDIA forum where an employee mentions this limitation: http://developer.nvidia.com... |
7,102,632 | 7,102,655 | C++: Is it a bad idea to use the value of a function returning shared_ptr directly? | For example:
boost::shared_ptr<int> test() {
boost::shared_ptr<int> x(new int(3));
return x;
}
void function() {
int y = *test();
...
}
Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.
| In the general case, no. Your example copies the contents of the shared_ptr, and then the original value is deleted.
Now, the bigger issue here is that it's fantastically inefficient to do a dynamic memory allocation for an int, but I'm assuming you're not doing that in real code. :)
|
7,102,766 | 7,103,724 | Best C++ RPC library for Windows/Visual Studio | I know this kind of question is asked a lot but I have a set of requirements:
1. Be able to compile and develop in Visual Studio on Windows.
2. Be somewhat modern - Async/threaded, clean.
3. C++
I've looked at thrift, messagepack, and even protobuf+RPC. All of them have massive issues in Windows.
FYI - I'm no pro progr... | Did you consider using Protobuf together with Boost asio? Of course it is not an RPC library, so that part you would have to do at your own, but it would be asynchronous and fast.
|
7,102,904 | 7,102,992 | Can boost Pointer Container Library be used as thread safe container collection? | Can we use boost Pointer Container Library to keep an array of strings winth thread safe push and pop and all such operations?
| No, as far as thread safety goes the same rules apply to the pointer container library and the standard C++ library containers. They're both safe for simultaneous read access from different threads but must be protected by mutexes to prevent simultaneous write access.
This is because the containers in the pointer cont... |
7,102,922 | 7,103,358 | Does any change in program state constitute observable behavior? | Consider the two following programs:
program one
int main()
{
printf( "hello\n" );
}
program two
int main()
{
srand( 0 );
if( rand() ) {
printf( "hello\n" );
} else {
printf( "hello\n" );
}
}
Do they have the same observable behavior or not? According to C++ Standard (1.9/6) the observable ... |
Do the two programs above have the same observable behavior?
As you say, that depends on whether srand() and rand() have observable side effects. They shouldn't; there can be no external noise source, since the sequence is required to be repeatable for a given seed, and there is no other reason to perform I/O or acce... |
7,102,984 | 7,103,020 | Why is QWidget's destructor not virtual? | Looking at qwidget.h, I found the destructor as below:
~QWidget();
I was wondering why this is not declared as virtual
| The destructor is virtual, because QWidget derives from QObject which does have a virtual destructor. Why it's not declared virtual in the code is a either style issue or a harmless mistake. I would have declared it virtual myself.
|
7,103,145 | 7,103,232 | What are exact requirements on automatic storage duration? | Depending on the compiler the following code:
int main()
{
srand( 0 );
if( rand() ) {
char buffer[600 * 1024] = {};
printf( buffer );
} else {
char buffer[500 * 1024] = {};
printf( buffer );
}
return 0;
}
when ran on a system with maximum stack size equal to 1 megabyte either pri... | "Lasts until" also is a minimum.
|
7,103,625 | 7,103,696 | is it possible to have a new file for each new day with log4cXX | I know the rollingPolicy parameter for log4cxx config file, but I can't manage to have the config file which can tell the logger to create a new file each new day, how could I achieve this result ?
| Yes. Using rolling style of Composite like this:
<appender name="LogAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4j.Util.PatternString" value="LogFile.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBac... |
7,103,679 | 7,104,498 | C++ Visual Studio 2010 not linking native static library | I am converting a C++ Visual Studio 2005 project to Visual Studio 2010, and I have used this guide in the process.
I have one issue left which is, that the linker does not link a native static library (it is not a .NET assembly but a third part library sqsapi32.lib). I have included the library sqsapi32.lib in the Prop... | The warning and the error you've shown aren't necessarily linked (no pun intended!).
To get around the error, ensure the sqsapi32.dll is placed in the same location as the exe you're trying to run.
Good luck,
|
7,103,710 | 7,104,044 | Properly (independent of 32bit/64bit) saving a float to binary ofstream | So apparently on my machine, float, double and long double each have different sizes each. There also doesn't seem to be a strict standard enforcing how many bytes each of those types would have to be.
How would one, then, save a floating point value into a binary file, and then have it read properly on a different sys... | You have to define a format, and implement that. Typically, most of the
network protocols I know use IEEE float and double, output big-endian
(but other formats are possible). The advantage of using IEEE formats
is that it is what most of the current everyday machines use
internally; if you're on one of these machine... |
7,103,752 | 7,103,926 | How does this variable parameters list function call works? | When a program needs to communicate using Microsoft RPC developers typically write a IDL definition for all methods, for example:
error_status_t rpcMyInterfaceGetFile( [in] const GUID fileId, [out] BYTE_PIPE filePipe );
which is compiled by MIDL compiler and produces a wrapper function:
/* [fault_status][comm_status] ... | Well, not quite sure but reading between the lines in the MSDN doc (which says that the last argument is Pointer to the client-side calling stack) it sounds like the NdrClientCall2 function can take the STUB_DESC structure, figure out what the argument types and sizes are, extract them from the stack, do the work of ca... |
7,103,964 | 7,105,064 | Class with virtual function, when derived from QObject, leads to linking error | Following is the code that works fine
class HttpService {
public:
virtual ~HttpService(); // implemented in .cpp
protected:
HttpService(struct MHD_Connection *conn) {}
};
class HttpFileService : public HttpService
{
public:
virtual ~HttpFileService() ; // implemented in .cpp
protected:
HttpFileService(s... | Force running qmake and see if it works.
|
7,104,079 | 7,105,916 | How to format a long adding thousands separator on Arduino | I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.
I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).
In a nutshell, how do I code the formatLong function?
long longToBeFormatted = 32432423... | I'm not sure what toolset gets used on Arduino. Sometimes the library will support a non-standard 'thousands grouping' flag - the single-quote character is the typical extension:
printf("%'ld",long_val);
If your library doesn't support this, something like the following might do:
#include <stddef.h>
#include <string.h... |
7,104,342 | 7,104,372 | What does '&' do in C/C++ and what is its equivalent operator in perl? | I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C.
What does the condition if ((flags & 0x400) != 0) mean? How do I do that in perl?
Is if ($flags == "\x400") correct?
| & is a bitwise AND. See Bitwise operators.
So flags is being treated as a series of bits, and then you AND it with something which has exactly the bit set that you want to check. If the result is non-zero, then the bit is set, otherwise the bit you were looking at isn't set. In particular, in your example 0x400 = 0100 ... |
7,104,889 | 7,104,943 | How to properly define destructor | I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.
What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what th... | In C++ you need to free the memory manually. There's no garbage collector. You obviously need to free the memory manually inside your destructor. If you allocated the memory using new, you need to use delete for each resource you allocated with new inside the deconstructor, for example:
class1::~class1(void)
{
dele... |
7,105,202 | 7,105,239 | C++ equivalent of Python properties | Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters?
| Yes, explicit getter and setters would be the closest construct in C++.
|
7,105,284 | 7,105,367 | C++ Initializer lists | I have to fill a std::vector with elements of type struct MHD_OptionItem.
This struct have this implementation:
struct MHD_OptionItem
{
enum MHD_OPTION option;
intptr_t value;
void *ptr_value;
};
I have tried this way:
vector<struct MHD_OptionItem> iov;
if(...)
iov.push_back({ MHD_OPTION_NOTIFY_COM... | Assuming you cannot change the struct or you want to leave it a POD:
void f()
{
struct {
MHD_OptionItem operator ()(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) {
MHD_OptionItem x = {opt, val, ptr};
return x;
}
} gen;
vector<struct MHD_OptionItem> iov;
if(... |
7,105,376 | 7,105,491 | Why do I get strange result when & (anding) bits on __int64 variable? | Here is the code:
#include <iostream>
using namespace std;
template<class T>
void printbinary3(T num){
for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
if((1 << i) & num)
cout << "1";
else
cout << "0";
}
cout << endl;
}
int main ()
{
char a = 1;
short b = 1;
int c = ... | In your printbinary3 function:
void printbinary3(T num){
for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
if((1 << i) & num)
Here, you are creating a literal 1 of type int, which most probably is 32 bit. If T = __int64, you will shift it for too many bits, leading to an overflow and the warning.
Instead of us... |
7,105,380 | 7,105,526 | How does the C++ compiler decide which of these functions is called? | Consider the following setup:
I am given an interface
template<class T>
void FooClass<T>::foo(boost::function<double (int)> f)
{...}
I want to implement f using a Functor:
class MyFun {
public: double operator()(int a) {do something...;}
}
However there is another function defined in the interface
template<cla... | The compiler 'preferres' the second definition because the template version results in an exact match for the function object parameter, whereas the boost::function parameter needs an implicit conversion to be accepted (and implicit conversions are considered after direct overload resolution). You can achieve what you ... |
7,105,449 | 7,106,231 | OpenGL perspective and lighting not working? | EDIT: A few people have said to use glNormal3f() to solve my lighting problem, but I researched and implemented that just now and it didn't change anything at all.
I'm kind of new to OpenGL so I guess I'm doing something wrong, but I followed the examples in the Red Book as closely as I could and I just can't figure ou... | You are drawing the elements around the origin (0,0,0) but you don't move the "camera" at the begining. so your are looking from the origin point at the scene, which is inside your elements.
try if
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glTranslate3f(0, 0, -10);
works to fix it
and for Perspective rendering... |
7,105,620 | 7,105,693 | Simple operation to waste time? | I'm looking for a simple operation / routine which can "waste" time if repeated continuously.
I'm researching how gprof profiles applications, so this "time waster" needs to waste time in the user space and should not require external libraries. IE, calling sleep(20) will "waste" 20 seconds of time, but gprof will not ... | Another variant on Tomalak's solution is to set up an alarm, and so in your busy-wait loop, you don't need to keep issuing a system call, but instead just check if the signal has been sent.
|
7,105,628 | 7,106,352 | c++ vector with strict ownership semantics | This is not a question about putting std::auto_ptr into std::vector.
Is there some vector equivalent of std::auto_ptr in std::, std::tr1:: or boost::? I use std::auto_ptr in function parameters and return values to decalre ownership semantics of these functions. But this way I can pass only single objects. As a tempor... | Without any particular reason as to why you need to maintain a vector of pointers, the first solution would be to ditch all the complexity and go for the simple:
std::vector<Type> f();
Ownership of the objects is unique (the vector owns them), and while the code looks like it is copying the vector on return it will be... |
7,105,678 | 7,105,749 | C++ loop until keystroke | If I want to loop until a keystroke there is a quite nice Windows solution:
while(!kbhit()){
//...
}
But this is neither an ISO-Function nor works on other Operating Systems except MS Win. I found other cross-plattform solutions but they are quite confusing and bloated - isn't there another easy way to manage thi... | You can use the next version of kbhit() for *nix OSes:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON... |
7,105,845 | 7,105,894 | Creating a vector of set | In my code I have a vector defined:
vector<vector<vector<vector<shared_ptr<foo> > > > > fooBoxes;
I am initializing the vector using:
int BOX_NUM = 12 //this is actually defined elsewhere
fooBoxes.resize(BOX_NUM);
for (int i = 0; i<BOX_NUM; i++){
fooBoxes[i].resize(BOX_NUM);
for (int j = 0; j < BOX_NUM; j++){
... | That depends on what you want to achieve. Your code will most definitely compile if you remove fooBoxes[i][j][k].resize(0); since the std::set does not support this function.
|
7,106,149 | 7,106,267 | how do i interact with a pc camera using c++ | i intend to interact with a pc camera using c plus plus. Are there any libraries you can recommend or ways to go about ? The idea is to take shots with a Samsung wireless cam then get the images transferred unto a pc with cam and on the pc show images as per the face detection using the cam . any ideas where to start ?... | If you're on Linux I think libwebcam would be a good start. Take a look at the example viewer app to get further details in using it. That is for camera access and general functionality. For face detection I guess you could use OpenCV(I haven't use it myself for this particular purpose so I cannot comment on its face d... |
7,106,346 | 7,106,374 | C vs C++ - cross-platform | I have a very quick question to which I havn't found an answer for.
Are there any major platforms (Windows, MacOS, unix, linux, Android, iOS, etc....) out there that supports C but not C++?
Thanks
| C and C++ are not operating system dependant. If there is a compiler that can compile the C/C++ code to execute not he current CPU. All is good.
|
7,106,408 | 7,106,448 | Global Object in singleton | In the Singleton pattern why is that we have to use a static object and not a global object?
I tried the following
class Singleton;
Singleton* instance1 = NULL;
class Singleton
{
private :
Singleton()
{
}
//static Singleton* instance1;
public:
static Singleton* getinstance()
if(... | If you make it a global object, then everyone has access to it, and anyone can use it without calling getInstance(). If so, then what is the purpose of getInstance() then? First time, you will call it to create the instance, then you wouldn't be required to call getInstance(), since after the first call, you can direct... |
7,106,484 | 7,106,623 | Programatically make a QToolButton identical to one from Qt Designer | I need to make a QToolButton that looks exactly like the default QToolButton you get when you drag one into your form in Qt Designer. Simply creating a QToolButton like this:
QToolButton *toolButton = new QToolButton(this)
does not work. You get a button, but it has no background (although it does display text). I tri... | It works for me, but you do have to set the geometry/text on it.
you can look in the file generated by UIC on your ui file with an example QToolButton to see what you are missing.
Make sure that the toolbutton has the correct parent - this could result in drawing strangeness if it is wrong.
e.g:
QToolButton* tb = new... |
7,106,714 | 7,107,873 | Best way to transfer struct from one process to another? | I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:
typedef struct tagTDATA {
BYTE c1;
DWORD dw1;
DWORD dw2;
cha... | It sounds like you are looking for an asynchronous IPC mechanism. Sockets are probably the easiest way to achieve this. Pipes would be another obvious alternative, and there are many higher level libraries available, but I think sockets sound like the best fit.
|
7,107,025 | 7,107,128 | unbuffered std streambuf implementation | for some quick testing of a serialization library I want to create a streambuf that can read/write to/from a socket. I do not want to use a buffer in the streambuf, but let the socket handle this. I am sure the serialization lib will only call std::istream::read and std::ostream::write. A quick look at Microsoft's basi... | It's (almost?) impossible to implement a std::streambuf without a buffer. You will have to overload underflow and overflow as many of the public interfaces to std::streambuf won't go via xsputn or xsgetn. E.g. sputc, sbumpc, etc. Even sputn is not guaranteed to cause a call xsputn depending on the state of the internal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.