question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,857,869 | 4,857,884 | Can ENOENT mean too many files on partition? | When calling access(2) and getting an errno == ENOENT the man page says:
ENOENT A directory component in pathname would have been accessible but
does not exist or was a dangling symbolic link.
However, in my case I was trying to create a file in /tmp/ and the directory component was accessible and exists.... | The main meaning of ENOENT is 'no such file or directory'. It means that the name you tried to access() was not there.
If you were trying to create the file, then maybe, perhaps, you would get ENOENT when there are 'too many files in a directory', but you'd be more likely to get some other error, I think - perhaps ENO... |
4,857,892 | 4,857,933 | Defining iterator of my own container | I am confused with some concepts about defining my own iterator:
From this: http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-iterator-define.html, which seems to suggest using inner iterator class which defines the operators. Many others inherit the base class iterator to redefine the operators.
I am quit... | The C++ specification on what exactly an STL container is mandates that any STL container type have several different fields available. Some, like begin() and end(), are functions, while others, like iterator, are types. These restrictions also apply to iterators. This allows C++ template functions to introspect on ... |
4,857,915 | 4,857,977 | Arranging bytes in a packet | If I need to create a packet like this:
field 1: SOCKS protocol version, 1 byte
field 2: status, 1 byte:
field 3: reserved, must be 0x00
field 4: address type, 1 byte:
field 5: destination address of
1 byte of name length followed by the name for Domain name
field 6: network byte order port number, 2 bytes... | In order to have what you want you can't have each field as a specific fixed index in the packet array because each position can only hold atmost one byte. You'd have to do something like this:
char address[] = "www.google.com";
int addressLen = strlen(address);
char* packet = (char *) malloc(sizeof(char)*6+addressLen)... |
4,858,042 | 4,859,020 | Python :: ctypes :: GetProcAddress() returns error | The following is a part of a debugger class. I've got the following code for enumerating processes in debugee. First it enumerates and loads handles of the existing debugee's processes into an array. Then I'm trying to get an address of particular function in particular module. In this case i'm trying to get address of... | GetProcAddress gets the address of a function in a DLL loaded in your process, not in a different process. You should check out the Debug Help Library.
Per your request about GetProcAddress, my references:
GetProcAddress
hModule [in]
A handle to the DLL module that contains the function or variable. The LoadLibrary... |
4,859,263 | 4,859,487 | Can multithreading speed up memory allocation? | I'm working with an 8 core processor, and am using Boost threads to run a large program.
Logically, the program can be split into groups, where each group is run by a thread.
Inside each group, some classes invoke the 'new' operator a total of 10000 times.
Rational Quantify shows that the 'new' memory allocation is tak... | Dynamic allocation of memory uses the heap of the application/module/process (but not thread). The heap can only handle one allocation request at a time. If you try to allocate memory in "parallel" threads, they will be handled in due order by the heap. You will not get a behaviour like: one thread is waiting to get it... |
4,859,306 | 4,860,697 | Rotate Sprite to Mouse Position | I've been using the SFML 1.6 library, and I'd like to know.
How does one rotate a sprite so it always turns toward where the mouse is located on screen?
Thanks.
(SFML specific code is preferred)
| If you have the position of the sprite : S = (Sx, Sy) and the position of the cursor C = (Cx, Cy)
You can calculate the angle between the vector = (Cx - Sx, Cy - Sy) and a unit vector for example = (1, 0, 0).
To calculate the angle you can use the cross product :
And then :
then you calculate the angle :
Finally Y... |
4,860,086 | 4,860,140 | ptrdiff_t too small? | I've always wondered: isn't ptrdiff_t supposed to be able to hold the difference of any two pointers by definition? How come it fails when the two pointers are too far? (I'm not pointing at any particular language... I'm referring to all languages which have this type.)
(e.g. subtract the pointer with address 1 from th... | No, it is not.
$5.7 [expr.add] (from n3225 - C++0x FCD)
When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is d... |
4,860,162 | 4,860,213 | C++ method signature problem | I'm trying to call addValues below:
Obj *s = new Obj();
vector<tm> dates(SIZE);
vector<double> values[COUNT];
for (uint i = 0; i < COUNT; i++) {
values[i] = vector<double>(SIZE);
}
s->addValues(&dates, &values); // <- this is the error line
and I've defined addValues:
void addValues(vector<tm> *newDates, vector<do... | template <size_t N>
void addValues(vector<tm>* newDates, vector<double> (&newValues)[N]);
The reason this works is because its a template. The value N is known at compile time since you define values as an array: vector<double> values[COUNT]. Since the compiler knows the size of values at compile time, it is able to r... |
4,860,215 | 4,860,721 | Ogre3D shows segfault error | I'm writing a game using Ogre3D and I have a problem.
When I starting program, it shows an segfault error:
*-*-* OGRE Initialising ... |
Compile the program with debugging information included (with GCC, this means make sure the -g option is passed to the compiler).
Run it in a debugger.
When it crashes, you'll get a stack trace.
Investigate if it seems to depend on something you did (or not did, such as a missing initialization), or if it looks like a... |
4,860,380 | 4,860,467 | Are bitwise operations going to help me to serialize some bools? | I'm not used to binary files, and I'm trying to get the hang of it. I managed to store some integers and unsigned char, and read them without too much pain. Now, when I'm trying to save some booleans, I see that each of my bool takes exactly 1 octet in my file, which seems logical since a lone bool is stored in a char-... | To store bools in a byte:
bool flag; // value to store
unsigned char b = 0; // all false
int position; // ranges from 0..7
b = b | (flag << position);
To read it back:
flag = (b & (1 << position));
|
4,860,549 | 4,860,694 | Embedding Lua in C++ mixed with C | I am working on embedding Lua in a C++ project, which relies heavily on some legacy C code. I have a few questions regarding to garbage collection and variable scope.
Here are some snippets related to the questions that follow:
/* C side */
typedef struct
{
/* fields */
} Element;
typedef struct
{
void * m_ele... | In Lua, elements that are no longer referenced are garbage collected (at the proper time).
This means that el_h and el_s will be considered for garbage collection whenever you will overwrite them, you don't need to make them local.
In other words, the object you'll get for el_h when i = 1 will be marked for being garba... |
4,860,550 | 4,860,601 | To avoid bugs is it necessary to erase the stack? | What do you need to do to clean up an int or char (not a pointer)?
Is it necessary to clean up this type of data after use?
sample ex:
// MAX = 100 ;
class Simple {
int a[ MAX ] ;
public :
~Simple ( ) ;
... // some declaration to fill, initial... | You don't have to overwrite int or char arrays unless you really care that data store in them can be somehow used to obtain sensitive data like passwords from your program.
See this and this questions for details on when that is needed. You likely don't need to worry about that.
But don't confuse overwriting memory wit... |
4,860,788 | 4,860,812 | Why is address of char data not displayed? | class Address {
int i ;
char b;
string c;
public:
void showMap ( void ) ;
};
void Address :: showMap ( void ) {
cout << "address of int :" << &i << endl ;
cout << "address of char :" << &b << endl ;
cout << "address of string :" << &c << endl ... | When you are taking the address of b, you get char *. operator<< interprets that as a C string, and tries to print a character sequence instead of its address.
try cout << "address of char :" << (void *) &b << endl instead.
[EDIT] Like Tomek commented, a more proper cast to use in this case is static_cast, which is a... |
4,861,002 | 4,861,264 | Equilibrium Index - What's wrong with my solution? | I have taken this example test before I'll try to take the real one for a job interview. The challenge is to implement the Equilibrium Index problem correctly.
I have coded some sort of solution that works only for the simple example and some of the edge cases.
Here's the code:
typedef vector<int> container_t;
typede... | Your logic it's right.
A[0] + A[1] + A[2] = A[3] + A[4] + A[5] is equivalent to A[0] + A[1] + A[2] - (A[3] + A[4] + A[5]) = 0
However, in your code, in the loop you add the values all the time, you never change the sign for those in the other half.
for (iterator_t iter = A.begin(); iter != A.end(); ++iter, ++i) {
su... |
4,861,141 | 4,861,231 | How can one manipulate an data nested private classES over using friend function | class Hen {
friend class Nest ;
class Nest {
int n ;
friend class Egg;
class Egg {
int e ;
} *eg;
} *nst ;
public :
friend void fill ( **!** ) ... | You need to make the outer class a friend of the nested class:
class Hen {
class Nest {
friend class Hen;
class Egg {
friend class Nest;
};
};
};
|
4,861,302 | 4,861,361 | Sigbus on std::map.find | I have got a map defined inside a class in header file like this:
std::map<int, char> mCompletedIds;
I can do with a vector here, as I just need to store the ids which have been completed. But to have fast find, I am using map. So, I always put second argument of pair as 0.
Now, In one of the fns. of class, I am doing ... | If you just want a store of numbers you can use std::set<int>
To see if a value is present use
std::set<int> mCompletedIds;
bool found = mCompletedIds.count(id) != 0;
Your SIGBUS error will usually be caused by bad alignment or some other corruption that happened in your code, and a tool like valgrind may indicate to... |
4,861,704 | 4,861,760 | What happens when I call a function in a DLL | I use a dll compiled from C++ code (LPSolve, see http://lpsolve.sourceforge.net/5.5/), from my C# code. I use the API to build a linear programming model, and subsequently solve it. I call functions such as:
[DllImport("lpsolve55.dll", SetLastError = true)]
public static extern bool add_columnex
(int lp, int... | Because the function prototype is using plain old datatypes and arrays, the memory for these values is pinned in place and then the native code acts directly on the data. Then when the function returns, the memory is unpinned and can be garbage collected.
In other words, they never leave the scope.
In terms of the C++ ... |
4,861,824 | 4,861,920 | Proxy server using socks5 | I have a problem when i`m sending my last packet,as I said in the comentary,I'm getting an warning sayng that i returned an unexpected answer follow by a different hex number every time i run it.
I am using Proxifier to test this,it always give me this when i try to connect to google:
[06:22] Starting: Test 1: Connect... | Following those lines of code:
if(temp[4] == 14) // test for lenght of www.google.com
{
char* domain = new char[temp[4]];
//....
Maybe it should be
domain[13] = '\0'; instead of domain[14] = '\0';
|
4,861,897 | 4,862,159 | sending error message to console | At run-time, How we can send a error message to console ?
Ex; like assert's job ;
assert ( expression ) ;// when it evaluates to false, it send a error message
I want to write a code, in more complex ;
ASSERT ( expression , error message ) ;
How can I do ? ( of course without using cout )
| This is a technique I have often seen:
assert ( <expression> && "Put your message here") ;
If expression fails then the assert still fails.
Also assert will put the whole expression into the error (including the message).
|
4,861,898 | 4,861,951 | Outputting bit data to binary file C++ | I am writing a compression program, and need to write bit data to a binary file using c++. If anyone could advise on the write statement, or a website with advice, I would be very grateful.
Apologies if this is a simple or confusing question, I am struggling to find answers on web.
| Collect the bits into whole bytes, such as an unsigned char or std::bitset (where the bitset size is a multiple of CHAR_BIT), then write whole bytes at a time. Computers "deal with bits", but the available abstraction – especially for IO – is that you, as a programmer, deal with individual bytes. Bitwise manipulatio... |
4,861,914 | 4,863,328 | What is the meaning of the term "free function" in C++? | While reading the documentation for boost::test, I came across the term "free function". What I understand is that a free function is any function that doesn't return anything (Its return type is void). But after reading further it seems that free functions also don't take any arguments. But I am not sure. These all ar... | The term free function in C++ simply refers to non-member functions. Every function that is not a member function is a free function.
struct X {
void f() {} // not a free function
};
void g() {} // free function
int h(int, int) { return 1; } // also a free function
|
4,861,935 | 4,893,005 | AJAX response not valid in C++ but Apache | I want to make a server written in C++ to power my game. I learned the basics of sockets and wrote a basic chat program that worked well. Now I want to create an HTTP server like Apache, but only for the AJAX request-response part.
I think just for the beginning i copied one Apache response text, and i sent the exact r... | the problem:
the index.html is served through apache on port 80. the browser loads it and starting sending requests.
The request file (program) was on another port , on the 8888 port, which already is a different server which dont enables ajax (dont know why) to get the post data. the program can still communicate with... |
4,861,942 | 4,862,094 | Embedding Lua in C++: Accessing C++ created through Lua, back in C++ (or returning results back from Lua to C++) | The title probably sounds a bit recursive - but this is what I am trying to do:
I have C++ classes Foo and Foobar;
I am using tolua++ to export them to Lua
In Lua:
function wanna_be_starting_something()
foo = Foo:new()
fb = Foobar:new()
-- do something
foo.setResult(42) -- <- I want to store something back at... | To understand how to exchange data back and forth, you should learn about the Lua stack that is the structure Lua uses to communicate with the host program. I guess tolua++ takes care of this for the classes/methods you exported.
Here there is a good start: http://www.lua.org/pil/24.html is for Lua 5.0 but there are in... |
4,861,965 | 4,862,280 | Is there an STL string class that properly handles Unicode? | I know all about std::string and std::wstring but they don't seem to fully pay attention to extended character encoding of UTF-8 and UTF-16 (On windows at least). There is also no support for UTF-32.
So does anyone know of cross-platform drop-in replacement classes that provide full UTF-8, UTF-16 and UTF-32 support?
| Well in C++0x there are classes std::u32string and std::u16string. GCC already partially supports them, so you can already use them, but streams support for unicode is not yet done Unicode support in C++0x.
|
4,862,130 | 5,251,074 | In IE, how can I find the screen coordinates of an HTML element including elements within frames? | I'm working on a browser automation framework that, among other browsers, drives IE. As such, I need to get the screen coordinates of elements the user wants to interact with. The primary method we use to get these coordinates is by using getBoundingClientRect(). The problem is that in IE, these coordinates are always ... | The correct approach for this project is to get the document containing the frame or iframe element and looping through the set of frames in that parent document until you find the proper frame. Once there, you can get the or element using the document.parentWindow.frameElement(), and can calculate the location of th... |
4,862,222 | 4,885,394 | locally disable function inlining | I need to make the compiler to not inline an inlined function.
eg:
I have an inline function A.
I have a function B that calls A.
In B, A is inlined and this is perfect.
Now I have a function C that calls A many times.
In C, A is inlined, and it is not good.
Is it possible to tell the compiler to not inline A when it i... | I have found the following solution:
template <class F> ALWAYS_INLINE F NOINLINE( F f ) {
return f;
}
It seems that the compiler (MSVC at least) don't inline functions called like this:
NOINLINE(my_inline_function)();
I think it is similar to the "calling it through a function pointer" solution from Nick D
|
4,862,386 | 4,863,223 | Parsing LPTSTR* command line args with boost::program_options | I am having a problem with command line parsing with boost:program_options. The quickest way to explain it is to show the code so:
const std::vector<tstring> args;
if (ac > 0 && NULL!=av) //ac is a ULONG
{
for (int i = 0; i < ac; i++)
{
args.push_back(av[i]); //av is an LPTSTR pointer (pointer to TCHAR... | You seem to be using a unicode build, so either explicitly use the wide char version:
po::wcommand_line_parser parser(args);
or the more flexible:
po::basic_command_line_parser<TCHAR> parser(args);
|
4,862,914 | 4,862,932 | Array initialization [c/c++] | Why this is not allowed?
#include <cstdio>
struct Foo {
int fooId;
char arr[ ];
} fooList[] =
{ {1, {'a', 'b'}},
{2, {'c', 'd'}}
};
int main()
{
for (int i = 0; i < 2; i++)
printf("%d %c\n", fooList[i].fooId, fooList[i].arr[0]);
}
whereas, this is allowed:
struct Foo {
int fooId;
char arr[2]; // this line ... | Only the last member of a C struct can be flexible as in arr[].
Shamelessly copying from paragraph 6.7.2.1, sub-paragraph 16 of the ISO C99 standard:
16 As a special case, the last element
of a structure with more than one
named member may have an incomplete
array type; this is called a flexible
array membe... |
4,862,959 | 4,863,127 | C++ how to store initial state of program in DLL / recognize uninitialized variable | I'm writing a DLL in C++ for use with VB6. As such, I cannot have a constructor called in my DLL (according to this discussion). However, I need to maintain an instance of a class internally -- so I intend to keep the object as a global variable and call the constructor from a global function, and after that, use anoth... | You can use global static variables or file scope variables in your CPP files:
bool bInited = false;
MyClass* pClass = NULL;
These assignment statements will be called inside DllMain, later you can test if they have been initialized properly.
You could declare the pointers as auto_ptr (if you use stl or something equ... |
4,863,211 | 4,863,288 | boost::bind and reference to temp variable | Suppose I have method:
void foo(const std::string& s);
Can I create boost::function:
boost::function<void(const std::string&)> f = boost::bind(foo, temp);
where temp is char* that is deleted before f is called.
| Yes. Bind cannot know that the char* can be held in a string, or that it is being passed to a string. To circumvent this, use:
boost::bind(foo, std::string(temp));
So that your temp is copied into the binder as a string.
|
4,863,221 | 4,863,336 | What's c++ compiling performance bottle neck? | When I do a fresh compilation for my project, which includes 10+ open-source libs. It takes about 40mins. (on normal hardware)
Question: where really are my bottle necks at? hard-drive seeking or CPU Ghz? I don't think multi-core would help much correct?
--Edit 1--
my normal hardware = i3 oc to 4.0Ghz, 8GB 1600Mhz DDR3... | Since VS 2010, VS can optionally use multiple cores when compiling a single project. It can also compile multiple projects in parallel. However, the parallel speed-up doesn't seem to be significant in my experience: e.g. Xcode is much better at doing parallel builds.
Fortunately you can don't have to rebuild the open s... |
4,863,324 | 4,863,373 | Create reference to new object | I am just learning C++, and I've come across the following conundrum:
As a C++ newbie, I've read that using reference instead of pointers (when possible) is generally a good idea, so I'm trying to get into the habit early. As a result, I have a lot of methods which have the general form of
void myMethod(ParamClass cons... | You should try not to use new, to begin with, as using it brings the trouble of memory management.
For your example, just do the following:
int main(int, char*[])
{
SomeObject myObject;
// two phases
ParamClass foo(...);
myObject.myMethod(foo);
// one phase
myObject.myMethod(ParamClass(...));
return 0;... |
4,863,790 | 4,864,190 | How do I copy binary data to a stringstream | I have a std::vector<int> and I want serialize it. For this purpose I am trying to use a std::stringstream
vector<int> v;
v.resize(10);
for (int i=0;i<10;i++)
v[i]=i;
stringstream ss (stringstream::in | stringstream::out |stringstream::binary);
However when I copy the vector to the stringstream this copy it as ... | Actually, this is your workaround but it may be used with std::copy() algorithm.
template<class T>
struct serialize
{
serialize(const T & i_value) : value(i_value) {}
T value;
};
template<class T>
ostream& operator <<(ostream &os, const serialize<T> & obj)
{
os.write((char*)&obj.... |
4,863,791 | 4,863,847 | Creating both static and shared C++ libraries | I'd like to build both static and shared libraries in a project.
I know that shared libraries need to be be created from objects compiled with -fpic to get Position Independent Code while the static library doesn't need this. This is all fine and I can create either a shared or static library.
I wouldn't want to compil... | The common approach that I've seen is, in fact, compiling your source twice, once with PIC and once without. If you don't do that, you either wind up with PIC overhead in the static library, or a shared object that can't be relocated by the OS (effectively meaning it's NOT shared across multiple clients of the library)... |
4,864,022 | 4,864,095 | Reference parameter lifetime | Given the following:
class ParamClass {...};
class MyObject {
public:
void myMethod(ParamClass const& param) { _myPrivate = param; }
private:
ParamClass _myPrivate;
}
[...]
MyObject obj;
void some_function(void)
{
ParamClass p(...);
obj.myMethod(p);
}
What will happen to _myPrivate at the end of t... | Since _myPrivate is not a reference, in the assignment _myPrivate = param, its value will be copied over from whatever the reference param points to, which in this case is the local variable p in some_function().
So if the assignment operator for ParamClass is implemented correctly, the code should be fine.
will I st... |
4,864,283 | 4,864,665 | What are the functions in the standard library that can be implemented faster with programming hacks? | I have recently read an article about fast sqrt calculation. Therefore, I have decided to ask SO community and its experts to help me find out, which STL algorithms or mathematical calculations can be implemented faster with programming hacks?
It would be great if you can give examples or links.
Thanks in advance.
| Several of the algorithms in <algorithm> can be optimized for vector<bool>::[const_]iterator. These include:
find
count
fill
fill_n
copy
copy_backward
move // C++0x
move_backward // C++0x
swap_ranges
rotate
equal
I've probably missed some. But all of the above algorithms can be optimized to work on many bits at a t... |
4,864,339 | 6,058,669 | zLib inflate has empty result in some cases | My program processes PDF files and reads some streams out of them. There are also FlateEncoded streams in there. I use the "inflate()" method of zlib to decompress them.
This usually works really well with the following code:
static string FlateDecode(string s){
int factor = 50;
z_stream stream;
while(true... | zlib simply seems to not support all deflated streams found in PDF files.
|
4,864,341 | 4,864,457 | Assigning C++ function pointers to member functions of the same object | How do I get the function pointer assignments (and maybe the rest) in test.calculate to work?
#include <iostream>
class test {
int a;
int b;
int add (){
return a + b;
}
int multiply (){
return a*b;
}
public:
int calculate (char operatr, int operand1, int operand2){
... | There are several problems with your code.
First, int (*opPtr)() = NULL; isn't a pointer to a member function, its a pointer to a free function. Declare a member function pointer like this:
int (test::*opPtr)() = NULL;
Second, you need to specify class scope when taking the address of a member function, like this:
if ... |
4,864,345 | 4,864,405 | How to conditionally include a file into Makefile? | Consider the following Makefile:
# <include global configuration Makefile>
INCL = -I../include \
-I<whatever>
CPPFLAGS=$(DEFS) $(INCL)
CXXFLAGS = -O0 -g -Wall -fmessage-length=0
SRCS = $(wildcard *.cpp)
OBJS = $(SRCS:.cpp=.o)
all: $(OBJS)
%.o: %.cpp
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
depend: ... | Something like this:
ifneq ($(MAKECMDGOALS),clean)
-include .depend
endif
See the make manual page on Goals for more information
Edit: -include cannot be tab indented, otherwise it is ignored.
|
4,864,503 | 4,864,819 | istream's tellg/seekg cannot be protected from stack smashing (g++)? | For a program that I'm writing, it is useful for me to calculate file sizes, which I calculate by using iostream's tellg and seekg functions, but this leads to a warning by -Wstack-protector. The following code reproduces the "problem":
#include <iostream>
std::streamsize get_file_size(std::ifstream& ifs) { // line 12... | You might wan't to see this.
And the general advice is you really shouldn't care, especially in your case, when you don't allocate any internal buffers that can be used to perform buffer overflow attack.
|
4,864,516 | 4,864,712 | How to access elements in a list in c++ | I am working through problems in Accelerated C++
We have a program which stores strings in vectors and outputs them according to certain rules.
The original code fragment is as follows.
typedef vector<string> Rule;
typedef vector<Rule> Rule_collection;
typedef map<string, Rule_collection> Grammar;
// read a grammar f... | You will need to replace your code with something like this:
ret[*(entry.begin())].push_back(
Rule(++(entry.begin()), entry.end()));
|
4,864,645 | 4,864,718 | Simple assert for ordered non re-entrant calling? | I have two functions:
void prepare() and void finish() that will be called sequentially like:
prepare();
<do something>;
finish();
...
prepare();
<do something>;
finish();
I want to make a simple assertion to simply test that they are in fact being called this way and that they aren't being called concurrently or ... | Your code is OK, unless you need to allow nesting prepare and finish calls.
If nesting is not allowed, you could use a bool instead of an int:
bool locked = false;;
void prepare() {
assert( ! locked );
locked = true;
...
}
void finish() {
assert( locked );
locked = false;
...
}
|
4,864,866 | 4,864,879 | C/C++ with GCC: Statically add resource files to executable/library | Does anybody have an idea how to statically compile any resource file right into the executable or the shared library file using GCC?
For example I'd like to add image files that never change (and if they do, I'd have to replace the file anyway) and wouldn't want them to lie around in the file system.
If this is possib... | With imagemagick:
convert file.png data.h
Gives something like:
/*
data.h (PNM).
*/
static unsigned char
MagickImage[] =
{
0x50, 0x36, 0x0A, 0x23, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20,
0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4D, 0x50, 0x0A, 0x32, 0x37,
0x37, 0x20, 0x31, 0x36, 0x32, 0x... |
4,864,902 | 4,864,934 | C++, iterator question | map <int, char*> testmap;
testmap[1] = "123";
testmap[2] = "007";
map<int, char*>::iterator p;
for(p = my_map.begin(); p != my_map.end(); p++) {
int len = strlen(p); // error here, why? thanks
cout << len << endl;
cout << p->first << " : ";
cout << p->second << endl;
}
I got error on this lie: int len = strlen(p... | I guess what you mean is
strlen(p->second);
|
4,865,021 | 4,865,071 | How to properly solve the "undefined reference to vtable" error? | I've read the FAQ and several other websites about this, but I can't seem to find the proper solution. I'm quite sure you've heard the question before, and I'd like to ask for specific help as to how I should solve this, if possible.
The specific error is:
error: undefined reference to `vtable for FGui'
It always point... | You need to moc your FGui and Ffoo classes.
|
4,865,231 | 4,865,454 | How do I avoid copy constructor in the conversion function? | I am trying to convert between two classes and avoid a temporary object.
Here is my declaration for Square:
class CSquare
{
public:
int dimension;
CSquare(int dimension);
// Conversion to Rectangle
operator CRectangle();
~CSquare(void);
};
and here is my declaration for Rectangle:
class CRectangl... |
How do I avoid the temporary object?
You don't. That's how conversions work. The temporary may be elided (constructing directly into the destination), but that is not required.
It sounds like you want move semantics, which are in C++0x. Even then, the temporary "exists", but it can be moved instead of copied, whic... |
4,865,428 | 4,865,467 | Invalid conversion to non-const reference in C++0x... bug in std::pair? | I have been developing a library that is getting pretty large, and now I am adding some template-based parts that use C++0x features. So I tried to compile my library (which compiled entirely without warnings on the current standard) with the flag -std=c++0x using gcc version 4.4.5 (on Linux). Now I got a huge influx o... | There are LOTS of bugs in gcc C++0x support, it's very much unfinished and development is ongoing. This is doubly true for a version as old as gcc-4.4.5. If you're serious about starting C++0x development before the standard is ratified, you need to use the bleeding-edge version of the compiler and standard library.
|
4,865,515 | 4,865,741 | Standard library containers producing a lot of copies on rvalues in GCC | I'm writing a app for both linux & windows, and noticed that the GCC build is producing a lot of useless calls to the copy constructor.
Here's an example code to produce this behavior:
struct A
{
A() { std::cout << "default" << std::endl; }
A(A&& rvalue) { std::cout << "move" << std::endl... | Both implementations (Visual C++ 2010 and GCC 4.4.0) are in error. The correct output is:
default
default
default
This is specified in 23.3.5.1 [vector.cons]/4:
Requires: T shall be DefaultConstructible.
The implementation is not allowed to assume that A is either MoveConstructible nor CopyConstructible.
|
4,865,561 | 4,865,678 | How do I prevent a runaway input loop when I request a number but the user enters a non-number? | I need to know how to make my cin statement not appear to 'remove' itself if you input the wrong type. The code is here:
int mathOperator()
{
using namespace std;
int Input;
do
{
cout << "Choose: ";
el();
cout << "1) Addition";
el();
cout << "2) Subtraction";
el();
cout << "3) Multi... | After reading in a bad value, cin is in a "failed" state. You have to reset this.
You must both clear the error flag and empty the buffer. thus:
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
The second call "flushes" the input buffer of any data that might be there, to get you ready for... |
4,866,043 | 4,866,087 | Overload resolution with extern "C" linkage | In a mixed C/C++ project, we need to make a call from C to a C++ function. The function to be called is overloaded as three separate functions, but we can ignore that from the C-side, we just pick the one most suitable and stick to that one.
There's two ways to do this: (1) write a small C++ wrapper with a extern "C" f... | I believe the language in the standard is specifically written to allow exactly one function with "C" linkage, and an arbitrary number of other functions with "C++" linkage that overload the same name (§[dcl.link]/6):
At most one function with a particular name can have C language linkage. Two declarations for a funct... |
4,866,290 | 4,866,383 | How many instances are there of static data declared inside a static member function in a header file? | I'm working on compiling Cppcheck on AIX using xlC. Every checker class is derived from a Check class, whose constructor is responsible for registering that type of checker in a global static list.
Here's the relevant part of the code in question (filenames link to full source on Github):
check.h
class Check {
public:
... | g++ has the correct behavior: there should be exactly one instance of the object. The C++ Standard says (C++03 7.1.2/4):
A static local variable in an extern inline function always refers to the same object.
Because the class has external linkage, the static member function also has external linkage, per C++03 3.5/... |
4,866,425 | 4,866,845 | Mixing class and struct | I'm well aware of the difference between class and struct, however I'm struggling to authoritatively say if this is well defined:
// declare foo (struct)
struct foo;
// define foo (class)
class foo {
};
// instance of foo, claiming to be a struct again! Well defined?
struct foo bar;
// mixing class and struct like t... | It looks to me like it's defined behavior. In particular, §9.1/2 says:
A declaration consisting solely of class-key identifier ; is either a redeclaration of the
name in the current scope or a forward declaration of the identifier as a class name. It introduces the class name into the current scope.
The standard di... |
4,866,433 | 4,866,508 | Is it possible to typedef a pointer-to-extern-"C"-function type within a template? | I want to add a public typedef to a template for a pointer to a function-taking-one-argument that uses "C" language linkage.
I tried:
extern "C" {
template <typename return_t_, typename arg1_t_>
struct test
{
typedef return_t_ (*C_fun1_t)(arg1_t_);
};
}
And:
template <typename return_t_, typena... | C++03, §7.5p4:
A linkage-specification shall occur only in namespace scope. … A C language linkage is ignored for the names of class members and the member function type of class member functions.
Unfortunately, you simply can't do this in current C++. This text is unchanged in the latest C++0x draft, but "template ... |
4,866,456 | 4,866,477 | Why does this implementation of COM IUnknown::Release work? | From examples I've seen COM IUnknown::Release() function implementation is something like that:
ULONG Release()
{
InterlockedDecrement(&m_count);
if(m_count == 0) {
delete this;
}
return m_count;
}
So, if m_count is 0, so we're deleting "this" object, and returning the ref count.
What I don't un... | That code is bogus. One can never trust m_count after the decrement. The correct code is always like this:
ULONG Release()
{
ULONG count = InterlockedDecrement(&m_count);
if(count == 0){ delete this; }
return count;
}
|
4,866,669 | 4,866,751 | C++ returning more precise of two template arguments from function? | I'm curious if there's any way to do this in C++. Let's say I have a templated vector class:
template <typename T>
class vector {
public:
vector(T a, T b, T c) : x(a), y(b), z(c) {}
T x,y,z;
};
And then I have a templated addition operator:
template <typename A, typename B>
vector<A> operator +... | There isn't any built-in support in the form of a library, but you can accomplish this using the conditional (?:) operator.
In reply to another answer, Johannes Schaub posted a promote<T, U> template that wraps the logic up quite nicely. With the template, you should be able to write:
template <typename A, typename B>... |
4,866,672 | 4,866,922 | Converting between Windows CryptoAPI and OpenSSL x509 formats | I have a CERT_CONTEXT structure which I've extracted from a smart card on Windows via the CryptoAPI. I need to convert this structure into a DER encoded byte array which is consistent with OpenSSL. The closest match I've got so far is via CryptEncodeObject using X509_ASN_ENCODING and the X509_CERT_TO_BE_SIGNED modifier... | DER encoded certificate can be obtained from (ctx->pbCertEncoded, ctx->cbCertEncoded) buffer where ctx is a PCCERT_CONTEXT object. Still you won't be able to recover the private key.
|
4,866,701 | 4,870,857 | Python PyGILState_{Ensure/Release} causes segfault while returning to C++ from Python code | UPDATE Well, it looks like adding PyEval_InitThreads() before the call to PyGILState_Ensure() does the trick. In my haste to figure things out I incorrectly attributed my "hanging" to PyEval_InitThreads().
However, after reading some Python documentation I am wondering if this is the correct solution.
It is not safe t... | Python expects a certain amount of initialization to be done by the main thread before anything attempts to call back in from a subthread.
If the main thread is an application that is embedding Python, then it should call PyEval_InitThreads() immediately after calling Py_Initialize().
If the main thread is instead the ... |
4,866,762 | 4,870,322 | MFC - Printing - Changing page orientation from a custom pagesetup dialog | I am developing a custom print dialog and page setup using MFC and VS2008 for my Win32 program. Since the code is legacy, I can't take much advantage from MFC view/doc architecture. As a result, I wrote a printing code completely from scratch.
I setup CPrintInfo, instantiate my custom print dialog box and hook this di... | Nowhere in your example code do you show how you're creating the DC for printing. When you call CreateDC, you must pass a pointer to a DEVMODE structure; this defines whether the printing will be portrait or landscape.
|
4,866,886 | 4,866,923 | Defaut Character Set 'Unicode' in Visual Studio 2005 | Does that mean i'm writting 64 bit code for x64 OS?
| No. It means that TCHAR is mapped to wchar_t and all functions that take TCHAR or LPTSTR arguments are mapped to their Unicode variants. For example CreateWindow is mapped to CreateWindowW and not to CreateWindowA.
And this is completely unrelated to CPU architecture. You can write Unicode and Multibyte programs for... |
4,866,913 | 4,867,462 | SSE normalization slower than simple approximation? | I am trying to normalize a 4d vector.
My first approch was to use SSE intrinsics - something that provided a 2 times speed boost to my vector arithmetic.
Here is the basic code: (v.v4 is the input) (using GCC) (all of this is inlined)
//find squares
v4sf s = __builtin_ia32_mulps(v.v4, v.v4);
//set t to square
v4sf t = ... | I am a dope - I realized I had SETI@Home running while benchmarking. I'm guessing it was killing my SSE performance. Turned it off and got it running twice as fast.
I also tested it on an AMD athlon and got the same results - SSE was faster.
At least I fixed the shuf bug!
|
4,867,430 | 4,867,519 | What is the proper way to overload operators in abstract base classes? | Suppose I have an abstract base class, that just defines a container on which addition can be performed:
class Base {
public:
virtual ~Base() {}
virtual Base operator+(const Base& rhs) =0;
};
Then I want subclasses of Base to provide the actual operation:
class Derived: public Base {
public:
Base operator+... | The best thing is not to.
operator+ returns a value and you can't return a value of an abstract type, by definition. Overload the operators only for concrete types and avoid inheriting from concrete types to prevent "slicing by overloaded operator".
Overload symmetric binary operators like operator+ as free functions a... |
4,867,559 | 4,867,600 | Naming Include Guards | How are C++ include guards typically named? I tend to see this a lot:
#ifndef FOO_H
#define FOO_H
// ...
#endif
However, I don't think that's very intuitive. Without seeing the file name it's difficult to tell what FOO_H is there for and what its name refers to.
What's considered best practice?
| From my own experience, the convention is to name the inclusion guards after the header file containing them with the exception that the name is all in caps and the period is replaced with an underscore.
So test.h becomes TEST_H.
Real life examples of this include Qt Creator, which follows this convention when auto-gen... |
4,867,839 | 4,868,757 | how can I tell if pthread_self is the main (first) thread in the process? | background: I'm working on a logging library that is used by many programs.
I'm assigning a human-readable name for each thread, the main thread should get "main", but I'd like to be able to detect that state from within the library without requiring code at the beginning of each main() function.
Also note: The librar... | This is kinda doable, depending on the platform you're on, but absolutely not in any portable and generic way...
Mac OS X seems to be the only one with a direct and documented approach, according to their pthread.h file:
/* returns non-zero if the current thread is the main thread */
int pthread_main_np(void);
I also ... |
4,867,912 | 4,868,138 | arrayList<string> problem | Here is the arrayList class:
template<class T>
class arrayList: public linearList<T>
{
public:
// constructor, copy constructor and destructor
arrayList(int initialCapacity = 10);
arrayList(const arrayList<T>&);
~arrayList() {
delete[] element;
}
void insert(int theIndex, const T& theElem... | You should try to use std::string as the contained type. While that will fragment the memory a bit, it will make the code simpler, and less error prone. As it is, it will not be able to handle words that take more than 10 characters (or 9 plus the nul terminator if you want to make the words compatible with C strings),... |
4,867,925 | 4,868,116 | Static method definition delegated to derived class (c++) | Last year I saw some source code (C++) where its author declares static function in base class, but leaves its definition to derived class. I remember there was constraint that only one derived class was permitted to define aforementioned static function.
I know that it is impossible to override static methods, but thi... | What it sounds like you are trying to do is a bit messy in my opinion. It feels like a combination of a Factory class, a Singleton and then trying to squish them all back into your result class hierarchy.
The simplest (not necessarily the best) solution I can think of is forget about having either Circle::Factory() or ... |
4,867,952 | 4,868,219 | Problem setting desktop wallpaper using SystemParametersInfo Function | I am just learning C++ and am trying to write a small program to change the desktop wallpaper. Using the documentation here, I wrote this program:
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")
void main(){
BOOL success = SystemParametersInfo(
SPI_SETDESKWALLPAPER, //iuAction
... | It addition to Dennis' comment about JPEG files, it is also important whether or not you compile with UNICODE in effect. If you do then you'll have to specify the file as L"C:\test.jpg". Note the L in front of the string, that makes it a wide string. Or use SystemParametersInfoA(), note the A (but it's archaic).
|
4,867,965 | 4,868,115 | Include File Ordering Strategy | I've seen fairly consistent advice that an implementation file (.cc / .cpp) should include its corresponding class definition file first, before including other header files. But when the topic shifts to header files themselves, and the order of includes they contain, the advice seems to vary.
Google coding standards ... | The order you list your includes shouldn't matter from a technical point of view. If you designed it right, you should be able to put them in any order you want and it will still work. For example, if your foo.h needs <string>, it should be included inside your foo.h so you don't have to remember that dependency ever... |
4,868,049 | 10,184,756 | How to efficiently wrap the index of a fixed-size circular buffer | I have a fixed size circular buffer (implemented as an array): upon initialization, the buffer gets filled with the specified maximum number of elements which allows the use of a single position index in order to keep track of our current position in the circle.
What is an efficient way to access an element in the circ... | Best I've come up with is:
public static int Wrap(int index, int n)
{
return ((index % n) + n) % n;
}
(Assuming you need to work with negative numbers)
|
4,868,204 | 4,869,141 | Issue Parsing File with YAML-CPP | In the following code, I'm having some sort of issue getting my .yaml file parsed using parser.GetNextDocument(doc);. After much gross debugging, I've found that the (main) issue here is that my for loop is not running, due to doc.size() == 0; What am I doing wrong?
void
BookView::load()
{
aBook.clear();
QString f... | Along the lines of what you thought, the problem is that you're writing using QDataStream but reading using plain std::ifstream. You need to do either one or the other.
If you want to use the QDataStream, you'll need to read it in as well. Check out the doc for more detail, but it looks like you can just grab the YAML ... |
4,868,226 | 4,868,351 | Is calling pure virtual functions indirectly from a constructor always undefined behaviour? | I'm working on building Cppcheck on AIX with the xlC compiler (see previous question). Checker classes all derive from a Check class, whose constructor registers each object in a global list:
check.h
class Check {
public:
Check() {
instances().push_back(this);
instances().sort();
}
static st... | Yes, it's undefined. The standard specifically says so in 10.4/6
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or d... |
4,868,227 | 4,868,371 | Valid uses for C++ include guards besides, well, include-guarding? | This question is one of several that discuss naming conventions for C++ include guards. The person asking that question thinks that this naming convention:
#ifndef FOO_H
#define FOO_H
// ...
#endif
is a bit non-intuitive when taken by itself (what does FOO_H mean?) and I tend to agree.
Others say that, barring the ... | I think the question is flawed in itself. The term include guards refers to #defines and checks for #defined in the particular use of guarding against multiple inclusion, which is as much to say that is the only use for that.
Now taken a little more generally, defines and conditional compilation can be used for other t... |
4,868,235 | 4,896,365 | Popup windows are behind window but it is rendered front? | I am updating the webkit embeded to my program however I come across a new problem about popup windows (MessageBox or File/Folder chooser dialogs).
For instance, if I invoke a javascript alert() clicking on a link, the MessageBox is rendered in front of the webkit window and looks like it is clickable, however when it... | In win/webview.cpp WM_CANCELMODE message invokes a function. Comment out, problem is solved.
|
4,868,449 | 4,868,977 | C++ : Why isn't my call to "std::uninitialized_copy" working? | I building a simple class that is supposed to mimic the functionality of the std::string class (as an exercise!):
#ifndef _STR12_1_H
#define _STR12_1_H
#include <string>
#include <iostream>
class Str12_1
{
public:
typedef char* iterator;
typedef const char* const_iterator;
typedef long size_type;
S... | Looking at the standard raw_storage_iterator does not typedef value_type to be T, but it's void instead:
template <class OutputIterator, class T>
class raw_storage_iterator
: public iterator<output_iterator_tag,void,void,void,void>
^^^^
whereas uninitialized_copy has to use that t... |
4,868,473 | 4,868,498 | What does it mean when a function signature has "&" before the name? | int &sum(int numa, int numb)
{
int sum = 0;
sum = suma+sumb;
return sum;
}
Is this function correct? Why does it use &?
ADDED COMMENT:
thank you all. But after I compiled it using gcc, it came up one warning but no error. It can run perfectly. Still wrong? or just a warning issue? –
| The & means you're returning a reference. In your case, you're returning a reference to an int, one that disappears as soon as the function returns; this is a serious bug.
|
4,868,561 | 4,869,159 | C++ Compiler tells me a type is not recognized | Using Visual C++ 2010 I have a code like the following:
file A.hpp:
...
#include "R.hpp"
...
class A; // forward declaration because the APtr_t is used inside the A class too.
typedef boost::shared_ptr<A> APtr_t;
...
class A {
...
void some_method () {
...
R::get()->mehod(); // singleton ;)
...... | My psychic debugging skills guess that A.hpp includes R.hpp and that your headers have proper include guards. In this case the include chain would look like blah.cpp -> A.hpp -> R.hpp -> A.hpp (include guard prevents inclusion). So it never saw A.hpp's contents inside R.hpp at all. You'll need to use one of the standar... |
4,868,759 | 4,868,790 | c++ printf question: How can I safely pass a char* to printf? | const char* abc = "foo";
printf(abc);
Is this safe or proper? I saw some legacy code including this.
Thanks!
Very very sorry..I made a mistake, i changed it back....
| No, this isn't safe. Assuming abc points to a valid string (which it currently doesn't), this kind of pattern can be susceptible to a format-string vulnerability. Refer to Format string attacks
edit: I see that you fixed the code in your question. It used to pass abc as the first argument to printf, which is really, re... |
4,868,966 | 4,869,192 | C++ mysterious code. any security issue? | foo(foo &afoo): va(foo,va++){
}
What is the security issue or problem of this code snippet.
| This with g++ compiles, and I don't think there's any UB
struct Va
{
Va(struct Foo&, int) {}
};
int operator++(const Va&, int) { return 42; }
struct Foo
{
Va va;
Foo(Foo &afoo) : va(afoo,va++) {}
};
to be specific operator++ is not doing anything with the not-yet-initialized va data member. It's more or ... |
4,869,216 | 4,869,356 | Calling derived class function from base class | class base
{
public:
virtual void start();
virtual void stop();
void doSomething() { start(); .... stop(); }
}
class derived : public base
{
public:
void start();
void stop();
}
But when I call doSomething() in the derived class it is using it's own definition of Start() and Stop() - not the derived ... | The code you've posted should work the way you want. Calling doSomething on an instance of derived will call the overridden start and stop functions defined in derived.
There's an exception to that, though. If you call doSomething in the constructor or destructor of base (whether directly or indirectly), then the versi... |
4,869,373 | 4,869,387 | How to compile Templates located in different files in C++? | When I put all the source in one file, the program successfully builds. However when I split them into header files, I get a link error.
The main of my program:
//C++_Class_Templates.cpp
#include <iostream>
#include <vector>
#include "Queue.h"
using namespace std;
//Usage for C++ class templates
void main()
{
My... | The short answer is: "you don't."
The longer answer is: well, it's basically the same as the short answer. For more information, see the C++ FAQ Lite entry "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?" Except for certain limited-use scenarios (like w... |
4,869,684 | 4,869,751 | C++0x library that implements move for fstreams | After finding the answer to How to return an fstream (C++0x), I was now wondering if there is a current c++0x library that implements move (or even swap) for fstreams (as gcc (27.9) does not). I'd prefer if it was free also.
Or is there any other way return to fstreams from functions by value?
I've tried compiling lib... | I believe Dinkumware sells a version of the C++ Standard Library with movable streams, but be sure to check it first.
|
4,869,754 | 4,869,874 | no suitable conversion function from "std::string" to "PVOID" exists | I am trying to use the SetParametersInfo function to change wallpapers.I would like to pass the filepath for the wallpaper as a variable, but whenever I try to do this, I get the error
Error: no suitable conversion function from "std::string" to "PVOID" exists
Here is the code I have thus far
#include <windows.h>
#in... | input.c_str() will return a const char * that will implicitly convert to PVOID.
Pass input.c_str() to SystemParametersInfo and it should work.
*Make sure this is not compiled with UNICODE=1 because then SystemParametersInfo is redirected to SystemParametersInfoW which would expect a std::wstring, not a std::string.
If... |
4,869,983 | 4,871,218 | How to create a program that can read all the images in folder using Boost and OpenCV? | What I want is simple: I need to open all images in a folder (I dont care for subfolders but it would be great to be able to search subfolders) and turn them into a vector of IplImage*s so I can use Boost.Foreach to loop through each image. How can I achieve this?
| Take a look at boost filesystem to find all the images files in a directory.
Then cvLoadImage or cv:imread to read each file
|
4,870,062 | 4,892,432 | CUDA compiling error | I write my first CUDA code as follows:
#include<iostream>
__global__ void kernel ()
{
}
int main()
{
kernel<<<1, 1>>> ();
std::cout<<"hello world"<<std:endl;
system("pause");
return 0;
}
And I set up Visual Studio 2008 following the instructions on these two pages:
Easiest Way to Run CUDA on Visua... | It looks like you have some non-latin characters in your directory names and that may be causing issues. Can you try putting the toolkit and your project into a directory without such characters? You'll probably also need to point the TMPDIR and TEMPDIR environment variables (I think I remembered those correctly) to la... |
4,870,151 | 4,870,520 | How to run each function from vector in new separate thread? | So I have something like
typedef boost::function<void(DataType)> Function;
typedef std::vector<Function> FunctionSequence;
typedef typename FunctionSequence::iterator FunctionIterator;
DataType* dataElement;
FunctionSequence funcs;
//...
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++i... | If what you're trying to do is launch a new thread for each function, and pass in a copy of your DataType object, you'll want to use Boost Threads and Boost Bind:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
boost::thread_group tg;
for (FunctionIterator it(funcs.begin()); it != ... |
4,870,279 | 4,870,340 | C++ Inheritance - why my function was not used? | I have a IBase class with virtual void CastData(){} in it. there it is used in another function.
I have another totally unrelated class IC with
virtual void CastData(){
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it){
DataType dataCopy;
dataCopy = *dataElement;
(*it)(dataCo... | virtual functions must be overriden by a derived class, not another base class. Perhaps provide an override in IGraphElement that calls into IC to do the work.
|
4,870,343 | 4,870,367 | Wrapping my head around windows.h - const char* vs LPSTR | I am getting started with the following simple messagebox application. The problem is that when I run this application the text is Chinese. I clearly have an encoding issue. Can someone point me to somewhere I can learn about windows.h specific string typedefs?
//test.c
#include <windows.h>
int WINAPI WinMain(HINSTANC... | It's most likely a wide char vs ordinary char issue. Try changing the code to:
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
MessageBox(NULL, L"Hello World", L"Note", MB_OK);
return 0;
}
If this solves your problem it means your pro... |
4,870,437 | 4,870,467 | pair<int,int> pair as key of unordered_map issue | My code:
typedef pair<int,int> Pair
tr1::unordered_map<Pair,bool> h;
h.insert(make_pair(Pair(0,0),true));
Erorr
undefined reference to `std::tr1::hash<std::pair<int, int> >::operator()(std::pair<int, int>) const'
Something I need to fix?
thanks
| This happens because there is no specialization for std::tr1::hash<Key> with Key = std::pair<int, int>.
You must to specialize std::tr1::hash<Key> with Key = std::pair<int, int> before declaring tr1::unordered_map<Pair,bool> h;.
This happens because std don't know how to hash a pair<int, int>.
Following there is a exam... |
4,870,549 | 4,871,090 | The 'L' and 'LPCWSTR' in WIndows API | I've found that
NetUserChangePassword(0, 0, L"ab", L"cd");
changes the user password from ab to cd. However,
NetUserChangePassword(0, 0, (LPCWSTR) "ab", (LPCWSTR) "cd");
doesn't work. The returned value indicates invalid password.
I need to pass const char* as last two parameters for this function call. How can I do ... | Those are two totally different L's. The first is a part of the C++ language syntax. Prefix a string literal with L and it becomes a wide string literal; instead of an array of char, you get an array of wchar_t.
The L in LPCWSTR doesn't describe the width of the characters, though. Instead, it describes the size of the... |
4,870,592 | 4,875,298 | Extrend QAbstractListModel to display custom background color? | Greetings all,
I have extended my own QAbstractListModel to change the background color of QCombobox.
As seen it the image ,I have two issues.
1) As shown in the first image snapshot , background color doesnt appear for the selected item.
2) When selecting items , the background turns in to default highlight color (l... | Both features (background of the selected item and highlighting color) are controlled by the view. Here is a quote from the docs:
For the text and icon in the combobox label, the data in the model that has the Qt::DisplayRole and Qt::DecorationRole is used.
So the background of the selected item wont be easy to chan... |
4,870,601 | 4,905,061 | valgrind reports problems with libcurl when using https | So I've got a very basic example of talking to a facebook server over https, but valgrind is complaining sadly. So I assume I'm not setting something up incorrectly... does anyone know what I'm doing wrong?
Here's my code:
#include <string>
#include <iostream>
#include <curl/curl.h>
size_t write_fn_impl( void* ptr, si... | MK is partially correct. Valgrind does throw up a lot of junk warnings about OpenSSL. But in my case the crashes I was seeing did seem to be due to some trouble with how I was using openSSL. In particular it was not getting correctly set up for multithreaded use. The curl docs cover what you need to do .. but somehow I... |
4,870,739 | 4,870,775 | nested class inheritance | template<class T>
class base
{
class nestedClass
{
T pos;
};
class derivedClass:public base<T>::nestedClass
{
void fun(){
pos = pos +5; // error: pos is not declared in this scope
}
};
};
| C++03 [Section 14.6/8] says
When looking for the declaration of a name used in a template definition, the usual lookup rules (3.4.1, 3.4.2) are used for nondependent names. The lookup of names dependent on the template parameters is postponed until the actual template argument is known (14.6.2).
Section 14.6.2/3 says... |
4,870,893 | 4,870,940 | Need help with getting the current memory on a program | I need to get the up to date memory useage of a program that is running. i googled it and found GetProcessMemoryInfo this looks like what i needed but i can't get it to work.
It wont take the handle i find for the window and i am not really sure what they want.
#include <iostream>
#include <Windows.h>
#include <tchar.h... | GetProcessMemoryInfo takes a process handle, not a window handle. After you find the window, you can call GetWindowThreadProcesId to the process ID, then OpenProcess to get a handle to the process. Then you can finally call GetProcessMemoryInfo for that handle.
When you do call it, you don't need the BOOL WINAPI at the... |
4,870,902 | 4,871,722 | Given three *slightly* different copies of a class object, how can I efficiently store the difference between them? | Direct Question: With three (or more) nearly identical copies of a class object, how can I best (or most efficiently) store the differences between them?
Background: I have an algorithm which requires a set of parameters:
struct params
{
std::string A;
std::string B;
double C;
double D;
userDefinedType... | You might find the Flyweight design pattern to be of interest. It is designed specifically to solve your problem.
Here's one way to store the differences:
Step 1: Replace all your members with pointers to the members. Yes, this adds a little memory overhead.
Step 2: Have classes store shallow copies of shared members... |
4,870,918 | 4,872,632 | Divide the application screen in Qt | I want to divide the application screen into parts like one part is fixed showing fixed controls & another one is variable which can be changed when user select something. Like in Qt Creator we are having the left side column always fixed & the content of center screen is changing when user is selecting something. I ha... | When you speak of the Qt Creator you certainly mean the controls on the left and right. In my opinion, the best thing to implement that are QDockWidgets. Have a look at them in the docs and as Martin said, look at the examples, they are perfect to learn each of the layout and composing issues.
QDockWidgets can be made ... |
4,870,930 | 4,871,063 | Duplicating subclass of abstract baseclass | I have an abstract base-class to enforce some subclasses to overload the << operator.
I am storing a bunch of pointers to instances of these subclasses in an std::stack... At some point I wish to duplicate the top item of the stack (and push it on top).
The problem is, I cannot instantiate an abstract class. And obviou... | I think you actually need a Clone method in this case. You want to dynamically copy the subclass item at runtime, and the normal way to change behavior at runtime is virtual methods. Without using some virtual method you would have no way of figuring out which child it is. You could probably use CRTP to automatically g... |
4,870,947 | 4,895,049 | Mutually exclusive contiguous ranges from multiple bitfields | (This is not a CS class homework, even if it looks like one)
I'm using bitfields to represent ranges between 0 and 22. As an input, I have several different ranges, for example (order doesn't matter). I used . for 0 and X for 1 for better readability.
.....XXXXX..............
..XXXX..................
.....XXXXXXXXXXXXX... | I'm assuming the solution you're mentioning in the comment is something like this:
Start at the left or right (so index = 0), and scan which bits are set (upto 100 operations). Name that set x. Also set a variable block=0.
At index=1, repeat and store to set y. If x XOR y = 0, both are identical sets, so move on to in... |
4,870,977 | 4,870,984 | nested iterator errors | //arrayList.h
template<class T>
class arrayList{
public:
// constructor, copy constructor and destructor
arrayList(int initialCapacity = 10);
arrayList(const arrayList<T>&);
~arrayList();
// iterators to start and end of list
class iterator;
class seamlessPointer;
seamlessPointer begin()... | I think that one of the problems is that you've written
sort(dict.begin, dict.end(),compare_nocase);
instead of
sort(dict.begin(), dict.end(),compare_nocase);
(Notice the parentheses after dict.begin)
Without compiling the code myself I'm not sure if there's anything else lurking here. I'll keep looking and update t... |
4,871,093 | 4,871,399 | Unable to open sqlite database | I have a simple app that I am doing that will load a list for my inventory. I am doing this to learn a little bit about Qt because it looks really neat.
I have a few windows and a database that all those windows pull data from. I get 8 compile errors when following the built in examples (though they all are for in me... | Add the following file to your *.pro file:
QT += sql
and do a qmake and build.
|
4,871,262 | 4,871,323 | Will overrides be called when class instance was send as if it was type with out overrides? | Having Class B that extends class A and overrides its functions can we be sure that when sending instance of (B*) as if it were type (A*) our overrides we created in class B will be called?
| As long as the method on A is defined as virtual this will be the case for both pointers and references. For example
class A {
virtual void Method() {
cout << "A::Method" << endl;
}
};
class B {
// "virtual" is optional on the derived method although some
// developers add it for clarity
virtual void M... |
4,871,273 | 4,871,563 | Passing rvalues through std::bind | I want to pass an rvalue through std::bind to a function that takes an rvalue reference in C++0x. I can't figure out how to do it. For example:
#include <utility>
#include <functional>
template<class Type>
void foo(Type &&value)
{
Type new_object = std::forward<Type>(value); // move-construct if possible
}
c... | The reason this fails is because when you specify foo<Movable>, the function you're binding to is:
void foo(Movable&&) // *must* be an rvalue
{
}
However, the value passed by std::bind will not be an rvalue, but an lvalue (stored as a member somewhere in the resulting bind functor). That, is the generated functor is a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.