question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,794,005 | 6,799,855 | Qt 4.8 beta and Mac OSX Lion, Phonon error | After a successful install of mac OS 10.7 I tried to compile my qt 4.7 project.
I had many warnings of "unsupported mac os x version". I thus decided to use Qt 4.8 beta and now, all the warnings are gone.
However, I now have a linker problem using Phonon:
dyld: Library not loaded:/Users/pulseagent/repos/build2/Desktop/... | For now I decided to stick with Qt 4.7.3, to remove the warnings I hacked the qtglobal.h and added Mac 10.7 as a supported version.
It seems to run fine ...
|
6,794,330 | 6,794,461 | how to get domain name in mongoose server c++ | I am using http://code.google.com/p/mongoose/ server inside my c++ application. I am looking a way to find domain name in c++ code.
Is there any api in mongoose to get current domain name ?
| You can retrieve it by calling -
const char *value = mg_get_header(connection, "Host");
|
6,794,463 | 6,794,629 | print callstack of a thread (c++), StackWalker or not? | Needing to print callstacks of C++ application thread by thread handle, I turned to StackWalker which is mentioned in previous stackoverflow answers.
However, the StakWalker code is dated 2005. I suspect something changed since then.
When I compile and run it, I get error (below), and output seems to be incomplete, tru... | This is not a bug from StackWalker sample provided on CodeProject. It is because of missing symbol files. Download and install the the symbol files (debugging symbols) for your OS and then retry.
http://msdn.microsoft.com/en-us/windows/hardware/gg463028
|
6,794,590 | 6,794,646 | How does file encoding affect C++11 string literals? | You can write UTF-8/16/32 string literals in C++11 by prefixing the string literal with u8/u/U respectively. How must the compiler interpret a UTF-8 file that has non-ASCII characters inside of these new types of string literals? I understand the standard does not specify file encodings, and that fact alone would make ... | In GCC, use -finput-charset=charset:
Set the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default is UTF-8. This can be overridden by either the local... |
6,794,710 | 6,804,297 | qt Qmake generating pkgconfig for a project | I have been told that it is possible to generate a pkg-config file through qmake, but I have no idea how to do it. I have been looking online for a while, and it seems as though it is something you just have to know how to do. Can someone give me an example, or point me to some sort of guide/tutorial?
| Is this what you are looking for?
To generate pkg-config using qmake you have to add to (modify) your project file (*.pro file):
unix {
CONFIG += link_pkgconfig
PKGCONFIG += <pc_file_without_extension>
}
|
6,794,731 | 6,794,818 | Optimizing a recursive double linked list delete node multiple times | I wrote a recursive doubly linked C++ functions to delete all the nodes in a doubly linked list having a certain value. Is it possible to optimize this? Thank you.
struct marynode {
int value;
marynode* next;
marynode* prev;
};
void DoubleLinkedListDeleteMultiple(marynode*& llist, int value){
marynode... | Is something wrong with std::list?
Also, structs + global functions? You probably want to use object oriented constructs like member methods instead.
To optimize this particular code a little, I'd change your recursive call to a while loop.
while(llist != NULL) {
if(llist->value == value) {
if(llist->pre... |
6,794,829 | 6,794,946 | Error c2259 implementing interface class from IUnknown | I'm trying to add a c++ project to my c# code and I'm trying to implement the IUnknown interface. I keep getting an error about c2259: cannot instantiate abstract class.
I've tried to play with some things like making the class a ref class and changing the implementation but nothing seems to work. Below is some of the ... | You need to implement the methods inherited from IUnknown: QueryInterface, AddRef, and Release. Failure to do that means your class still has pure virtual methods, and the compiler is correct to forbid you from instantiating such a class.
|
6,794,995 | 7,365,506 | Design classes for "two-dimension"-like expansion by inheritance | I'd like to make two base classes (e.g. figure and move) with some children for each one(cube, sphere and so on for figure; shift, rotate, rescale and so on for moves). Initial number of figures and moves is unknown - it must be expandable. Each move should know how to move each figure, so having N figures and M moves ... | Well, my current solution is to use typeid/typeinfo to identify figure/move pair and call corresponding function (non-member) to move figure by this move from global object of map type like this
typedef pair<string, string> fm_pair_t;
typedef figure (*fm_act_f) (const figure& F, const move& M);
map<fm_pair_r, fm_act_f>... |
6,795,049 | 6,795,098 | Deprecated Header warning (C++) | I keep receiving the deprecated header warning:
#ifdef __DEPRECATED
#warning This file includes at least one deprecated or antiquated header. \
Please consider using one of the 32 headers found in section 17.4.1.2 of the \
C++ standard. Examples include substituting the <X> header for the <X.h> \
header for C++ include... | The headers coming from the C world are to be prefixed with c, and not postfixed.
That means you'll want to include cmath, cassert and ctime.
In those cases, only the header name is subject to deprecation, not the contents.
Note: you can deduce which headers are subject to this kind of deprecation by matching their nam... |
6,795,123 | 6,795,156 | How to initialize char**? | Here is my piece of code:
char** filename;
*(filename) = "initialize";
printf("filename = %s",*(filename));
I got this error when I tried to run it:
Run-Time Check Failure #3 - The variable 'filename' is being used without being initialized.
Is there any way to fix this?
| You need to allocate room for filename using new or malloc. As it is, filename is just a pointer to a random area of memory you have not requested...
filename = new char*;
|
6,795,335 | 6,795,415 | Header files repeatedly used in different header files in my static library | Since I got multiple classes and utility-functions I reuse on a regular basis, I started to create a static library for those parts.
Until now, most of those header files with class and function declarations #include the same "global" header file which itself #includes other header files (like <string> <windows.h> etc.... | I think you only have the option of defining a general header file that all other header files include and that defines WIN32_LEAN_AND_MEAN.
Otherwise you could instruct the user to include such definition in his own files, but his would be error prone.
As to inclusion of <windows.h> I think that it will not be include... |
6,795,382 | 6,795,538 | Performance of drawing function | I'm creating small engine/framework for making games. It's kind of simple question but I haven't found an answer so I'd like to consult you.
There are some classes derived from Graphic with the Draw(...) function. Draw() will be called dozens or maybe even hundreds of times (if there are many sprites to render). Draw()... | Any object which needs to be drawn will be affecting a large number of pixels; it is likely that drawing itself will take much more time than calling the drawing function, so the calling overhead will be negligible. Don't worry about it until profiling shows it to be a bottleneck.
|
6,795,608 | 6,795,669 | c++ parse file and read binary | I want to save email accounts and passwords, which I will have previously encrypted with an algorithm. They need to be saved and read as binaries, with fwite and fread. What I want, is to be able to know if it's a pass or an email account, saving it between < e > < e > and < u > < u >
For example:
<e> !"§(!"$)Asdn12§(!... | If usernames and passwords are always paired I suggest you store the length (in number of bytes) before each username and before each password. This way you can read the length (say a 4 byte integer) and know how long the next username / password record will be. You can then repeat this without worrying about searchi... |
6,795,628 | 6,795,760 | capture C++0x flag inside the program |
Possible Duplicate:
GNU C++ how to check when -std=c++0x is in effect?
What I want to do is:
#if defined(CPLUSPLUS_OXFLAG)
//do something
#else
//do something else
#endif
Now how can I capture -std=c++0x argument passed to the compiler(g++) to define my CPLUSPLUS_OXFLAG flag?
| The GCC documentation states that the preprocessor symbol __GXX_EXPERIMENTAL_CXX0X__ is defined when compiling with -std=c++0x.
|
6,795,629 | 6,795,680 | How does one downcast a std::shared_ptr? | Consider:
struct SomethingThatsABase
{
virtual bool IsChildOne() const { return false; }
virtual bool IsChildTwo() const { return false; }
};
struct ChildOne : public SomethingThatsABase
{
virtual bool IsChildOne() const { return true; }
};
struct ChildTwo : public SomethingThatsABase
{
virtual bool I... | This ought to work:
if (ptr->IsChildOne())
{
SomeClientExpectingAChildOne(std::static_pointer_cast<ChildOne>(ptr));
}
|
6,795,890 | 7,562,555 | Weird use of `?:` in `typeid` code | In one of the projects I'm working on, I'm seeing this code
struct Base {
virtual ~Base() { }
};
struct ClassX {
bool isHoldingDerivedObj() const {
return typeid(1 ? *m_basePtr : *m_basePtr) == typeid(Derived);
}
Base *m_basePtr;
};
I have never seen typeid used like that. Why does it do that weird dance ... | I think it is an optimisation! A little known and rarely (you could say "never") used feature of typeid is that a null dereference of the argument of typeid throws an exception instead of the usual UB.
What? Are you serious? Are you drunk?
Indeed. Yes. No.
int *p = 0;
*p; // UB
typeid (*p); // throws
Yes, this is u... |
6,795,927 | 6,795,978 | Reducing for loop overhead | I have a need to iterate through an amortization formula, which looks like this:
R = ( L * (r / m) ) / ( 1 - pow( (1 + (r / m)), (-1 * m * t ) );
I'm using a for loop for iteration, and incrementing the L (loan value) by 1 each time. The loop works just fine, but it did make me wonder about something else, which is th... | Compilers would exercise an optimization technique here which is called loop invariant code motion. It does pretty much what you did manually, i.e. extracting a constant part of expression evaluated repeteadly in loop into a precomputed value stored in variable (or register). Hence it is not likely that you gain any pe... |
6,796,157 | 6,797,458 | Unicode encoding for string literals in C++11 | Following a related question, I'd like to ask about the new character and string literal types in C++11. It seems that we now have four sorts of characters and five sorts of string literals. The character types:
char a = '\x30'; // character, no semantics
wchar_t b = L'\xFFEF'; // wide character, no... |
Are the \x/\u/\U character references freely combinable with all string types?
No. \x can be used in anything, but \u and \U can only be used in strings that are specifically UTF-encoded. However, for any UTF-encoded string, \u and \U can be used as you see fit.
Are all the string types fixed-width, i.e. the arrays ... |
6,796,238 | 6,796,275 | print element from list | I have a list that prints out weather data for a year. The data is listed by month and I need to find the yearly totals after the list is sorted. I used the list.sort() function to sort the list by month. From there, I need to print a specific element of data, but I'm unsure how to do so. here's an example of the unsor... |
I was thinking of sorting the list by whatever I need to get. For example, sort by temp, and display the last temp.
Sorting is slow. Sorting just to perform analysis on data is baaad.
Why not track maxima and minima as you add items to the list? Perhaps with a wrapper class.
If this is not feasible for whatever reaso... |
6,796,344 | 6,796,392 | Do any C or C++ compilers optimize within define macros? | Let's say I have the following in C or C++:
#include <math.h>
#define ROWS 15
#define COLS 16
#define COEFF 0.15
#define NODES (ROWS*COLS)
#define A_CONSTANT (COEFF*(sqrt(NODES)))
Then, I go and use NODES and A_CONSTANT somewhere deep within many nested loops (i.e. used many times). Clearly, both have numeric values t... | It depends on your compiler.
#include <math.h>
#define FOO sqrt(5);
double
foo()
{
return FOO;
}
My compiler (gcc 4.1.2) generates the following assembly for this code:
.LC0:
.long 2610427048
.long 1073865591
.text
.p2align 4,,15
.globl foo
.type foo, @function
foo:
.LFB2:
movsd .LC... |
6,796,655 | 6,796,711 | Why use one vs the other: `boost::shared_array` VS `boost::shared_ptr<std::vector>`? | So to deal with large blobs of memory either for an image or similar there are clearly lots of options.
Since I'm a fan of smart pointers and RAII I'm wondering about whether it's smarter to go with :
a shared_ptr to a std::vector
or
to go with a shared_array pointing to a dynamically allocated array.
What are t... | It's the same as comparing std::vector vs. C array.
Think about shared_array as a RAII C array. What you get is just automatic memory deallocation. Useful in cases when you deal with 3rd-party code that returns arrays.
Theoretically it's faster than std::vector in some edge cases, but much less flexible and less sec... |
6,796,808 | 6,796,844 | Is there a way to set the width of each field at one shot instead of setting every time using streamio? | I need to get the date and month in two digit format. But instead of using setw all the time, is there a single setting to say that set every field to minimum 'x' length.
void getDate(std::string& m_resultDate)
{
time_t curTime;
struct tm *curTimeInfo;
std::stringstream sCurDateTime(std::stringstream::out ... | Iostreams are fickle, and you cannot really rely on the various formatting flags to persist. However, you can use <iomanip> to write things a bit more concisely:
#include <iomanip>
using namespace std;
o << setw(2) << setfill('0') << x;
Modifiers like o << hex and o << uppercase usually persist, while precision and fi... |
6,797,045 | 6,797,077 | Pointer to a typedef with incomplete type | Is there any way to declare a pointer to an incomplete type that will be set by a typedef in the implementation?
Here is exemple of what I want:
#ifndef TEST_H
#define TEST_H
namespace std {
class string; // THIS WON'T WORK!
}
struct Test {
std::string *value;
};
#endif
string is a typedef to basic_string, ... | No, it's not.
Really, at this point, you're just going to have to #include <string>. It's not harmful because you can't have a circular dependency with string: standard headers don't even know that your headers exist!
A std::string* is usually wrong, anyway.
|
6,797,074 | 6,863,913 | Passing array of template typedef's to constructor | I have a template class in a header that fails to compile, but when I try to make a minimal show case, it compiles fine. I'm trying to make a class that can be constructed from an array, deducing the length automatically. The error is "reference to a zero-sized array is illegal", which makes no sense, as it should au... | I finally figured it out. The constructor with a template type capacity was failing when the class also had a member function capacity. Whoops. Problem goes away when I rename with template type to Cap
|
6,797,178 | 6,822,151 | How to create a game save file format in c++ using STL | I just learned about the i/o part of the STL, more specifically fstream. Although I can now save binary info and classes I've made to the hard drive, I am not sure how to define how the info should be read.
I saw the answer for making a file format from this post:
Typically you would define a lot of records/structure... | The first stage in determining how to structure your save-file is determining what information needs to be stored. Presumably, you have a list of entities, each of which with generic information (probably derived from one of a few base classes), such as position, velocity etc.
One of the best things you can do to impl... |
6,797,280 | 6,798,441 | Mac OSX 10.7 Lion Audio Unit Effect template Failing to compile | I just upgraded to Mac OSX 10.7 Lion. First of all, I hate the new spaces, I dislike not being able to access any directories deeper than my user directory, but lets get to the question.
I develop Audio Unit Plugins. I have a few whose code is compiling and working perfectly (they're even released for sale) in XCode 4.... | Search in the Xcode documentation for Technical Note TN2276 for instructions on updating an existing audio unit for Lion.
You have to replace
COMPONENT_ENTRY(TestAU)
with
AUDIOCOMPONENT_ENTRY(TestAU, Filter)
But there is a little more so read the document.
Edit:
BTW regarding your comment about not being able to ac... |
6,797,384 | 6,797,413 | C++ string turning into a pointer | I have a function with the following declaration:
void playCard(string card);
and the following implementation:
void Player::playCard(string card)
{
cout << "Playing " << card << "!" << endl;
// Find iterator representing the card to be played
vector<Card*>::iterator iter;
for(iter = hand.begin(); ite... | You want break instead of continue inside the loop.
They're kind of similar; continue means continue with the next iteration of the loop, break means break out of the loop.
|
6,797,527 | 6,797,546 | Nested Comments in C++ | This should be a common problem and possibly similar to some question here but i am looking foe the best way to comment out multiple lines (rather methods ) in C++ which have comments within them .I did check out some posts on SO but couldnt get the full details on using something like if #0 .
I did check out this post... | You are almost correct; essentially it is being suggested to "if-def" the section of code out. What you want to do is use the precompiler directive #if to block the code for you. Ex below shows that I want to ignore everything between the if and endif.
#if 0
/* Giant comment
it doesn't matter what I put here */
// ... |
6,797,570 | 6,797,583 | Hexadecimal vs decimal on binary conversion | For example, here are two ways to set an integer variable (say C++):
int x = 0xFF;
int y = 255;
Which statement would compile faster to set the actual bits to the integer value?
Edited: *compile changed from execute. I assumed the conversion to binary was at execution time, but seems to be at compile time given @munto... | There is absolutely no difference in execution time, and probably no difference in compilation speed.
Added in response to comment:
Here's what happens. The compiler has a parser, probably recursive-descent, and at bottom it calls a lexer to get tokens. In this case the token after = is a number, which it can tell by t... |
6,797,649 | 6,797,667 | Initializing a static boost::unordered_map | I have a few static unordered_maps in my application that I would like to be able to initialize on start up. They are not part of a class. In my initial setup, the header and source file were as follows:
namespace Game
{
namespace Elements
{
enum Element
{
Air = 1,
Dark ... | You have to put the definitions in the correct namespace. Otherwise you are defining two new maps in the global namespace, instead of the ones in Game::Elements:
namespace Game {
namespace Elements {
boost::unordered_map<Element, std::string> ElementNameMap = boost::assign::map_list_of
(Air, string("Air"))
(Da... |
6,797,813 | 6,797,848 | Is destructor required for a class with structure of pointers | I have a class which has a struct with pointers as one of its member.
struct group {
void *v1,
void *v2;
};
class A {
A (group& handle)
: m_handle(handle)
private :
group m_handle;
};
There are no pointer members in class A. I don't see any issue (such as memory leaks) when no destructor is defined ... | Yes, v1 and v2 could be leaked, if they aren't deallocated in some other part of your program. So, in the destructor of A you can delete v1 and v2 (if it's appropriate to), or you can just add a destructor to group (in c++, a struct is exactly like a class except for default visibility - stuff is public by default rath... |
6,798,507 | 6,798,525 | Infinite "true" while loop | I know I am probably just doing something dumb wrong, but I need to take a number from the user, create an infinite loop (by making my while statement true) of multiples of 2. I got the math to multiply the number from the user times itself, but I can't get it to loop. This is the last part of my homework for the week ... | There is unreachable code at: cout << e << ", ";
Perhaps this was meant to go in the while loop?
You are assigning e the value of d*d over and over. Because d*d does not change, the value of e never changes. Perhaps you should initialize e to the number you want outside of the loop, and then set e = e * 2 inside of the... |
6,798,516 | 6,798,529 | Class with non-default constructor, within a class (C++) | I have a class which takes two arguments on it's constructor, an int and a void(*)(void) so normally when I need to call it I do it like this:
obj_child (int_value, pointer_to_foo);
Now what I want is to instantiate the obj_child with constant arguments, within another class.
So I tried:
class obj_parent
{
priva... | You have to initialize the object in the constructor of the class.
obj_parent() : child_instantiation (int_value, pointer_to_foo) {}
|
6,798,575 | 7,199,361 | C++ Qt Reflection with Copy and Assignment | As the QObject documentation and many others explain, a QObject has an identity and thus hides its copy constructor and assignment operator.
However, I'm not deriving from QObject for its dynamic properties feature or the signals/slots feature. I only want reflection, or the ability to access Foo::staticMetaObject.
cla... | If you are only interested in having reflection for
the class name,
enums and flags (Q_ENUMS, Q_FLAGS),
class info (Q_CLASSINFO),
you can use Q_GADGET instead of Q_OBJECT:
class Foo {
Q_GADGET
Q_ENUMS(Color)
public:
enum Color { Blue, Red, Pink };
private:
Color color;
};
which will declare and defi... |
6,798,742 | 6,800,024 | How to create boost::function from template signature | Recently I was trying to create flexible observer pattern implementation which hides boost::signal. I almost succeeded.
I have a Observer class which has to have an update method matching signature provided by template parameter.
Example of use:
Observable<void(float, float)> observable;
Observer<void(float, float)> ... | No, boost::function won't help you either. 13.4.3 says
Nonstatic member functions match targets of type
“pointer-to-member-function;” the function type of the pointer to
member is used to select the member function from the set of
overloaded member functions.
This means you cannot take an address of overloaded ... |
6,798,817 | 6,798,838 | how to pass variable argument to exe? | Okay, let's say that I have b.exe, which takes a string argument.
I want to invoke b.exe within a.cpp, with system:
string s1 = "hallo";
system("b.exe s1");
printf("s1 after invoke = %s",s1);
and this is the code in b.cpp:
int main(string s)
{
s = "hello world";
return 0;
}
... | It is not possible to modify command line arguments among different processes. s1 is known only to A.CPP, and s is only known to B.CPP.
|
6,799,006 | 6,799,058 | How to swap content of void pointers? | I'm making a function which receives array of any datatype and reverse it elements.
void f(void *p, int size)
{
for(int i=0; i<=size/2; i++)
{
swap(p+i, p+size-i-1);
}
}
but problem is how can i implement swap function which swap their content without dereferencing void pointers?
| Or you could use the std::reverse function
int main()
{
int data[] = { 1, 2, 3, 4, 5, 6, 7};
std::reverse(data, data + sizeof(data)/sizeof(data[0]));
}
|
6,799,102 | 6,799,254 | efficient way to divide ignoring rest | there are 2 ways i found to get a whole number from a division in c++
question is which way is more efficient (more speedy)
first way:
Quotient = value1 / value2; // normal division haveing splitted number
floor(Quotient); // rounding the number down to the first integer
second way:
Rest = value1 % value... | If you're dealing with integers, then the usual way is
Quotient = value1 / value2;
That's it. The result is already an integer. No need to use the floor(Quotient); statement. It has no effect anyway. You would want to use Quotient = floor(Quotient); if it was needed.
If you have floating point numbers, then the secon... |
6,799,192 | 6,819,490 | Best practice to share a struct from a C# program to a C++ win32 DLL? | What is the best practice to share memory of a struct from a C# program to a C++ win32 DLL?
I've used structs in managed shared memory using Boost between two C++ programs and it worked great. I'm lost on the best way to accomplish this between where the struct gets populated in the C# program and the C++ DLL that is a... | The best practice for sharing memory would be to use the MemoryMappedFile class in C# and CreateFileMapping/MapViewOfFile in C++.
|
6,799,237 | 6,799,647 | Dll vs static lib (MSVC9 RunTime Library option) | For a MSVC9 Win32 project following options are shown under Configuration Properties -> C/C++ -> Code Geberation -> Runtime Library:
/MT, /MTd, /MD, /MDd
is it correct that for a DLL /MTd should be used and for static lib /MDd?
Thanks.
| There are two issues that are at play here.
First, you need to choose if you want the Debug version of the CRT or the Release version. The debug versions have special checks and code paths designed to help you catch bugs while writing an application. You should not use them for the final release version of an applicati... |
6,799,321 | 6,801,047 | Crash during running at cvCopyImage/cvResize | I'm making simple webcam program using OpenCV 2.3 and got stuck by the runtime error. Any idea will be appreciated.
Compile passes but upon running, I get the following error (at cvCopyImage/cvResize in 'read' function in the code below).
error:
OpenCV Error: Bad argument (Unknown array type) in cvarrToMat, file /usr/l... | The problem is that you are returning a pointer to a stack allocated variable, which is automatically destroyed at the end of the function.
// ...
Mat frame;
capture >> frame;
return &frame;
} // frame destroyed is at the end of the function yet you return a pointer to it!
You need to allocate the frame on th... |
6,799,405 | 6,799,423 | Using glLoadMatrixf with my own matrix | I have a simple drawing loop where I manipulate the camera, using glRotatef and glTranslatef then I attempt to draw a an object with my own matrix instead of using the gl* commands
e.g.
void GLCore::render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(camera.xRot,1.0,0.... | glLoadMatrix assigns your matrix to the top of the stack. What you want to do is to multiply your matrix with the one on the top of the stack. Use glMultMatrix for that.
|
6,799,410 | 6,799,446 | Scripting Language for C++ | I have an the need to use a scripting language, but I have a horrible list of requirements.
The workstations(PS2 Linux) at uni do not let us have admin access and have a very old version of GCC).
Can anybody recommend a script language that ...
Work on Linux
GCC 2.95.2 :(
No need for admin access
Easy to integrate wit... | Just use Lua, and don't use their machines. If you must, keep your full dev environment and dependencies on a flash drive. Lua is literally the industry standard for this.
|
6,799,707 | 6,799,717 | Mixed data typeinput in C++ | Why does this program run fine?
#include<iostream>
using namespace std;
int main()
{
cout <<"What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin>>address;
cout << "Year built: " << year << endl;
cout << "Address: " << ... | cin>> leaves the newline character (\n) in the iostream. If getline is used after cin>>, the getline sees this newline character as leading whitespace, thinks it is finished and stops reading any further.
Two ways to solve the problem:
Avoid putting getline after cin >>
OR
Consume the trailing newline character fr... |
6,799,750 | 6,799,769 | how to detect when compiler emits an error | To compile a C++ project, I want to write a perl script to compile my program and see if the compilation went wrong or not. If the compiler gives any compilation error, I'll need to perform some other task.
The perl script will be something like this:
@l1 = `find . -name '*.c'`;
@l2 = `find . -name '*.cpp'`;
... | You should check $? instead, after g++....
perlvar
$?
The status returned by the last pipe close, backtick (`` ) command,
successful call to wait() or waitpid(), or from the system() operator.
The exit value of the subprocess is really ($?>> 8)
So you should check if g++ returned 0 (success) or non-zero.
if ($? >> ... |
6,799,755 | 6,799,849 | C++ bind2nd question | This was one of the questions showed up on my Final exam. I can't figure out what I'm supposed to do.
I know BindSecArg requires a () operator, but not sure what goes inside.
In this question you are required to implement something similar to std::bind2nd. For simplicity main
is written using a ”for”-loop, but it may b... | probably there are better implementations:
template <typename T>
class BindSecArg
{
public:
BindSecArg(int value2) : m_value2(value2){ };
int operator()(int value1) { return T()(value1, m_value2);}
private:
int m_value2;
};
int the link I posted in the comment to your question you can find the stl code.
|
6,799,762 | 6,800,471 | How to print wstring on Linux/OS X? | How can I print a string like this: €áa¢cée£ on the console/screen? I tried this:
#include <iostream>
#include <string>
using namespace std;
wstring wStr = L"€áa¢cée£";
int main (void)
{
wcout << wStr << " : " << wStr.length() << endl;
return 0;
}
which is not working. Even confusing, if I remove € from ... | Drop the L before the string literal. Use std::string, not std::wstring.
UPD: There's a better (correct) solution. keep wchar_t, wstring and the L, and call setlocale(LC_ALL,"") in the beginning of your program.
You should call setlocale(LC_ALL,"") in the beginning of your program anyway. This instructs your program t... |
6,799,838 | 6,799,863 | Boost date_time cpp files missing | I'm trying to compile this program and I'm having trouble finding the following files online:
#include <libs/date_time/src/posix_time/posix_time_types.cpp>
#include <libs/date_time/src/gregorian/date_generators.cpp>
speed_test\speed_test.cpp|42|error: boost/date_time/posix_time/posix_time_types.cpp: No such file or di... | You seem to have some mistake in the #include directive, boost libraries are usually included as
#include <boost/whatever.hpp>
or
#include <boost/module/header.hpp>
Or if the boost libraries were not installed to your include paths and it is present in the current directory:
#include "boost_1_46_1/boost/..."
Rules ... |
6,800,003 | 6,800,285 | Order of decorations in Decorator Pattern | Most of you know the pizza / cofee example for the decorator pattern.
Pizza* pizza1 = BigPizzaDecorator(MushromDecorator(SimplePizza()));
Pizza* pizza2 = MushromDecorator(BigPizzaDecorator(SimplePizza()));
the two object behave in a similar way, but not completely, in particular if you have non-commutative operation, ... | Ive never known this sort of thing to be needed when using decorators. And I would think that if you need to do this, then you shouldn't be using decorators, especially as you're knowingly "pushing the decorator beyond it's intent".
I have had a stab at doing this, the code is below. Basically, I create a thin layer ... |
6,800,192 | 6,800,221 | Output numbers with digit grouping (1000000 as 1,000,000 and so on) | While it is easy to write something that does this by myself, I often wondered if there was something like this in iomanip or somewhere. However, I never found something useful. Ideally, it'd be sensitive to locales (e.g. in Germany you'd write 1,234,567.89 as 1.234.567,89) and hence highly superior to building the com... | According to this thread, you can set a locale on your output stream by doing something like:
#include <iostream>
#include <locale>
#include <string>
struct my_facet : public std::numpunct<char> {
explicit my_facet(size_t refs = 0) : std::numpunct<char>(refs) {}
virtual char do_thousands_sep() const { return '... |
6,800,224 | 6,800,397 | Memory management differences in return by value | I'm trying to follow a tutorial here: regarding overloading operators, and I've found something that's really confused me.
There was a previous question on this very website here where this tutorial was discussed, namely regarding how the variables in the class were preserved because the whole class was passed back by ... | The problem is that you are not following the rule of the three, which basically boils down to: *if you manage resources, then you should provide copy constructor, assignment operator and destructor for your class*.
Assuming that on construction you are allocating memory for the pointers, the problem is that the implic... |
6,800,521 | 6,800,643 | OutputDebugString error | I use:
OutputDebugString(L"My error");
in Visual Studio 2010, but instead of displaying "My error", I get just an "ERROR" in the window.
How do I fix this issue?
| Since you're explicitly passing an UNICODE string, I'd suggest you also explicitly call OutputDebugStringW().
Otherwise, if the UNICODE preprocessor symbol is not defined in your compilation unit, the ANSI version of the function (OutputDebugStringA()) would end up being called with an UNICODE string, which it does not... |
6,800,795 | 6,800,855 | Multiple inheritance, base class pointers and sizeof | Take the typical demonstration of how pointer values can change through casting:
struct B1 { int x; };
struct B2 { int y; };
struct D : B1, B2 { };
int main() {
D d;
cout << (B1*)&d << " " << (B2*)&d << " " << &d;
}
// Typical output:
// 0xbf814ab4 0xbf814ab8 0xbf814ab4
I got to thinking; that offset probably... | The B1 and B2 objects are subobjects of d. The sizeof operator gives information about the size of a complete object, not a subobject.
The Standard allows but does not require a base class subobject to occupy no memory. So on another compliant implementation, you could find in your second example that the subobjects ... |
6,800,810 | 6,800,859 | What is the most accurate way to count a sum of vector elements using std::accumulate? |
Possible Duplicate:
C++ float precision question
I've got a problem of determining the most precise method of the three to calculate the sum of vector elements, which can be only positive numbers, using std::accumulate.
1)
double sum(vector<float> &v)
{
return accumulate(v.begin(), v.end(), 0.0);
}
2)
double s... | The difference should be really small, but starting with the smaller numbers will be slightly more accurate. Consider for exposition purposes that your floating point number contained only 4 significant digits and an exponent, and that it was decimal rather than binary. Using the numbers:
a = 5000
b = 5000
c = 1000e4 (... |
6,800,811 | 6,801,122 | basic_streambuf::seekoff what should be returned when ios_base::in | ios_base::out is specified? |
27.6.3.4.2 Buffer management and positioning
pos_type seekoff(off_type off, ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
Effects: Alters the stream positions within one or more of the
controlled sequences in a way that is defined separately for each
class derived from basi... | It is a bit up to your stream to define what happens. The built in streams differ, in that some can have separate read and write positions (stringstream) while others just have one (fstream).
If the user does a reposition and specify both in and out, perhaps you should move both. If it is a seek with a zero offset to g... |
6,800,824 | 6,800,868 | How do you force compiler to pass some variable by reference in C++? | Here is a simple example;
template <typename T>
void foo(T t) {}
std::string str("some huge text");
foo(str);
My question is how can I force the compiler to pass str by reference
without modifying function foo?
| Pass the reference type explicitly:
template <typename T>
void foo(T t) {}
int main() {
std::string str("some huge text");
foo<std::string&>(str);
}
This does modify the function instantiation that you get (by generating a void foo<std::string&>(std::string& t)), but it doesn't modify the function template.
Liv... |
6,800,836 | 6,800,853 | Counting the number of words in a file | #include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int hmlines(ifstream &a){
int i=0;
string line;
while (getline(a,line)){
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a){
int i=0;
char c;
while ((c=a.get()) && (c!=EOF)){
if(c==' '){
i++;
}
}
ret... | int hmwords(ifstream &a){
int i;
You've forgotten to initialize i. It can contain absolutely anything at that point.
Also note that operator>> on streams skips whitespace by default. Your word counting loop needs the noskipws modifier.
a >> noskipws >> c;
Another problem is that after you call hmlines, matos is a... |
6,800,862 | 6,892,390 | Sqlite3 ORM for C++ implementing lazyloading | What would you suggest to use in the following scenario:
Desktop application in C++
Cross platform (might use wxwidgets)
Sqlite3 DB (no concurrent accesses by different users)
Would like some kind of configurable lazy loading mechanism, meaning certain parts of an object can be loaded at different moments.
I would li... | ODB is a C++ ORM released under GPL (or a purchasable commercial license) that supports SQLite. It also supports lazy-loading of relationships and is cross-platform.
See http://www.codesynthesis.com/products/odb/features.xhtml for details.
|
6,801,347 | 6,801,562 | constexpr with operator|= | I tried to write a function, which returns an integer with only the highest bit of the input set, using a C++0x constexpr.
constexpr inline uint64_t
get_highest_bit(uint64_t p)
{
return
(p|=(p>>1)),
(p|=(p>>2)),
(p|=(p>>4)),
(p|=(p>>8)),
(p|=(p>>16)),
(p|=(p>>32)),
(p-(p>>1));
}
T... | (Not tested on GCC because I don't have 4.6, but I've verified that the algorithm is correct.)
To use constexpr you must not have assignments. Therefore, you often have to write in functional form with recursion:
#include <cstdint>
#include <climits>
constexpr inline uint64_t highestBit(uint64_t p, int n = 1) {
re... |
6,801,442 | 6,801,497 | Weird characters on the output of an ifstream | #include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
char a;
cout << "give me the filename: ";
cin >> filename;
ifstream caroll;
caroll.open(filename.c_str());
while (a=caroll.get() && !caroll.eof()){
cout << a << " ";
}
caroll.close()... | Please turn on your compilers warning level. There's a bug here:
while (a=caroll.get() && !caroll.eof()) {
This is interpreted as:
while (a = (caroll.get() && !caroll.eof()) ) {
^ ^
You need to add parenthesis around the assignment:
while ((a = caroll.get()) && !caroll.eof() ) {... |
6,801,529 | 6,801,565 | Making l-value from r-value | I've got quite a nifty get fnc which returns pointer to 'a type'. Now I would like to reuse this fnc in fnc set to set some value to this type returned by get:
template<class Tag,class Type>
set(Type t, some_value)
{
get<Tag>(t) = value;
}
The only problem I have is that: Because get returns pointer and not reference ... | Dereferencing a pointer (with the * operator) yields a reference. The type of the reference depends on the type of the pointer. const T * becomes const T &, while T * becomes T &.
So, if get returns a pointer to a non-const variable, you can write:
*get<Tag>(t) = value;
If get does not meet such requirement, and you c... |
6,801,644 | 6,803,062 | Problem on Hooking Keyboard Messages using SetWindowsHookEx | I 'm trying to hook on Keyboard Messages without any success.
I create a test console win32 app:
int _tmain(int argc, _TCHAR* argv[])
{
HOOKPROC hHookProc;
HINSTANCE hinstDLL;
HHOOK hHook;
hinstDLL = LoadLibrary(TEXT("pathtodll\\KeyHook.dll"));
hHookProc= (HOOKPROC)GetProcAddress(hinstDLL, "HookProc");
hHook = Se... | Instead of performing a blank while loop after calling SetWindowsHookEx(), try having the loop pump the calling thread's message queue instead, via Peek/GetMessage(). Some hooks run in the context of the thread that installs them, so the OS has to be able to switch to that thread when needed.
|
6,801,796 | 6,801,812 | C++: Throwing exceptions, use 'new' or not? | Is it proper to use throw new FoobarException(Baz argument); or throw FoobarException(Baz argument);?
When catching I always use catch(FoobarException& e) "just in case" but I never could find a solid answer whether I had to use new or not in C++ (Java definitely) or if it was just a preference of the programmer.
| Exceptions in C++ should be thrown by value, and caught by reference.
So this is the proper way:
try
{
throw FoobarException(argument);
}
catch( const FoobarException &ex )
{
cout << ex.what() << endl;
}
Don't throw an exception created with new, since who's responsible for deleting it is not well-defined. In ... |
6,801,843 | 6,802,387 | Can it cause problems to explicitly pass a reference into a function template that's not expecting one? | There was a question regarding passing taking the following function template, and instantiating it with a by-reference string parameter:
template <typename T>
void foo(T t) {}
The answer was, of course, to give the argument explicitly:
int main() {
std::string str("some huge text");
foo<std::string&>(str);
}
(... | Consider that it's common to write algorithms like this:
template <typename InputIterator>
void dosomething(InputIterator first, InputIterator last, otherparams) {
while (first != last) {
do the work;
++first;
}
}
It's also how the standard algorithms are implemented both in GCC and in the old ... |
6,801,844 | 6,801,857 | C++ Optimizing If Statements | Consider following statement:
C a, b; //C contains c1, c2 and c3 all integers
if(a.c1==b.c1 && a.c2 == b.c2) {
a.c3=b.c3;
}
Will this statement be optimized to the following:
if(a.c1 == b.c1) {
if(a.c2 == b.c2) {
a.c3=b.c3;
}
}
AFAIK, C++ compilers does not perform this kind of operation sinc... | Yes. The following code snippet:
C a, b; //C contains c1, c2 and c3 all integers
if(a.c1==b.c1 && a.c2 == b.c2)
{
a.c3=b.c3;
}
will be "optimized" to this (or something equivalent):
if(a.c1 == b.c1)
{
if(a.c2 == b.c2)
{
a.c3=b.c3
}
}
This is required not because of optimization but because the... |
6,801,851 | 6,801,873 | C++: how to track a pointer to a STL list element? | I would like to track a pointer to a list element for the next read access. This pointer would be advanced every time the list is read. Would it be bad practice to cache an iterator to the list as a member variable, assuming I take proper precautions when deleting list elements?
| An iterator to a list element remains valid until the element it refers to is removed. This is guaranteed by the standard.
There is no problem with caching an iterator as long as you make sure you don't remove elements from the list or refresh the cached iterator when you do.
|
6,801,953 | 6,802,060 | Why is boost::checked_delete "intentionally complex"? | So I was looking through some boost source code and came across this:
(from <boost/checked_delete.hpp>)
template<class T> inline void checked_delete(T * x)
{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_comple... | Someone asked the same question earlier. This post written by Peter Dimov (one of the writers of boost/checked_delete.hpp) pretty much speaks for itself:
What's the result of applying sizeof to an incomplete type?
A compile-time error, unless the compiler chooses to return 0 as a
nonstandard extension.
Why ... |
6,801,967 | 6,802,031 | Send float array from C++ server to C# client | I'm trying to send some data from a C++ server to a C# client. I was able to send over char arrays. But there is some problem with float array.
This is the code on the C++ server side
float* arr;
arr = new float[12];
//array init...
if((bytecount = send(*csock, (const char*)arr, 12*sizeof(float), 0))==SOCKET_ERROR){
}... | It's not clear from your code what the streamReader variable points to (ie what's its type?) but I would suggest you use the BinaryReader instead. That way, you can just read data one float at a time and never bother with the byte[] array at all:
var reader = new BinaryReader(/* put source stream here */)
var myFloat =... |
6,801,989 | 6,802,004 | Accessing outside of class's namespace inside class method? | I have a header resource that I'm making use of that defines a struct called
typedef struct { ... } Mii;
Now, in my own program, I'm writing a wrapper class that uses this struct privately and internally for its own operations, so I put my class inside my program's namespace to avoid conflict.
namespace CMii {
cla... | You can do the following:
::Mii m
|
6,802,395 | 6,802,451 | How does the Visual C++ compiler pass the this ptr to the called function? | I'm learning C++ using Eckel's "Thinking in C++". It states the following:
If a class contains virtual methods, a virtual function table is created for that class etc. The workings of the function table are explained roughly. (I know a vtable is not mandatory, but Visual C++ creates one.)
The calling object is passed ... | Member functions in Visual Studio have a special calling convention, __thiscall, where this is passed in a special register. Which one, I don't recall, but MSDN will say. You will have to go down to assembler if you want to call a function pointer which is in a vtable.
Of course, your code exhibits massively undefined... |
6,802,617 | 6,802,936 | C++ Assignment Operator without Copy Constructor | The question: Can I define an assignment operator and not the copy constructor? For an internal class (not exposed in the API), is this still a bad design practice?
The reason I need it: As this question mentions, QObject makes its copy constructor and assignment operator private so that if a subclass tries to use eith... | While possible, as DeadMG says, it is rather foolish.
You don't have to call the base class's copy constructor from your own, so if you absolutely have to have value semantics, then it is still possible. But in the context of QObjects, this is still rather unorthodox. Even for your own internal classes, the princip... |
6,802,757 | 6,802,899 | C++ pointers and classes | Trying to solve this question for the last 45 minutes, but couldn't figure out the what I'm suppose to do. Here's the question.
class C; //forward declaration
class Cpointer {
public:
};
class C { //do not modify
int i;
public:
C(int _i=0) : i(_i) {}
Cpointer operator& () { return Cpointer(this); }
voi... | I feel slightly uneasy posting solution but since you say it's not a homework... Here it is:
class Cpointer {
C* ptr;
public:
Cpointer(C* c) : ptr(c) { }
~Cpointer() { delete ptr; }
C* operator->() { return ptr; }
};
There are three points here:
Constructor to get the C* pointer and st... |
6,802,791 | 6,802,803 | Number of "constants" in enum |
Possible Duplicate:
(How) can I count the items in an enum?
Is there a way to get the number of constants in enum?
For example:
enum C{id,value};
And later this would return 2:
//pseudo code
get<C>::value
And also, is it possible to access those constants via [] optor? Like i.e.:
C[0] would return id
| Usually, you start at zero and the last member gives the size of the enum excluding it.
enum C { id = 0, value, size };
C::size is the size of the enum. Is it possible to access those constants via subscript? No, it is unfortunately most assuredly not possible. However, in this case, you don't really want an enum- you... |
6,802,978 | 6,802,990 | Implement conversion operator for pointer | The question is simple but i can't find a solution.
class foo
{
public:
operator int()
{
return 5;
}
};
foo* a = new foo();
int b = a;
Is it possible to implement that behavior?
| You can't. Conversion operators need to be members of a class, but foo* is not a user-defined class type, it's a pointer type (besides, int b = *a would work).
The best thing you can do is to use an utility function that does the casting.
|
6,803,058 | 6,803,390 | wxWidgets connect() not recognizing event type | I'm trying to connect a wxListCtrl event to a function in C++, and it should be straightforward. Generally using Connect() works, but for one reason or another, it isn't recognizing the event name (EVT_LIST_ITEM_SELECTED). I've included wx/listctrl.h, and even checked to make sure the event is listed (it is; not in lis... | try
wxEVT_COMMAND_LIST_ITEM_SELECTED
|
6,803,395 | 6,804,155 | Child process receives parent's SIGINT | I have one simple program that's using Qt Framework.
It uses QProcess to execute RAR and compress some files. In my program I am catching SIGINT and doing something in my code when it occurs:
signal(SIGINT, &unix_handler);
When SIGINT occurs, I check if RAR process is done, and if it isn't I will wait for it ... The ... | If you are generating the SIGINT with Ctrl+C on a Unix system, then the signal is being sent to the entire process group.
You need to use setpgid or setsid to put the child process into a different process group so that it will not receive the signals generated by the controlling terminal.
[Edit:]
Be sure to read the ... |
6,803,489 | 6,803,554 | Knowing which memory pages were Accessed during execution | In my program, I need to know which pages are being accessed by the program periodically, So after each 0.5 or 1 second I check which pages were accessed and calculate a checksum from those page values.
I use mprotect function to mark memory areas which need to be seen and install SIGSEGV signal handler for each threa... | For faster method, the special compiler pass can be constructed. It will instrument memory access with changing a flag in the shadow memory. E.g. for each read or write operation, the compiler pass will add special write operation to some thread-specific area (shadow memory).
There is a http://code.google.com/p/address... |
6,803,548 | 6,803,705 | Using content of members of a Struct in a vector | After excellent advice I defined a struct, filled it with data read from a file and pushed it on a vector. Nice!!! Could somebody tell me now how I can call back the content of a member of the i-th struct I pushed on the vector?
The Structure definition:
struct Config_Data
{
int Surf_Index;
std::string Surf_Mne... | Element numeration in std::vector starts with zero value. Thus if vector holds one element, index of this value is 0. In case of two values - 0 and 1 and so on. Do not be confused by the size() vector method. It returns a number of holding elements.
So index of the newly pushed value equals to size()-1. Access to i-th ... |
6,803,556 | 6,803,635 | Do custom container iterators guarantee ADL to consider namespace std? | I have no intention of using this in real code. I promise.
Does the standard guarantee that std namespace is going to be found when a function argument is of type container::iterator and container::iterator isn't a typedef for a built-in type?
For example
#include <set>
#include <algorithm>
int main()
{
std::set<in... | I believe that the answer is no in the most general case, but yes for most practical implementations.
According to the C++ ISO standard, §3.4.2/2, there is a notion of an "associated namespace" for an argument, which is defined in a way that includes
If T is a class type (including unions), its associated classes are:... |
6,803,732 | 6,803,866 | Libcurl write data to array | I've really searched this. I've seen examples of how you can download and write data to a file with libcurl but I don't know how to write them to an array
that's the code I have so far:
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int written = fwrite(ptr, size, nmemb, (FILE *)stream)... | It seems, what you need is described in the libcurl documentation:
CURLOPT_WRITEFUNCTION
Function pointer that should match the following prototype: size_t
function( char *ptr, size_t size, size_t nmemb, void *userdata); This
function gets called by libcurl as soon as there is data received that
needs to be save... |
6,803,778 | 6,803,815 | Threading the writing in a log file | I'm setting up a log system for my (2d) game engine, and it should be able to write lines to a file.
The point is, writing to the disc is not instantaneous. If the file writing (basically, the file.flush()) is done in the thread who is calling the Trace.Write(), will it hang while the file is being written ?
If it is t... | Yes, your thread may be suspended while it is in a IOWAIT state. This is a classical suspend situation.
If it is a good idea to create a thread only responsible for writing logfile entries depends on your code. Is it I/O bound? Then it might be a good idea. Is your code CPU bound? Then it won't help much. Is it neither... |
6,803,986 | 6,805,244 | Valgrind and "WARNING: new redirection conflicts with existing" | I get this in Valgrind.
--24101-- REDIR: 0xbb20580 (operator delete(void*)) redirected to 0x93b7d48 (operator delete(void*))
--24101-- REDIR: 0xbb22580 (operator new[](unsigned long)) redirected to 0x93b88b7 (operator new[](unsigned long))
==24101== WARNING: new redirection conflicts with existing -- ignoring it
--2410... | A big part of Valgrind's magic is how it is able to intercept/redirect function calls in order to keep track of the state of the world.
As I understand it, redirection is achieved using shared object/function name patterns which when matched 'redirect' calls to new addresses. Checking out the valgrind source, we find t... |
6,804,029 | 6,804,415 | code guards fail and template from string literal | I know the only way to pass a string literal as template argument is to declare it before:
file a.h
#ifndef A_H
#define A_H
#include <string>
char EL[] = "el";
template<char* name>
struct myclass
{
std::string get_name() { return name; }
};
typedef myclass<EL> myclass_el;
#endif
file a.cpp
#include "a.cpp"
ma... | Let's start with what the Standard says for the benefit of all, from 14.3.2 Template non-type arguments [temp.arg.nontype] (C++03 Standard):
1 A template-argument for a non-type, non-template template-parameter
shall be one of:
— an integral constant-expression of integral or
enumeration type; or
— the name of a n... |
6,804,033 | 6,804,080 | With system() in C++ on Windows, why are two quotes required to invoke a program in another directory? | I have the find.exe program in my utils folder. This does not work:
system("\"utils/find.exe\"");
All I get is
'utils' is not recognized as an internal or external command,
operable program or batch file.
However, for some reason this works:
system("\"\"utils/find.exe\"\"");
Echoing the single quoted string
system("... | I assume you're on windows because you're trying to execute an .exe file. So, instead of writting "utils/find.exe", try to write "utils\find.exe". The delimiting character on windows is '\', so it probably sees "utils" as a command since '/' is ignored.
|
6,804,044 | 6,804,113 | Use a mutex as a semaphore? | I need two threads to progress in a "tick tock" pattern. When implmented with a semaphore this looks fine:
Semaphore tick_sem(1);
Semaphore tock_sem(0);
void ticker( void )
{
while( true )
{
P( tick_sem );
do_tick();
V( tock_sem );
}
}
void tocker( void )
{
while( true )
{
P( t... | A Mutex is not simply just a binary semaphore, it also has the limitation that only the locking thread is allowed to unlock it.
You are breaking that rule.
Edit:
From MSDN:
The ReleaseMutex function fails if the calling thread does not own the
mutex object.
From some site that google turned up for pthread_mutex_unl... |
6,804,165 | 6,804,522 | Why does the sqlite3pp sample behave this way? | So I try simple sqlite3pp modified a bit code:
#include <iostream>
#include <sqlite3pp.h>
using namespace std;
int main(int argc, char* argv[])
{
try {
sqlite3pp::database db("test.db");
{
db.execute("CREATE TABLE IF NOT EXISTS users ( email varchar(65) primary key, pass varchar(65))"... | Having had a quick look in the implementation of sqlite3pp, it seems stuff tends to just return error codes, and expects you to check them; it looked like it could be the destructor for the transaction that is throwing an exception, which is why you see your error message at the point that you do.
|
6,804,216 | 6,804,259 | How to initialize a container of noncopyable with initializer list? |
Possible Duplicate:
Can I list-initialize a vector of move-only type?
I use gcc 4.6.1 to compile this code
int main()
{
std::vector<std::unique_ptr<int>> vec({
std::unique_ptr<int>(new int(0)),
std::unique_ptr<int>(new int(1)),
});
return 0;
}
In what g++ complains there is s... | You can't move objects out of initializer lists, since they only allow const access to their members. As such, you can't use initializer lists and move constructors; they can only be copied.
|
6,804,253 | 6,804,286 | jni.h: No such file or directory | I have been following this tutorial, and at step 5, I am getting the following output from GCC:
HelloWorld.c:1:17: error: jni.h: No such file or directory
In file included from HelloWorld.c:3:
HelloWorld.h:15: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘void’
HelloWorld.c:5: error: e... | Open up a terminal and type:
locate jni.h
That should tell you where every file called jni.h is on your system. I am on ubuntu 11.04, and it's located at:
/usr/lib/jvm/java-6-openjdk/include/jni.h
/usr/lib/jvm/java-6-sun-1.6.0.26/include/jni.h
You may also need to get it from the repos:
sudo apt-get install openjdk-... |
6,804,299 | 6,804,316 | cannot convert from 'void' to 'Token' (C++) | Edit: Added token struct/enum to code block
I'm new to c++, so forgive me if I missed something obvious. I'm trying to write a c++ version of the Shunting Yard Algorithm, but it won't compile because it gives me the error: "cannot convert from 'void' to 'Token' (on the line I marked)." Can anyone tell me why it gives t... | The problem is that pop_front does not return a value. If you want to remove the first element and read its value, you can do so in two steps:
Token t = tokenList.front();
tokenList.pop_front();
This convention is employed throughout the STL, mostly for efficiency reasons. By having front return the value and pop_fr... |
6,804,568 | 6,811,063 | Being Smart About Vector Memory Allocation | Let's say I have to iterate over a potentially very large vector of numbers and copy the even and odd elements into new, separate vectors. (The source vector may have any proportion of evens to odds; it could be all evens, all odds, or somewhere in-between.)
For simplicity, push_back is often used for this sort of thi... | I'm going to answer the question I think you really meant to ask, which is "should push_back() be avoided in the inner loops of heavy algorithms?" rather than what others seem to have read into your post, which is "does it matter if I call push_back before doing an unrelated sort on a large vector?" Also, I'm going to... |
6,804,607 | 6,805,120 | How to check the validity of the dateformat (ex, %d/%m/%Y-%H:%M:%S)? | I am using boost optionsparser to parse the command-line arguments passed by the user.
Now the program had an option for the user to specify his/her choice of dateformat.
like,
program -d %d/%m/%Y-%H:%M:%S , program -d %d/%m/%Y and so on.
The problem I am facing is, *How do I check the validity of the format string pas... |
I wouldn't need to pass around the data and do stuff unncessarily since I do some calculation before actually using the format to generate the date string.
Instead of jumping through hoops to calculate something to pass to the date class to validate the format string, why don't you just ask the date class to format t... |
6,804,849 | 6,804,913 | C++: Is not deleting an object /always/ a memory leak? | class MyClass
{
// empty class with no base class
};
int main()
{
MyClass* myClass = new MyClass();
return 0;
}
Is this a memory leak?
| Yes. Even though your class is empty, you still leak memory. There are a few reasons for this:
Allocations are never zero-length. Your OS doesn't hand back a buffer of zero bytes. There is a minimum allocation size, and this is the size you'll get if you allocate a zero-byte structure. (On my machine, it's 16 bytes.)
... |
6,805,076 | 6,805,083 | Locations for different program elements |
Local variables are located on the stack
Dynamically-allocated memory is located on the heap
String literals have a const location
Uninitialized global and static variable are located at .bss (block started by symbol)
Initialized static and global variables are located in the data section
Where are pointer variables ... | Functions are in .text section.
Pointers are wherever: local pointers on stack, global/static points in .bss, etc.
Yes, an automatic (on stack) pointer could point anywhere (or nowhere at all):
void foo() {
char *p = NULL; // this pointer points nowhere
const char *q = "hello"; // points to rea... |
6,805,328 | 6,805,391 | fixed length array data structure which allows quick reuse of arbitrary elements? C++ | I am relatively new to c++ and am trying to choose the most appropriate data structure for a specific problem but am finding it difficult to find answers.
I wish to create a small (1000 elems max) array of either ints or simple structs. At any time in my code I will need to add and remove elements from my array but I d... | I think the best approach in this case is using a preallocated doubly-linked list...
// Untested code... just to give the idea
struct Node
{
int data;
Node *prev, *next;
static Node *first, *last, *free;
// Allocates a new node before the specified node or
// at the end of the list if before is N... |
6,805,393 | 6,805,431 | Problem with WndProc() in header file | I have a LRESULT CALLBACK function in a header file(hook.h) that I both forward declare then define in the file(along with some classes that contain static variables). I then define(implement/create?) the static class variables in the associated .cpp file (hook.cpp).
Finally I include the header file in my stdafx.h fil... | Move your definition of KeyboardProc (or is it LowLevelKeyboardProc?) into hook.cpp. That is, move this code from hook.h into hook.cpp
LRESULT CALLBACK KeyboardProc( int code, WPARAM wParam, LPARAM lParam )
{
// implements function
}
But leave your "declaration" of KeybaordProc in hook.h. That is, leave this line i... |
6,805,417 | 6,805,425 | STL container library - Is it legal to call allocate/deallocate on different instances of the allocator class? | First of all, I don't think it is. But, I've observed such a behavior with MSVC 10.0 in Debug mode. I'm using a custom allocator class which relies on the user to pass only pointers allocated on the same instance to deallocate. However, in Release mode, my code is working.
Is this a bug or am I mistaken?
| The standard requires that any allocator be able to deallocate memory produced by any other allocator of the same type, even if it's a totally different instance. This is required to get list::splice working correctly. It's largely considered a design flaw in the C++ spec, and in C++0x they're introducing a set of fi... |
6,805,507 | 6,805,528 | Default constructor defined with default arguments outside the class definition, why does this work? and what happens with templates involved? | I am aware this is bad form and that default-values should be specified in the declaration, but if you would please indulge me for a moment.. why does this compile? and what is happening exactly?
#include <iostream>
using namespace std;
class test
{
public:
test(int n);
};
test::test(int n = 666)
{
cout << n;... | It looks like the C++ specification specifically allows the first case and disallows the second!
Quote from the C++ spec (§8.3.6/4):
For non-template functions, default arguments can be added in later declarations of a function in the same scope.
So it looks like for non-template functions, you can indeed introduce t... |
6,805,563 | 6,805,579 | returning character pointers from functions | i obtained a double value with decimal part as 0 from calculations and then want to convert this value into char array consisting of the digits as elements(using ascii codes) and then return it...i wrote the following code for it...
char* as_string(double a,char* ptr)
{
int digits=0;
for(int i=1;;i++)
{if(static_... | You should ask yourself the Question:
Is ptr pointing to a memory location big enough to hold digits?
I don't think so.
The problem is you are passing a pointer ptr to the function but you don't know before hand how much memory is needed to be allocated to ptr.
You can have two options:
You can guess the maximu... |
6,805,763 | 6,805,778 | how can i initialize a dynamically allocated array of characters so i don't get those weird characters? | I want to use that array of characters in my game of "hangman" to view to tha user his current progress.
#include <iostream>
#include "randword.h"
#include <fstream>
#include <time.h>
#include <cstdlib>
using namespace std;
int main()
{
InitDictionary();
string tixaio=Randomword();
int m = tixaio.length();
int gue... | When you print an array of characters in C++, cout (or any ofstream object, for that matter) looks for the null terminating character to determine when to stop printing. Now, if you've only allocated m bytes for the array, and cout tries to access memory outside of those m bytes, you could possibly even get a segmentat... |
6,805,923 | 6,806,099 | How to find the function symbol in nm or objdump when using shared_ptr for abstract class? | I use shared_ptr for an abstract class ABC. ABCImpl class is the implementation of ABC. abc_ptr is a shared_ptr< ABC> points to an ABCImpl objects. In caller function, abc_ptr will call one of the member function (func_in_ABC) in ABC class. The compile is successful. But when I use nm or objdump, I could only see the s... | Since func_in_ABC is a virtual function, you don't actually need the symbol name to call it. You just need the offset into the virtual table for that specific virtual function.
If you make func_in_ABC non-virtual, you should see the symbol show up in the nm output.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.