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,002,004
7,002,269
What's the "price" of using inheritance in an embedded environment with C++?
I'm starting a new embedded project with C++ and I was wondering if it is too much expensive to use a interface oriented design. Something like this: typedef int data; class data_provider { public: virtual data get_data() = 0; }; class specific_data_provider : public data_provider { public: data get_data() {...
Inheritance, on its own, is free. For example, below, B and C are the same from a performance/memory point of view: struct A { int x; }; struct B : A { int y; }; struct C { int x, y; }; Inheritance only incurs a cost when you have virtual functions. struct A { virtual ~A(); }; struct B : A { ... }; Here, on virtually...
7,002,147
7,002,583
Binding a CPen to a list box
Does anyone know how to bind a CPen object to a listbox in VS2005 C++? Can I do it as a ToString with some sort of conversion? I am creating a custom list of different pens for the user to select. Thanks. COLORREF rgbRED = (255,0,0); CPen penRed(PS_SOLID,3,rgbRED); CDialog::OnInitDialog(); ShowWi...
2 options. (simple) Use a normal CListBox with strings as the items, and keep the link between the string to the actual CPen as free functions (or member of some other classes) and you will have to do a one-to-one association between the current selected item (usually an index number) and the CPen information you have...
7,002,426
7,002,431
C++ standard: default "const T& value" in vector constructor for type 'int'
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); vector<int> vec(10); cout << "vec.size: " << vec.size() << endl; for (vector<int>::const_iterator iter=vec.begin(); iter != vec.end(); ++iter) { cout << *iter << endl; } Output from VS2010: vec.size: 10 0 0 0 0 0 0 0 0 0 0 Ques...
Yes, this is the required behavior. T() for any numeric type T yields 0 (of type T, of course). This is called value initialization, which for numeric types is the same as zero initialization.
7,002,444
7,043,390
"Program is not a recognized executable" error in Eclipse
I'm trying to debug a C++ programme in Eclipse Indigo. The project is using autotools/configure (and the respective plugin) as build system. After successful build I right-clicked on the binary in the project browser and chose "Debug As". Then I used the file browser to select the binary. Clicking on "Debug" then open...
I found the answer: the binary parsers configured in eclipse were the wrong ones. Adding the correct binary parser under Project --> Properties --> C/C++ Build --> Settings solves he problem.
7,002,663
7,002,782
choosing gui for c++ for cross-platform game
I have just started learning c++ a few days ago and the book I have got does not cover any of the gui aspects in it. Ultimately I am wanting to make simple multilayer games(2-8 players). I've been doing some reading on gui libraries but have no idea what would be best or what to look for. Is there a gui library you wou...
For most applications a typical toolkit like Nokia's Qt or WxWidgets is just fine. If you're planning on having an OpenGL-based game anyhow, you might take a look at GLUI to see if it adds enough tools to make your GUI development easier.
7,002,668
7,002,694
Are there any problems with changing the target of a function pointer from within the function? (C++)
I have a program that defines changes the target function of a function pointer from within the function being called by said pointer, like so: void increment(int&); void superincrement(int&); void (*fooncrement)(int&); int main() { int j = 0; fooncrement = increment; while (true == true) { fooncr...
This is well-defined. In fact, this technique is often used to implement state machines.
7,003,119
7,003,194
Determining the most used value in an array
I am needing to write an application that determines the value that comes up most often in an array in C++ and its position in the array. For example, if I have an array A where A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 I must determine that 3 is the most often used numbe...
There are several ways to do this. One is to sort the array, so that you can count all similar values at once. Another is to use an associative array, a.k.a. a dictionary, where the values from A are keys and frequencies are the values associated with the keys.
7,003,278
7,003,303
How do I protect a character string in shared memory between two processes?
I have a piece of shared memory that contains a char string and an integer between two processes. Process A writes to it and Process B reads it (and not vice versa) What is the most efficient and effective way to make sure that Process A doesn't happen to update (write to it) that same time Process B is reading it? (Sh...
Since you have two processes you need a cross-process synchronisation object. I think this means that you need to use a mutex.
7,003,630
7,003,674
sizeof an inline struct declaration
If there's a structure with a pointer to a struct declared within it, how do you determine the size of the sub-struct? typedef struct myStruct { int member; struct subStruct { int a; int b; } *subStruct_t; } myStruct_t; How do you allocate space for the subStruct_t pointer? I was thinking something along...
M.subStruct_t = calloc(1,sizeof(*M.subStruct_t)); Note: allocate for the size of the structure, not for the pointer
7,003,914
7,004,205
finding triangulars from array
zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if and A[P] + A[Q] > A[R], A[Q] + A[R] > A[P], A[R] + A[P] > A[Q]. For example, consider array A such that A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20 Triplet (0, 2, 4) is triangular. Write a funct...
If O(N³) is acceptable time complexity then the Pseudocode below should work. If you have stricter time complexity requirements then you'll have to specify them. for (P in A){ for (Q in A){ for (R in A){ if(A[P] > 0 && A[Q] > 0 && A[R] > 0){ if(A[P] > A[R] - A[Q] && A[Q] > A[P] ...
7,004,005
7,004,876
Window positioning with Aero Themes (shadows) on - Window at 0,0 has some of the border hidden
I am opening a window at 0,0. When Aero and window shadow are disabled, this works just fine. If window shadow is enabled, part of the window's border (and title) are hidden above the upper / left of left edge of the desktop. Is there a way to detect if the shadow is on and by how many pixels do I need to adjust the wi...
Aero lies about the window position. This is a heavy duty app-compat feature, windows borders have had the same width for a very long time. That was not sustainable, at Vista time it was getting important to not make a window border one pixel wide. Monitor technology moved on, having a 1600 x 900 resolution display ...
7,004,031
7,004,072
C++ unresolved externals
Does anyone know what this means? 1> Generating Code... 1>BlankWindowDXbaseImpl.obj : error LNK2019: unresolved external symbol "public: __thiscall DXBase::DXBase(void)" (??0DXBase@@QAE@XZ) referenced in function "public: __thiscall BlankWindowDXBaseImpl::BlankWindowDXBaseImpl(void)" (??0BlankWindowDXBaseImpl@@QAE@XZ)...
It means that you have unresolved external symbols. What are symbols? Symbols can be anything from variables, classes, member functions or functions. Why they are unresolved? Some part of your code (or libraries that you are using) rely on these symbols and they are not being found because you are not linking the corre...
7,004,129
7,004,342
Why does std::istreambuf_iterator fail boost's SinglePassIterator concept check?
The following program: #include <boost/range/concepts.hpp> #include <iterator> #include <istream> using boost::range_detail::SinglePassIteratorConcept; int main() { BOOST_CONCEPT_ASSERT(( SinglePassIteratorConcept<std::istreambuf_iterator<char>> )); } Fails to compile with both MSVC and gcc. The MSVC error is a...
The only requirement of the type of operator* of an InputIterator is that it be convertible to value_type (§24.1.1/2). Since it's meaningless to assign a value to the result of operator* for an istreambuf_iterator, it would be incorrect for it to return a reference or any kind of lvalue. Boost is in error to check for ...
7,004,327
7,004,345
Is it bad practice to have a macro definition return a value for a function?
Using a macro defined to conditionally return a value has a disadvantage where it is not apparent from only looking at the client code might exit at the point of the macro. The use case I am considering is writing a value and error checking, like so: #define WRITE_CHK(file, param)\ if (!write_that_returns_zero_on_fail(...
The standard answer is "don't use macros"; but that's often slightly simplistic. There are sometimes cases where they can greatly cut down on the boilerplate verbosity that you'd otherwise have. So, why not encode the fact into the macro name? e.g. WRITE_OR_RETURN_ON_FAILURE. It may be slightly verbose, but it's muc...
7,004,495
7,004,555
How do I avoid using arrays?
My professor wants us to write a program without using arrays or vectors like this: Write a program using functions that calculates and prints parking charges for each of the n customers who parked their cars in the garage. Parking rates: a parking garage charges a $5.00 minimum fee to park for up to five hours. the ...
On every iteration, generate the relevant output, but don't stream it to std::cout. Instead, stream it to a std::stringstream object. Then, at the end, stream that object to std::cout. The maths can be done simply by maintaining a running accumulation of the input values. This, of course, assumes that using a std::s...
7,004,721
7,004,759
How to do something every millisecond or better on Windows
This question is not about timing something accurately on Windows (XP or better), but rather about doing something very rapidly via callback or interrupt. I need to be doing something regularly every 1 millisecond, or preferably even every 100 microseconds. What I need to do is drive some assynchronous hardware (ethern...
You should consider looking at the Multimedia Timers. These are timers that are intended to the sort of resolution you are looking at. Have a look here on MSDN.
7,004,886
7,004,940
Why is exception handling often looked down upon in C++?
I have seen the trend that many people don't like to use exceptions in their c++ programs. Some people even go as far as saying that exceptions are not natural to c++. Game programmers generally disable exception handling . Also Exceptions handling is usually avoided in performance critical applications. I do know th...
I have four problems with exceptions: People are tempted to use them as part of non-exceptional program flow In order to use them properly, you also need to be well versed in other C++ techniques (RAII, smart pointers) It offers an 'easy way out' - "stuff it - I'll just throw" Without careful planning, you often you e...
7,005,075
7,005,192
SSE data types and primitives
In most tutorials or code snippets on the net one sees the following: float *arr= (float*) _aligned_malloc(length * sizeof(float), 16); __m128 *m1 = (__m128*)arr; Does this violate strict aliasing rules or not? I'd think it does, but then surely all those tutorial writers don't ignore it just for convenience and since...
That hasn't violated it -- yet. However, writing through one pointer and reading through the other would violate strict aliasing. Instead, you should use functions like: _mm_load_ps _mm_store_ps
7,005,084
7,005,128
When and why should destructor in base class NOT be defined as virtual?
This example below illustrates how to prevent derived class from being copied. It's based on a base class where both the copy constructor and copy assignment operator are declared private. class Uncopyable { protected: // allow construction and destruction of derived objects... Uncopyable() {} ~Uncopyable() {}...
A base class destructor only needs to be virtual if you might try deallocating an object of a derived type through a pointer of the base type. Consequently, if you only inherit from the base class privately instead of publicly, as would be the case in Uncopyable, then you don't need to worry about putting in a virtual...
7,005,435
7,005,447
Why set<string>::iterator cannot use as key of map?
I have a piece of code like this: set<string>::iterator it1; set<string>::iterator it2; pair<set<string>::iterator,bool> ret; set<string> s; ret = s.insert("bbbb1"); it1 = ret.first; ret = s.insert("bbbb2"); it2 = ret.first; map<set<string>::iterator, set<string>::iterator> m; m.insert(make_pair(it1,it2)); but th...
std::set iterators are not random access iterators so they are not less-than comparable. The type that you use as a key in a std::map must be able to be sorted using a strict weak ordering. By default, std::map uses < to order keys. You can change this behavior by providing a comparator when you define the type of th...
7,005,645
7,005,704
C++, Text to ASCII while-loop error
I've come this far without asking for help, but I've got a problem that I can't seem to fix. I like cryptology, so now that I am learning C++, I want to make programs to encrypt and decrypt strings. I read that the best way is to convert the text to ASCII and go from there, so here is a simple program I made in C++ to ...
Easiest way to actually make the code you have work is change this line strEncrypt.at(a) = b; to this strEncrypt += b; Which will add the characters to the empty string strEncrypt. Your code doesn't make much sense though as char types are already ascii. You'll have to explain more about what kind of encrypting you a...
7,005,707
7,007,354
Active Directory implementation
we have authetication as file system in our application server. Now i am trying to implement AD support into existing authentication within our application server, we need to add multiple AD support, scenario so i added an application to configure the multiple LDAP, now i found that login to server will be based on D...
Since you're dealing with AD, you can simply bind with the sAMAccountName or UPN. Alternatively, you can use a hard coded account to search the user with (e.g. (&(objectCategory=user)(objectClass=person)(sAMAccountName=%s))) and get the DN from there. With both options, the user don't have to type in (or even know) the...
7,005,713
7,005,723
How to compile a c++ program in Linux?
I made a file hi.cpp and I wrote the command given below: #include <iostream> using namespace std; int main () { cout << "Hello World! "; cout << "I'm a C++ program"; return 0; } then I ran it in my RHEL 6 machine with the following command gcc hi.cpp and I got some errors which are as follows: [chankey@localh...
Use g++ g++ -o hi hi.cpp g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.
7,005,956
7,005,966
#pragma once or include guards not working on extern funcs
I'm experiencing a very strange (and annoying) linker error on my project. Say for example I have the file KernelExports.h: #pragma once extern "C" { DWORD* KeTimeStampBundle; DWORD KeGetCurrentProcessType(); //etc... } I then #include this in my stdafx.h and then add #include "stdafx.h" all all my *.cpp ...
DWORD* KeTimeStampBundle; This does not declare a function. It declares and defines an object of type DWORD* named KeTimeStampBundle. If you include this header file in multiple source files, you will have multiple definitions of this object (one from each source file in which the header is included). Include guards...
7,006,090
7,006,097
difference between catch (domain_error const & x) and catch (const domain_error & x)
I would like to know whether the following statements are same or different 1> catch (domain_error const & x) 2> catch (const domain_error & x) 3> catch (domain_error & const x) // I think this is illegal Basically, I thought case 1> and case 2> are same and case 3> is not legal syntax. Please correct me if I am wron...
You are correct; the first two are equivalent and the last one is an error. More generally, when dealing with references, the syntaxes const T& and T const & are equivalent, while T & const is not allowed.
7,006,167
7,006,198
Preventing instantiation of unused default function arguments
Lets say I have a function which takes a function pointer as a parameter, and that parameter has a default argument. template <typename T> T* default_construct() { return new T(); } template <typename T> void register(T* (*construct)() = default_construct<T>) { // Save that function pointer for later } Lets ...
Here's one solution that solves the problem because it doesn't use default arguments: template <typename T> T* default_construct() { return new T(); } template <typename T> void register(T* (*construct)()) { // Save that function pointer for later } template<typename T> void register() { register<T>(defau...
7,006,213
7,006,239
How do you display images in OpenGL
How do you render images (.bmp and .jpeg) using OpenGL ? I've come across some tutorials, but they were for C# not C/C++. The reason I want to render images, is because I want to draw a spaceship(for a game). I could use a OpenGL primitive, but it doesn't really look that great. The other option is to draw the spaces...
By texturing a Quad (or better yet, two Triangles). Unless you really need .bmp or .jpeg, I would suggest that you use .tga (Targa) images as they are more commonly used and support alpha channel. Some C++ resources: http://nehe.gamedev.net/tutorial/loading_compressed_and_uncompressed_tgas/22001/ http://nehe.gamedev.ne...
7,006,510
7,006,813
Density of floating point number - Magnitude of the number
Is it true that the more the floating point number is big (either positive or negative) the less we have bits to encode the decimal digits? Can we encode more decimal digits between 21 and 22 than between 216 and 232? Is there the same count of values between this two ranges?
Yes the density of numbers that are exactly representable by a floating point number gets smaller as the numbers get bigger. Put it another way, floating point numbers only have a fixed number of bits for the mantissa and as the numbers get bigger, fewer of those manitssa digits will be after the decimal point (which i...
7,006,695
7,006,717
What should be the index type when iterating over the elements of a vector?
I usually iterate over a vector that way: for (int i = 0; i < myVector.size(); i++) { Element* e = myVector[i]; } But then the compiler usually gives me this warning: warning: C4018: '<' : signed/unsigned mismatch So if an int is not right, which type should the index be? vector::size() seems to be of a "size_typ...
You should use std::vector<T>::size_type1. Its unsigned integral type. Its usually same as size_t. To know the difference between size_type and size_t, see this topic: C++ for-loop - size_type vs. size_t 1. Similarly, you can use std::string::size_type, std::list<T>::size_type, std::deque<T>::size_type, std::set<T...
7,006,718
7,006,758
iterator become invalid after swapping with temporary container
It's said that if swap two container's value, the iterator will not become invalid. so following code works fine vector<int> v1; v1.push_back(1); vector<int>::iterator i = v1.begin(); vector<int> v2(v1); v2.swap(v1); cout<<*i<<endl; //output 1 but when I turned to a temporary container, the iterator become invalid, ...
I believe it's because the iterator belongs to the container that you swap it with. When you swap it with a temporary, the iterator points to a member of the temporary, then the temp is destroyed and the iterator becomes invalid. I don't know for sure that's how it works, but it's the only way I could think of that ite...
7,006,938
7,006,995
A point from the ISO C++ draft (n3290): 3.4.3.2/1 Namespace members
A point from the ISO C++ draft (n3290): 3.4.3.2/1 Namespace members If the nested-name-specifier of a qualified-id nominates a namespace, the name specified after the nested-name-specifier is looked up in the scope of the namespace. If a qualified-id starts with ::, the name after the :: is looked up in the gl...
::S is a qualified-id. In the qualified-id ::S::f, S:: is a nested-name-specifier. In informal terms, a nested-name-specifier is the part of the id that begins either at the very beginning of a qualified-id or after the initial scope resolution operator (::) if one appears at the very beginning of the id and ends with...
7,006,968
7,007,320
A point from the ISO C++ draft (n3290): 3.4.3.2/2 Namespace members
A point from the ISO C++ draft (n3290): 3.4.3.2/1 Namespace members For a namespace X and name m, the namespace-qualified lookup set S(X, m) is defined as follows: Let S`(X, m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S`(X, m) is not empty, S(X, m) is S`(X, m); other...
If in the namespace X, there exists at least one declaration of the name m, then those declarations are used for the lookup set. Otherwise, all namespaces from using directives in the namespace X are checked for declarations of the name m in the same way as described above. Or in other words : you check the namespace X...
7,007,098
7,007,123
Confused about if condition CPP
Confused about if condition, how does it executes following statements. if(1 && (1 || 0) != 0) or if(1 || (1 && 0) != 0) In above if statement what is the sequence of executing/validating the statements. (left to right or right to left) if left to right, then if first argument/expression is true does it evaluates 2...
Logical && short circuits if the first operand evaluates to false (because false && x is false for all x) Logical || short circuits if the first operand evaluates to true (because true || x is true for all x) They both evaluate left-to-right.
7,007,147
7,007,279
How to make OS X Cocoa application load custom frameworks from the folder it resides in?
By default all frameworks are being loaded from ~/Library/Frameworks and that's fine for development purposes, however for deployment purposes I need to find a way to load all my linked custom frameworks from the folder with the application folder or somewhere in the .app folder... Please tell me, how can I do it? Is i...
I am not entirely sure what you want, but if you simply want to link a framework/lib at any location, double click on your target in xcode4, click the plus in the "Link Binary With Libraries" Section and choose "add other...". If linking is not enough and you need to copy stuff inside your .app folder simply also add t...
7,007,403
7,007,475
Are volatile reads and writes atomic on Windows+VisualC?
There are a couple of questions on this site asking whether using a volatile variable for atomic / multithreaded access is possible: See here, here, or here for example. Now, the C(++) standard conformant answer is obviously no. However, on Windows & Visual C++ compiler, the situation seems not so clear. I have recentl...
Yes they are atomic on windows/vc++ (Assuming you meet alignment requirements etc or course) However for a lock you would need an atomic test and set, or compare and exchange instuction or similar, not just an atomic update or read. Otherwise there is no way to test the lock and claim it in one indivisable operation. ...
7,007,468
7,007,514
g++ error: ‘malloc’ was not declared in this scope
I'm using g++ under Fedora to compile an openGL project, which has the line: textureImage = (GLubyte**)malloc(sizeof(GLubyte*)*RESOURCE_LENGTH); When compiling, g++ error says: error: ‘malloc’ was not declared in this scope Adding #include <cstdlib> doesn't fix the error. My g++ version is: g++ (GCC) 4.4.5 20101112 (...
You should use new in C++ code rather than malloc so it becomes new GLubyte*[RESOURCE_LENGTH] instead. When you #include <cstdlib> it will load malloc into namespace std, so refer to std::malloc (or #include <stdlib.h> instead).
7,007,469
7,007,942
C/C++ library for lazy evaluation of SIMD/SSE expressions
Libraries such as intel-MKL or amd-ACML provide easier interface to SIMD operations on vectors, but I want to chain several functions together. Are there readily available libraries where I can register a parse tree for an expression like log( tanh(x) + exp(x) ) and then evaluate it on all members of an array ? What I...
It may not do exactly what you want, but I suggest you take a look at macstl. It's a SIMD valarray implementation which uses template metaprogramming, and which can combine expressions into a single loop. You may be able to use this as is or perhaps as a basis for something closer to what you need.
7,007,591
7,007,616
Syntax in Assigning to Map of structs
struct Structure { // Structure(const char* n, int v, bool a) : name(n), value(v), awesome(a) {} const char* name; int value; bool awesome; }; std::map<const char*, Structure> map; map["alpha"] = {"Alpha", 0, true}; map["beta"] = {"Beta", 1, false}; map["gamma"] = {"Gamma", 2, true}; G++ (4.6) accepts this sy...
The above code is only legal in C++0x by using the new uniform initialization syntax. C++03 will reject this. In the interim, defining a constructor for your struct is the way to go.
7,007,802
7,008,476
Erase specific elements in std::map
I want to erase some elements in my std::map. I wrote erase + remove_if technique which I always do with other sequence containers. But it wasn't compile with map. Why? And How can I do this job? std::map<int, int> m; bool foo(const std::pair<int, int>& p) { return p.second > 15; } int _tmain(int argc, _TCHAR* ar...
Write it like this for map, since remove_if won't work for map iterators (it merely puts offending elements at the end, and map iterators don't allow for this): template <typename Map, typename F> void map_erase_if(Map& m, F pred) { typename Map::iterator i = m.begin(); while ((i = std::find_if(i, m.end(), pred...
7,007,817
7,007,890
A confusing detail about the Most Vexing Parse
My question is how the following line can be parsed as a function declaration: vector<int> v(istream_iterator<int>(cin), istream_iterator<int>()); I understand most of the details of the Most Vexing Parse and why the second temporary iterator can be interpreted as a type that is a function returning an iterator and ta...
istream_iterator<int>(cin) is exactly the same as istream_iterator<int> cin but with superfluous parens. This declarator syntax was inherited from C, and I think even the inventor of C (Ken Thompson?) described it as a mistake.
7,007,874
7,008,650
Finding location of crash using Map file
I am investigating a faulty code. Application verifier shows heap is corrupted after below call: AA!Class::Function+dbaf I have map file with me.Please help me how to reach on line number using above information and information present into Map file. Preferred load address is 00400000 0002:00000dc4 __imp_?Class@...
Do you only have a map file? No PDB? If you have full symbols then use the map and .pdbs (and .exe) with WinDBG (are you on windows?). I would imagine that you do seeing as how you have been given the name of the function. IF not... dbaf is your answer. What does that equate to? The offset should be the location of fau...
7,008,014
7,008,281
C/C++ - Conditional header file inclusion not working
I have three files in my project. a.c b.c test.h test.h declares a namespace test_namespace { int i; void f1(); }; test.h is also surrounded by #ifndef __x #define __x ... #endif now, a.c includes test.h and b.c also includes test.h . a.c has the main() function, and b.c has the implementation of test_name...
Include guards are there to protect multiple header inclusions in the build of a compilation unit. They aren't necessary for cases when you have two separate code files and one header, like your example. (So think more when test.c uses a.h and b.h, in those cases where b.h needs to #include a.h.) But that's a note a...
7,008,047
7,008,111
Is there a way to get the string representation of HRESULT value using win API?
Is there a function in win API which can be used to extract the string representation of HRESULT value? The problem is that not all return values are documented in MSDN, for example ExecuteInDefaultAppDomain() function is not documented to return "0x80070002 - The system cannot find the file specified.", however, it do...
You can use _com_error: _com_error err(hr); LPCTSTR errMsg = err.ErrorMessage(); If you don't want to use _com_error for whatever reason, you can still take a look at its source, and see how it's done. Don't forget to include the header comdef.h
7,008,323
7,008,932
Querying a bitmap distinguishing 0-values
I'm writing a piece of software that will process huge amounts of data. For memory efficiency, some of the fields in the records being processed are stored in a single bitmap. Using #defines I declared what both the position and the size of each field in the bitmap is. Now I need a fast way to check against predefined ...
As a solution I'd define and pass in a mask rather than position and size so if you wanted a 2 bit data from position 3 and 4 of an 8 bit map you'd define #define mask = 0x18;//binary 00011000 then in check bit you just need to: return (map & mask) == value;
7,008,423
7,009,435
How do I remove all the selected items in a QListWidget?
QListWidget::selectedItems returns a list of QListWidgetItem, but the only function for removing an item that I found is takeItem, which accepts only indexes, and selectedIndexes function is protected.
Try qDeleteAll(listWidget->selectedItems());
7,008,611
7,009,511
Detecting if an item is clicked at at some row in a QlistWidget
I Have been given this simple task , I have this list where i instert items whenever ok is clicked,void Form::ok() handle that event is supposed to add new list items to the list. Now what am not able to do is to detect the if an item is clicked at at some row then do something according to that, this is my code.. #in...
Something as below : connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(itemClickedSlot(QListWidgetItem *))); void Form::itemClickedSlot (QListWidgetItem * itemClicked) { //Do something with clicked item }
7,008,738
7,009,972
How get HDD current load info in windows?
I need once per second get information about HDD loading like (current write speed,current read speed, total loading percent etc.) more info is better. Spesial functions on Win32 API i dont find. Maybe need very low level functions or i need go to driver level. Please help me solve this problem! Thanks!
You have two options, checking the performance of your hard disk by accessing the S.M.A.R.T info or using the windows performance counters you can access these counters using the WInApi or the WMI. Check these resources S.M.A.R.T Hard drive information using S.M.A.R.T. WinApi Accessing Performance Data in C++ WM...
7,008,764
7,008,978
Is this LPARAM separated correctly now?
I am examining the value of a LPARAM when I receive the WM_KEYDOWN event. But I am unsure that I am correctly examining the 1st 16 bits then the next 8 bits & so on. This is how MSDN explains a LPARAM is organised for a WM_KEYDOWN msg: http://msdn.microsoft.com/en-us/library/ms646280(v=vs.85).aspx Are my bit (splits?)...
Here you go. void outputLParam( LPARAM lParam ) { printf("Repeat Count : %d\n", (lParam) & 0xFFFF); // print the value of the 1st 16 bits printf("Scan Code : %d\n", (lParam >> 16) & 0xFF); // print the value of the next 8 bits printf("Extended Key : %d\n", (lParam >> 24) & 0x1)...
7,009,053
7,009,153
How to make exe/tar.bz2 from .o file in G++?
Is there any way to make exe or tar.bz2 fiel from .o file in G++? Must I use nasm or any else program for making axe and tar.bz2, or it is possible in G++?
To make an exe, use the linker: g++ -o myprog myob1.o myob2.o To make a compressed archive, use tar: tar cjf myarchive.tar.bz2 /path/to/all/my/files/ To make an axe, use two sticks and three diamonds.
7,009,080
7,009,692
Detecting full screen mode in Windows
I need to detect if some application is currently running in full screen mode. If yes, then I must stop my application. So, how can I detect that? p.s. Win32 C++
hWnd = GetForegroundWindow(); RECT appBounds; RECT rc; GetWindowRect(GetDesktopWindow(), &rc); Then check if that windows isn't desktop or shell. Simple if instruction. if(hWnd =! GetDesktopWindow() && hWnd != GetShellWindow()) { GetWindowRect(hWnd, &appBounds); // Now you just have to compare rc to appBounds ...
7,009,270
7,009,331
what is the optimal data structure for a pool container?
At the moment i use the STL vector container template to put back and get the connections. 1) on get, a connection is returned and "erase()"d from pool vector. 2) on release, the connection is handed back to the pool via "push_back()". This might be very heavy if the pool is frequently used. So my question is, is there...
If you only append at the back and erase from the back, vector is fine. If you append and erase from both front and back, but never from the middle, use deque. If you frequently must insert into and erase from the middle, use list. Depending on your lookup and traversal requirements, set might be an alternative. In a...
7,009,330
7,009,507
Config cgi on apache2
I need my apache web server to run c++ compiled binary files. I've done everything I'm told in different tutorials to set my cgi-bin directory but nothing has helped! I've added to apache config (sites-available/default): ScriptAlias /cgi-bin/ /var/www/cgi-bin/ <Directory "/var/www/cgi-bin"> AllowOverride None ...
Your test.cgi does not output any headers. It should output a set of headers and a body, separated by a blank line, something like this: Content-type: text/plain Hello world! There are many more things that could be the problem, but start by adding a "content type" header and an empty line to your test programs outpu...
7,009,619
7,010,212
Swap memory speed in Linux
I have a process in Linux 64 bit (Redhat Enterprise) which enrolled one million of records into memory, each record is 4KB so total memory consumption is about 4 Gigabytes. My computer has 2GB of RAM and 3 GB of swap memory. So obviously part of data will be put into swap memory. The problem is that I don't know why i...
There are two options: The process works over the records sequentially. Than it was the stupidest thing on Earth to roll them all up to memory. If you can fix the process, fix it to only load a bit at a time. If you can't fix the process, you'll have to buy more memory. The process works over the records in random o...
7,009,797
7,009,849
How to read user keyboard input?
At the moment i use a system such as: case WM_KEYDOWN: keys[wParam] = true; Which doesnt work for lowercased letters or special characters such as "&", so im asking is there a winapi function to read keyboard so i could get any 8bit character from user, if he writes "Æ" i would get the corresponding index for that cha...
There is the WM_CHAR message which gives you the fully translated character code. Your message loop must use TranslateMessage prior to DispatchMessage for propper keycode to character translation.
7,009,812
7,010,080
Deriving different and incomparable types from int in C++
I know I cannot derive from an int and it is not even necessary, that was just one (non)solution that came to my mind for the problem below. I have a pair (foo,bar) both of which are represented internally by an int but I want the typeof(foo) to be incomparable with the typeof(bar). This is mainly to prevent me from pa...
As an alternative to writing it yourself, you can use BOOST_STRONG_TYPEDEF macro available in boost/strong_typedef.hpp header. // macro used to implement a strong typedef. strong typedef // guarentees that two types are distinguised even though the // share the same underlying implementation. typedef does not create ...
7,009,966
7,010,527
I/O overloading and reading from text files
I need to define a read and a print function for a class that has an array of objects as a private variable. I have to read in objects from a text file and print them to the screen. To do this I need to overload the << and >> operators. I understand I need to use loops to read and print the information stored in the ar...
Array Bounds In your class, you have: Employee list[MAXSIZE]; Given this, there is an error the code you tried: EmployeeList::EmployeeList(istream& in) { list[MAXSIZE] = in; } list only has elements from list[0] to list[MAXSIZE - 1]. list[MAXSIZE] is one past the end of the array, and is invalid. Constructors That ...
7,010,040
7,010,085
Easy way to iterate std::map<...>?
I have a variable with a type similar to: map<bool, map<string, pair<string, int> > > items; which I pass around to different functions. Is there a less tedious way for me to iterate over it then saying for (map<bool, map<string, pair<string, int> > >::iterator p = items.begin(); p != items.end(); p++) ... ev...
You can use BOOST_FOREACH. You'll have to use a typedef for clarity though: typedef std::map<std::string, std::pair<std::string, int> > inner_map; typedef std::pair<bool, inner_map> map_entry; BOOST_FOREACH(map_entry& p, items) { ... } I prefer a plain typedef and a for loop though. I see typedef the same way I s...
7,010,583
7,010,845
Looking for special C++ data structure
I'm looking for a C++ implementation of a data structure ( or a combination of data structures ) that meet the following criteria: items are accessed in the same way as in std::vector provides random access iterator ( along with iterator comparison <,> ) average item access(:lookup) time is at worst of O(log(n)) compl...
Let's go through these... average item lookup time is at worst of O(log(n)) complexity removal/insertion of items does not invalidate previously obtained iterators provides item insertion and removal of at worst O(log(n)) complexity That pretty much screams "tree". provides random access iterator ( along with ite...
7,010,587
7,013,572
write/read string in a TTree (cern root)
after saving a string into a TTree std::string fProjNameIn, fProjNameOut; TTree *tTShowerHeader; tTShowerHeader = new TTree("tTShowerHeader","Parameters of the Shower"); tTShowerHeader->Branch("fProjName",&fProjNameIn); tTShowerHeader->Fill(); I'm trying to do the following fProjNameOut = (std::string) tTShowerHeader...
Ok, this took a while but I figured out how to get the information from the tree. You cannot directly return the information, it can only be returned through the variable it was given in. std::string fProjNameIn, fProjNameOut; TTree *tTShowerHeader; fProjnameIn = "Jones"; tTShowerHeader = new TTree("tTShowerHeader","...
7,010,760
7,010,817
C++ keypress: getch, cin.get?
I have a Win32 program that runs on a loop. I would like to be able to pause that program while awaiting a keypress. It doesn't matter whether I use 'any key' or a specific key, but I need to have the program freeze until I press something. I am wondering which command I should use. I am working with Visual C++ and the...
You should use neither. You should use #include <iostream> ... int main() { ... std::cin.ignore(); //why read something if you need to ignore it? :) }' Here's the documentation
7,010,791
7,011,138
C++ Tuple of Boost.Range - get Tuple of element types?
I am experimenting with Boost.Range and the Boost Tuple. If I have a Tuple of ranges, how can I typedef a Tuple or the corresponding element values? To put this another way, what do I put in place of /*?*/ here: typedef boost::tuples::tuple<std::vector<int>&, char[]> TupleOfRanges; typedef /*?*/ TupleOfElements; I c...
Use boost::mpl::transform with that typedef chain you wrote as the functor! See http://www.boost.org/doc/libs/1_47_0/libs/mpl/doc/refmanual/transform.html
7,010,827
7,011,404
Named constructor idiom and new operator
I use the named constructor idiom to create objects, because I have lots of calls with identical parameters but the object shall be created differently. The C++ FAQ tell us how to do this. It also tells us how to force objects being heap allocated. Yet it really fails to tell us how to use the named constructor idiom w...
You can avoid named constructor idiom for this completely, and do it using an additonal dummy enum parameter to select the constructor. enum Carthesian {carthesian}; enum Polar {polar}; class point_t { int X,Y; public: point_t(int x, int y) : X(x), Y(y) { } // may keep as a default point_t(Carthesian, int...
7,010,887
7,011,216
i need to make 2 c++ scripts to compress and decompress Strings on tow different platforms windows mobile and PHP server
Possible Duplicate: Where can I find an example unzipper using zlib? Those scripts should be with the same algorithm for compression (or deflating) and decompression (or Inflating) Strings ,So i choose to use the zlib Library to handle this issue, My question is how to use ZLIB with c++ in details ,i.e integrating a...
You already have an answer for this in another post, look for 'C++ cross-platform zlib simplifer-wrapper'...
7,011,071
7,011,144
Detect 32-bit or 64-bit of Windows
I want to detect whether the current Windows OS is 32-bit or 64-bit. How to achieve it using C++? I don't want processor type I want OS's bit type. This is because you can install 32-bit OS on 64-bit processor.
The function to call is IsWow64Process or IsWow64Process2. It tells your 32-bit application if it is running on a 64 bit Windows. If the program is compiled for 64 bits, it will already know.
7,011,165
7,011,287
How do I send 10,000 ~ 20,000 bytes data over TCP?
Can I send about 10,000 ~ 20,000 bytes data over TCP? I am transferring an image (60 by 60) from Android client to linux server. On android it seems ok. On server side, if I try to send the picture data back to client, then it doesn't work. On client side, if I parse then I got some weird number that I shouldn't get. ...
What you are trying to do is easy (20K is not "big"). By far the most common reason something like this happens, is disregarding the return codes of send and recv. You should keep a few things in mind: send(2) can't always copy all the data from user space to kernel space. Check the returned value The data doesn't arr...
7,011,184
7,011,243
Floating point comparison
int main() { float a = 0.7; float b = 0.5; if (a < 0.7) { if (b < 0.5) printf("2 are right"); else printf("1 is right"); } else printf("0 are right"); } I would have expected the output of this code to be 0 are right. But to my dismay the output is 1 is right why?
int main() { float a = 0.7, b = 0.5; // These are FLOATS if(a < .7) // This is a DOUBLE { if(b < .5) // This is a DOUBLE printf("2 are right"); else printf("1 is right"); } else printf("0 are right"); } Floats get promoted to doubles during ...
7,011,238
7,014,918
Setup OpenCV-2.3 for Visual Studio 2010
I'm trying to use opencv 2.3 with Visual Studio 2010 Express. My code is from example: #include "stdafx.h" #include <highgui.h> int _tmain(int argc, _TCHAR* argv[]) { int c; // allocate memory for an image IplImage *img; // capture from video device #1 CvCapture* capture = cvCaptureFromCAM(1); ...
Well, the official guide is for installing OpenCV 2.1 on VS2010, so I wrote some instructions below that shows how to properly install and configure the x86 version of OpenCV 2.3 on Visual Studio 2010 (Express), since a lot of folks seem to have problems setting it up correctly. Download OpenCV-2.3.0-win-superpack.exe ...
7,011,333
7,011,401
pointer to a two dimentional array
How can I let a pointer assigned with a two dimensional array? The following code won't work. float a1[2][2] = { {0,1},{2,3}}; float a2[3][2] = { {0,1},{2,3},{4,5}}; float a3[4][2] = { {0,1},{2,3},{4,5},{6,7}}; float** b = (float**)a1; //float** b = (float**)a2; //float** b = (float**)a3; cout << b[0][0] << b[0][1] ...
a1 is not convertible to float**. So what you're doing is illegal, and wouldn't produce the desired result. Try this: float (*b)[2] = a1; cout << b[0][0] << b[0][1] << b[1][0] << b[1][1] << endl; This will work because two dimensional array of type float[M][2] can convert to float (*)[2]. They're compatible for any...
7,011,447
7,014,829
Concatenating two QStrings with an integer
I want to do something like this in C++ using Qt: int i = 5; QString directory = ":/karim/pic" + i + ".jpg"; where + means I want to concatenate the strings and the integer (that is, directory should be :/karim/pic5.jpg). How can I do this?
Qt's idiom for things like this is the arg()function of QString. QString directory = QString(":/karim/pic%1.jpg").arg(i);
7,011,552
7,011,605
How to expose hidden overloading from base class?
Given this code: class base { public: string foo() const; // Want this to be visible in 'derived' class. } class derived : public base { public: virtual int foo(int) const; // Causes base class foo() to be hidden. } How can I make base::foo() visible to derived without replicating it with a dummy method overloadi...
Sorry for the short answer, but yes. It's exactly like this and does what you want: class derived : public base { public: virtual int foo(int) const; using base::foo; }; Also note that you can access the base even without using: derived x; string str = x.base::foo(); // works without using
7,011,567
7,011,836
C++ <--> C# modify a marshalled array of bytes
I have an unmanaged C++ function which is calling a managed C# method in a DLL. The purpose of the C# method is to take an array of bytes (allocated by the C++ caller), populate the array, and return it. I can get the array INTO the C# method, but the populated data are lost when they get back to the C++ function. R...
You could do the marshaling yourself. Have the C# function accept a parameter by value of type IntPtr. Also a second parameter indicating array length. No special marshaling attributes are needed or wanted. Then, use Marshal.Copy and copy the array from the unmanaged pointer to a managed byte[] array that you alloca...
7,011,599
7,011,639
Efficient swap method for a derived class
Here is a code fragment that speaks for itself. Thank you! class Foo : private std::vector<int> { public: void swap(Foo& x) { std::swap(bar, x.bar); // what goes here? } private: int bar; };
std::vector<int>::swap(x); But, you shouldn't inherit from vector. Due to injected-class-names, this can be rewritten as vector::swap(x);
7,011,801
7,012,083
Image outline points generator?
Is there any code(specifically Java or C++) or software in which we import any image and it gives the outline of that image in points, which we can use again to draw image outline by joining those points in JOGL or OPenGL ..
There's an outline tracer in Inkscape (which is open source c++). http://inkscape.org/doc/tracing/tutorial-tracing.html This will convert to vector format - so you could get some points out this way. EDIT: this actually uses http://potrace.sourceforge.net/ for the tracing..
7,011,924
7,012,426
Maze representation help
I want to create maze using graph but I don't know where to start. I just know ways to represent a maze that use array of array or graph. In Array of Array representation, is recursive backtracking used to generate maze? If I choose to use graph-based struct to generate the maze, then how do I map edges representing p...
Thinking Labyrinth -- All you never thought you'd want to know about mazes. In addition to helping you identify terms for further research, this website is an extensive resource in itself.
7,012,073
7,012,155
what is the best way to return a pointer to vector's data? const or non-const?
#include <vector> using std::vector; class A { public: A() { buf.push_back(65); buf.push_back(66); buf.push_back(67); } ~A(){} const char * getA() const { // why never run here? return &buf[0]; } const char * getA() { return &buf...
Question 1 There is a compiler error because you've declared getB() as const. So therefore, buf is effectively const, so operator[] will return a const reference to the member element. Question 2 That overload of getA() never gets called because a is not const, so the non-const overload takes priority. If you do: con...
7,012,278
7,012,354
stop reading from stdin
I am writing a simple console application in LInux/C++ that accepts user input from command line. I am using std::getline( std::cin ) / std::cin >> text in a thread. After 10 seconds I would like to stop accepting console input and write a text message then do other things. I am using a separate thread for the timer. T...
You can use ncurses or if you don't want to, you can use select as described in this blog post. Basically, you can use select and specify the timeout. If the stdin FD is set, then you can read from it safely and won't block. If you want more info on select, check this out and of course Wikipedia. It's a handy call to k...
7,012,579
7,013,266
Qt/C++ memory leak with QThread and QPainter::drawText()
I'm using Qt4.6, 32bit compiled under 64bit Linux, and have a puzzling memory problem which I can't figure out. I have a QWidget containing a QLabel. This QLabel serves as a painting area by for each repaint setting: m_label->setPixmap(QPixmap::fromImage(image)); The image is updated in the widgets paintEvent: void Me...
While most drawing operations are supported onto QImage in a non-GUI thread, there is a supportsThreadedFontRendering on X11 systems about whether text rendering is allowed: http://doc.qt.nokia.com/4.7-snapshot/qfontdatabase.html#supportsThreadedFontRendering I'm not sure what that flag is returning on your system. Bu...
7,013,021
7,013,202
Breaking out of a loop with a keypress
I am writing a Win32 GUI app which has a loop which I would like to restart only when a keypress is made. The main loop is already running, and I can't simply restart it, so I have to insert a 'hang' point which the user can manually break out of. The code below represents what I have put at the end of my main loop. It...
You can just call MessageBox.
7,013,102
7,038,683
Installing My Qt app on the Symbian test device
after I have finished my code , it run perfectly. i want to try it on a Symbian Device ... I connected My phone via usb and then i choose Sync and connect I am using Qt Creator so i checked for Symbian device down left of the window.... and i run I got the following error: No device is connected. Please connect a devic...
Use nokia PC suite or nokia ovi suite to connect your mobile with PC.......It will automatically detect your device.
7,013,121
7,017,111
Compiling Boost.Test tests faster
I am using xcode (gcc) to compile my boost test suite and it takes too long. The tests are minimal dummy tests, yet it takes several seconds (about 20) to compile them: #include "boost/test/included/unit_test.hpp" BOOST_AUTO_TEST_CASE(dummy) { BOOST_CHECK_EQUAL(2+2, 4); } BOOST_AUTO_TEST_CASE(dummyFail) { BOO...
The reason it's slow to compile is because boost/test/included/unit_test.hpp is huge. Using a library makes it faster because the huge header is compiled when the library is built and not thereafter. Your tests then include a smaller set of headers, leading to shorter build times. Because I'm too lazy to build the libr...
7,013,176
7,013,492
Check whether DirectX or OpenGL is supported
i want to check whether a concrete DirectX Version (e.g DirectX 9) or a concrete OpenGL Version is suppported on the current windows system (to runtime of course).
OpenGL and DirectX is present all Windows Systems. But the capability to execute particular extentions or using capabilities are depends on hardware. It's possible to you query the particular feature and use the features. It differs from one machine to other. You can get the device parameters in Direct using GetDeviceC...
7,013,240
7,013,275
How can I use and launch an exe file inside my c++ program?
I want to use an .exe file inside my c++ program. I reviewed and checked these functions (system - ShellExecute - CreateProcess) to achieve this goal, but I found them useless because I need the output of that .exe file inside my program for further processes.
CreateProcess can be used to pipe the output from the created program back to the creator. MSDN even has sample code to do exactly this: Creating a Child Process with Redirected Input and Output
7,013,286
7,013,523
How to find, from which Types is object composed of?
ok, yesterday I posted almost identical question here , but I wasn't able to modify the answer(working) to my needs... I did not want to mess the other topic, so I have started new one. So, I have 2 (actually about 15) structs, which can composed an object class MyBase{}; template <typename Super, typename T1, typenam...
You can do that with function overloading: template <typename Super, typename T1, typename T2> void doStuff(A<Super, T1, T2>& a) { a.doStaffA(); } template <typename Super, typename T1, typename T2> void doStuff(B<Super, T1, T2>& b) { b.doStaffB(); } And then: // ... void update() { //this I want //if( com...
7,013,294
7,013,546
I fail to make enum work correctly
enum ENU{YES=0,NO,DONTKNOW}; void func(ENU e) { int n; cout<<"1+1="; cin >> n; if(n==2) cout<<e.YES; else cout<<e.NO; if(ischar(n)) cout<<e.DONTKNOW; } The error is always displayed. Because my program is too small and poor formed.
You probably want something like this: enum ENU {YES=0,NO,DONTKNOW}; void func() { int n; cout<<"1+1="; cin >> n; if(ischar(n)) cout<< DONTKNOW; else if(n==2) cout<< YES; else cout<< NO; } There's no point in your example in pass...
7,013,309
7,013,665
Visual Studio debugger error: Unable to start program Specified file cannot be found
I have a solution in C:\full path here\VS2010\blender.sln This solution contains many projects(around 100). When I compile them, they all work fine. I can run them without any problem, and (quite) everything works (there are some bugs). One of the projects is ALL_BUILD, but it gives the same error if I try to debug INS...
Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply n...
7,013,352
7,013,419
What's the Win32 API (MFC) equivalent to SystemInformation.CaptionHeight in .NET?
I am trying to figure out the Win32 API (MFC) equivalent to SystemInformation.CaptionHeight in .NET. So far I looked at SystemParametersInfo() (http://msdn.microsoft.com/en-us/library/ms724947%28v=VS.85%29.aspx) and it doesn't seem to fit the bill.
You can call GetSystemMetrics with an argument of SM_CYCAPTION. (If you look at the code for the .Net property, that's all it does.)
7,013,530
7,014,345
boost::asio and use of send()
When using a boost::asio::ip::tcp:socket there are many methods one can use to write/send data. There's also asio::write that takes the socket as a parameter, etc. My question is is there any compatibility issues (gotchas) with the boost asio libraries when using the standard send() function? Should one categorically n...
You need to use the boost asio send and send_to function for UDP sockets while the write method is used for synchronous stream write i.e used for TCP and cannot be used for UDP as it is "stream write".
7,013,705
7,013,794
Heap corruption between two DLLs
When I compile in release mode, I have heap corruption on the deallocation of a std::string. In fact, in a DLL named Atc.dll, I call a function which is in another DLL named Utilies.dll. At the end of my function in Atc.dll, I have the heap corruption. This my function in Atc.dll: void CoreController::readConfigXMLFil...
The usual reason (on Windows) is that you allocate memory in 1 dll, pass it to another when then frees is. Often this is fine, but if each dll is built with a different CRT (C runtime library) then you get issues like this. The reason there is that the debug CRT does memory allocation slightly differently than the rele...
7,013,708
7,044,960
Weird things with libCurl and OpenSSL
It's me again. I just can't understand, why it goes that way! I downloaded compiled static libs of OpenSSL, from here, this link is on the official cUrl site in Download page. I downloaded Zlib and compiled them, then I compiled libcurl with mingw32-make mingw32-ssl-zlib I changed in all makefile.m32 pathes to the Zl...
The openssl-libs you link against seem to be import-libraries. That means they only contain the information your code needs to call functions and then load and call the corresponding functions from the dll. So the problem is: although you link to static libs, the libs then load and use dynamic dlls. They are no "real" ...
7,013,981
7,014,624
Losing characters in TCP Telnet transmission
I'm using Winsock to send commands through Telnet ; but for some reason when I try to send a string, a few characters get dropped occasionally. I use send: int SendData(const string & text) { send(hSocket,text.c_str(),static_cast<int>(text.size()),0); Sleep(100); send(hSocket,"\r",1,0); Sleep(100); return 0; } Any...
As mentioned in the comments you absolutely need to check the return value of send as it can return after sending only a part of your buffer. You nearly always want to call send in a loop similar to the following (not tested as I don't have a Windows development environment available at the moment): bool SendString(c...
7,014,262
7,014,291
Overloading the << operator to print out a std::list
I've been having some problems trying to implement an overloaded << operator function that can print out a std::list which is a member of one of my classes. The class looks like this: class NURBScurve { vector<double> knotVector; int curveOrder; list<Point> points; public: /* some member functions */ friend o...
curve is const-qualified, so curve.points is const-qualified and curve.points.begin() returns a std::list<Point>::const_iterator, not a std::list<Point>::iterator. Containers have two begin() and end() member functions: one pair are not const-qualified member functions and return iterators, the other pair are const-qu...
7,014,553
7,047,169
SWI-Prolog C++ interface
I get an error while trying to load a DLL generated with swipl-ld in prolog the predicate that throws the exception is this initialization(shlib:use_foreign_library('C:/Users/valquiria.duarte/Desktop/dlog-server-0.3-beta-source/dlog-server/output/hash_swi.dll', install)), and the exception is this one ERROR: '$open_sh...
According to this note at ComputerHope, Windows may report this error when the file is missing (or corrupt). It appears the filepath is fully specified in the the call to use_foreign_library, but it's worth double-checking that the path is correct about where the DLL is located. It seems a little odd that you reported...
7,014,626
7,014,723
C++ throw dereferenced pointer
What is the type of the exception object in the following thrown: Question1> range_error r("error"); throw r; Answer1> an object of range_error Question2> exception *p = &r; throw *p; Answer2> a sliced object of exception Question3> exception *p = &r; throw p; Answer3> a pointer pointing to range_error is thrown....
I think you are right in all three. The type of the thrown object (IIRC) is the static type of the object being thrown. I would have to dig into the standard for a while to find the exact quotes, but a simple example seems to confirm this: struct base {}; struct derived : base {}; void t() { derived d; base * b...
7,014,634
7,213,354
Exposing a string on the global object in JavaScriptCore
I've written a portable framework in JavaScript, and I'd like to run some performance tests under various JavaScript interpreter shell environments. In order to accomplish this, I need to be able to pass command-line arguments (argv) to the script context. Rhino and Spidermonkey interpreters do this by default already,...
To create a JSString from a char*: JSC::JSGlobalData * globalData; JSString * CreateJSString(const char * chars, size_t length) { const char * string = chars; if (0 == length) { length = strlen(chars); } if (isASCII(string, length)) { JSString * jsstr = JSC::jsString(globalD...
7,014,871
7,014,893
C++ passing pointers
I'm expecting the code below to print 1 but its printing a random large number. I don't understand why this is happening, please advise. #include <iostream> using namespace std; int * returnArray() { int myArray[5]={1,2,3,4,5}; return myArray; } void printArray(int * myArray) { cout << *myArray<< end...
In your code, returnArray returns a pointer to the first element of myArray, which is local to the function. When the function returns, the memory of its local variables gets released as the call stack is popped, so it can be used for other purposes. In this case, since you call printArray afterwards, the stack area or...
7,015,006
7,015,752
XML data binding for C++ like JAXB for java
I am writing this question as a complete **naive** in this field of "Use of data binding and parsing in c++". So, please bear with me . :) You may find this question as duplicate of THIS After doing a bit of googling I found that what C++ has similar library to JAXB for java for object representation of an XML in...
Answer to the first question: No! Serialization is almost always a small subset of data-binding. Data binding gives you an object model specific to your schema. That means you have to have a schema to use data-binding. No such need for XML serialization/deserilization. Check this too: http://www.rpbourret.com/xml/XMLDa...
7,015,007
7,015,077
Owner drawn taskbar thumbnail preview
Is there a way to draw the taskbar thumbnail preview on my own, instead of letting Windows draw it for me? What I need is a dynamic thumbnail; for example, let's say I want the thumbnail to be a reverse of the "real" thumbnail. Any way to do that?
Yeah you can do with this method: DwmSetIconicLivePreviewBitmap. Complete example: http://msdn.microsoft.com/en-us/library/ff819048(v=vs.85).aspx
7,015,068
7,015,802
Why does creating new v8::Array before v8::Scope cause segmentation fault, but v8::String and v8::FunctionTemplate do not?
Please consider the following code snippets, based on v8's sample.cc sample shell, which causes a segmentation fault: int RunMain(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::HandleScope handle_scope; // Create a template for the global object. v8::Handle<v8::ObjectTemplate...
When you create a new v8::Array via API V8 actually invokes Array constructor from the current context. It's almost as if you executed new Array(n) in JavaScript. If there is no context then there is nothing V8 can invoke to create an array thats why it segfaults. v8::String represents primitive string value. No contex...
7,015,209
7,015,249
Template class with template function
Can anyone tell what is wrong with this piece of code? template<class X> class C { public: template<class Y> void f(Y); // line 4 }; template<class X, class Y> void C<X>::f(Y y) { // line 8 // Something. } int main() { C<int> c; char a = 'a'; c.f(a); return 0; } Compilation: $ g++ source.cpp ...
The compiler already tells you the answer. The class C is a template with one parameter, and the member function f is a template member function, and you have to define it in the same way: template <class X> template <class Y> void C<X>::f(Y y) { // Something. } If you define the function at the declaration site, ...
7,015,285
7,015,465
Undefined reference to 'operator delete(void*)'
I'm new to C++ programming, but have been working in C and Java for a long time. I'm trying to do an interface-like hierarchy in some serial protocol I'm working on, and keep getting the error: Undefined reference to 'operator delete(void*)' The (simplified) code follows below: PacketWriter.h: class PacketWriter { pu...
If you are not linking against the standard library for some reason (as may well be the case in an embedded scenario), you have to provide your own operators new and delete. In the simplest case, you could simply wrap malloc, or allocate memory from your own favourite source: void * operator new(std::size_t n) { void...