question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,523,654
6,524,646
How to grab specifc libraries from my boost/lib folder?
I've compiled Boost and it works just fine. I would like to to copy specific .dll's and .libs into my project for deployment. The problem is I'm having a hard time finding which packages contain the libraries I need. I've looked around but haven't seen any documentation on what's actually inside the compiled libraries....
Are you deploying your application as an executable or as a project to be compiled by the user? If it is the former, you shouldn't need to send static libraries, as they're linked into your executable. If you build Boost libraries as dynamic libraries, you will need them of course. But if you're deploying your app as s...
6,523,883
6,525,514
How can one identify children of a child process?
I have a long-running Python program that starts and stops a Postgres server as part of its operation. I stop the server by using subprocess to spawn pg_ctl -m fast. As a fall-back, I check the return code and, if it failed, I then run pg_ctl -m immediate. The problem is that sometimes both fail. I haven't been able...
Here is a simple shell script solution: pgrep -P $(head -1 $PGDATA/postmaster.pid) This prints out the PIDs of the child processes. I'm not aware of a standard Python module that can get that information. pgrep gets the information from /proc, so you could reimplement that in Python, but I doubt that it would be wort...
6,523,991
6,526,263
Proper way to design object hieararchy
In my game Bitfighter, I have a class called AbstractTeam that has two subclasses: Team and EditorTeam. They share many methods, but Team tracks spawn points (implementing addSpawn() and getSpawns() methods), whereas EditorTeam does not care at all about spawn points. There are two designs I can see for implementing t...
Use number 1. That's what dynamic_cast is for. You definitely should not define members in your base class that all derived classes will not implement.
6,524,062
6,525,273
Encrypting Strings using XOR and hashing them using BSAFE(OpenSSL like library)
I have to calculate SHA-2 hash of an XOR encrypted string. I am using RSA BSafe library(very similar to OpenSSL). My XOR function looks something like this: for (int i = 0; i < strlen(combined); i++) { encrypted[i] = (combined[i] ^ authkey[i%strlen(authkey)]); } This produces some '\0' chars (NullTerminations) in...
With OpenSSL, you pass the length explicitly. The data containing NULLs does not matter. unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len, const unsigned char *d, int n, unsigned char *md, unsigned int *md_len); n is the length of your data, which is pointed to by d. O...
6,524,087
6,524,230
C++ Call Function When Variable is Requested
I've see this done before in languages based on mono, but I'm just curious if this would be possible in c++. If I had the following class class test { public: int foo; int myfunction(); }; when I try and access the foo variable, is their any way I can make it so it calls myfunction and returns its valu...
One possible workaround, which is a bit evil, would be to use a macro. #include <stdio.h> #define FOO myfunction() class test { private: int foo; public: int myfunction() { return 42; } }; int main() { test t; printf("%d\n",t.FOO); return 0; } As I alluded to in the comments to your ...
6,524,185
6,524,855
private copy constructor/assignment operator and copy-initialization
This is a followup of this question in the following code, why does line 1 compiles while line 2 and 3 does not (using visual C++ 2010) class ABase { protected: ABase() {} ~ABase() {} private: ABase( const ABase& ); const ABase& operator=( const ABase& ); }; class A : ABase { }; class B { public: ...
The compiler is wrong in accepting the first use. Even if the copy is elided, the copy constructor must be accessible for the code to be correct. In this particular case there is an implicitly declared copy constructor in A: §12.8/4 If the class definition does not explicitly declare a copy constructor, one is declare...
6,524,259
6,526,213
What are the consequences of mixing exception handling models in Visual Studio 2010?
I have third-party static library built with Enable C++ Exceptions set to No (/EH flag not specified). What are the consequences to calling into it from code built with C++ exceptions enabled (/EHa)? If a Structured Exception is thrown from within the library, will the function provided to _set_se_translator by the ma...
Calling into code which does not have exceptions enabled shouldn't produce any problems -- this is no different than calling an external C function or something of that nature. Calling from code which does not have exceptions enabled (into exception enabled code) will probably not contain the correct stack unwinding se...
6,524,677
6,524,802
Variable keeps getting set to NULL after function in DLL
I need valid data to be in the global variable QObject *p. However, assigning anything to this variable inside of a function works within the scope of the function, but after the function returns, p is set back to NULL, even though p is global. Here is my code: #include ... // various includes // p is NULL ...
You're creating a shallow copy of that parameter mParent. At some point, that pointer must be getting set to null (or you're passing it as null), which will result in p also becoming null.
6,524,821
6,524,940
Opening stream via function
I need help with the non-copyable nature of [io](f)streams. I need to provide a hackish wrapper around fstreams in order to handle files with unicode characters in their filenames on Windows. For this, I devised a wrapper function: bool open_ifstream( istream &stream, const string &filename ) { #ifdef __GLIBCXX__ F...
What about: ifstream * open_ifstream(const string &filename);
6,524,888
6,524,932
C++ standard terminology for heap/stack
There seems to be some uncertainty about the terminology that should be used. There seems to be 2 different points of view: some people prefer to use heap and stack to mean the location of bytes others are insisting that those "heap" and "stack" terms shouldn't be used in c++, but instead prefer "automatic storage dur...
"heap" and "stack" are merely practical implementations of the general concepts specified by the C++ standard. The standard doesn't care where you store your objects, it cares about the lifetime of those objects, and so it talks about "automatic storage duration". But compilers typically use a stack as one of the tool...
6,525,030
6,527,548
Fragment shaders on ATI cards versus NVIDIA ones
I use this fragent shader (inspired from some tutorial found on the NVIDIA site some time ago). It basically compute bi-linear interpolation of a 2D texture. uniform sampler2D myTexture; uniform vec2 textureDimension; #define texel_size_x 1.0 / textureDimension[0] #define texel_size_y 1.0 / textureDimension[1] vec4 t...
As far as I can tell you're not quantiting the texture coordinate before sampling the texture. This could very well be the reason for those lines to appear because your input texture coordinate comes to lie on exactly the border between texels there. So you need to quantize uv to texel centers first. Keep in mind that ...
6,525,160
6,525,199
Using function stored in other local files of same directory
I've this following code in C++: //file0.cpp #include "file11.cpp" #include "file22.cpp" #include<iostream> #include<conio.h> using namespace std; extern void func1(int i); extern void func2(int i); int main(void) { int i; func1(i); func2(i); cout<<"the value of i is"<<" "<<i; getch()...
Well, you are typing #inluce and not #include on your source files When a compiler tells you something, it is usually important :P EDIT When reading compiler errors, start with the first one, not the last one, and fix it. Do not attempt to correct the second one because most of the time it is a side effect of the first...
6,525,245
6,525,707
Getting Clang to work on windows
I have followed the following step by step guide and I've managed, after a bit of fiddling, to get clang to compile using code:blocks and MinGW. Great, so now I could add the Clang module to eclipse (why have one IDE when you can have four) and start compiling. I can compile a simple program that doesn't use the stand...
There's some instructions for building clang on this page (hidden in the "Clang Development" part of the sidebar...). For MinGW you want the section called "On Unix-like Systems". The only tricky part is step 5 which tells you how to set up the paths for the C++ standard library. These need to be added into the code...
6,525,463
6,525,593
Stream syntax for reading from std::vector (or other sequence)?
Imagine I have a Variant class which can represent a variety of POD types, plus std::string, and I have a template method T get_value(const Variant&) that can extract the underlying types from it. Assume I have a vector of these, ie. std::vector<Variant> variants;, and I want to read several values from it with a conve...
Something like (untested) template <typename Iter> class Extractor { Iter cur; Iter const &end; public: Extractor(Iter const &begin, Iter const &end) : cur(begin), end(end) { } template <typename T> Extractor &operator>>(T &x) { if (cur == end) throw SomeException()...
6,525,564
9,733,761
Make a QMainWindow only horizontally-resizable - that is, width is resizable, but height is fixed
Can I make a QMainWindow with a grid layout resize only horizontally but not vertically? I want its vertical size to be the minimum needed to hold all the buttons/line edits.
I saw another way in one of the examples in a book called "C++ GUI Programming with Qt 4". They did it with setFixedHeight(sizeHint().height());
6,525,607
6,525,638
getline end of line?
I have an text file with binary values in n columns and y rows. I am using getline to extract every row of the binary values and assign them to vectors: I am using getline to extract every row of a file, where each row consists of a series of '0' or '1' separated by space, and assign them to a vector. std::vector< std:...
The obvious way would be something like: while (linestream >> temp >> sep) vi.push_back(temp); Though this may well fail for the last item, which may not be followed by a separator. You have a couple of choices to handle that properly. One would be the typical "loop and a half" idiom. Another would be a locale th...
6,525,650
6,525,665
Benefits of using reserve() in a vector - C++
What is the benefit of using reserve when dealing with vectors. When should I use them? Couldn't find a clear cut answer on this but I assume it is faster when you reserve in advance before using them. What say you people smarter than I?
It's useful if you have an idea how many elements the vector will ultimately hold - it can help the vector avoid repeatedly allocating memory (and having to move the data to the new memory). In general it's probably a potential optimization that you shouldn't need to worry about, but it's not harmful either (at worst y...
6,525,812
6,526,135
Read/write into a device in C++
How can I read/write to a device in C++? the device is in /dev/ttyPA1. I thought about fstream but I can't know if the device has output I can read without blocking the application. My goal is to create and application where you write something into the terminal and it gets sent into /dev/ttyPA1. If the device has some...
Use open(2), read(2), and write(2) to read from and write to the device (and don't forget to close(2) when you're done). You can also use the C stdio functions (fopen(3) and friends) or the C++ fstream classes, but if you do so, you almost definitely want to disable buffering (setvbuf(3) for stdio, or outFile.rdbuf()-...
6,526,225
6,526,290
struct keyword in function parameter, and const-correctness
I have an opaque type in my library defined as: typedef struct MyOpaqueType* MyType; // easier to type for client code I can't pass a pointer-to-const struct around using the typedef, so some functions look like: void UsePointerToConst ( const struct MyOpaqueType * ) instead of: void UserPointerToConst( const MyType...
Is the struct keyword in the parameter list only necessary in C? Yes. See Jens Gustedt's answer. Is there a better way to do this? Just typedef the struct, not the pointer. This is better because you only need one typedef instead of one for each of {MyOpaqueType, MyOpaqueType *, MyOpaqueType const *, MyOpaqueType ...
6,526,451
6,526,504
how to include git commit-number into a c++ executable?
i use git as a version tracker for my c++ project. sometimes i need to repeat a calculation and i would like to know which version of the program i used. what would be a good way to put a # of the commit into the main executable? in other words. i'd like the program to tell me the # of the current commit in an introdu...
Probably the easiest way to do this would be to add to your makefile a rule to generate a .c file with the current git commit ID: gitversion.c: .git/HEAD .git/index echo "const char *gitversion = \"$(shell git rev-parse HEAD)\";" > $@ Now simply add gitversion.c to your build process as normal. Make sure to remove...
6,526,500
6,526,604
C++ Name Mangling Library for Python
I'd like to mangle and demangle C++ function names in a Python program. Is there anything like that available? I searched for hours now, perhaps I'm lucky here...
You most likely don't want to be doing this in Python. As an aside you probably shouldn't be exporting mangled names from your DLLs since it makes it hard to use for anyone with a different compiler. If you have to use mangled names then just hard code them in your Python code. If you were going to do mangling in Pytho...
6,526,526
6,526,590
hash table with integer as keys
A hash function transform a Key into an integer hash value, is it possible to have an integer as a Key ? with boost::hash function it seems I get the same integer for the hash value...so I am a little bit in trouble
With integers that wouldn't be a problem, would it? Equal input values would produce the same hash-value, and distinct input values produce distinct hash-values. This is the perfect hash-function!
6,526,642
6,526,816
What is this (0x01000000) and how do I store it?
So I've created an XML file that will configure an application that has already been built. Up until now, it was hard-coded with constants that represented offset values in flash memory. enum { MAIN_FLASH_OFFSET = 0x01000000, LOADER_FLASH_OFFSET = 0x01e00000, MICROCODE_FLASH_OFFSET = 0x00060400, ...
Convert the string to a string stream and read the value into your integer. Using atoi(abc) would probably work also. #include <ios> #include <sstream> int i; string abc = "0x001"; stringstream convert ( abc ); convert>> std::hex >> i; The majority of that code came from a 10 second google search.
6,526,697
6,566,887
retrieve C++object member pointer using Python
I'm using box2d in my application. It has a class b2Body. It has a property void *userData and methods for it's accessing. In other words: we can store there some additional info about physic body. I want to store there some class object: MyClass *obj = new MyClass(); b2Body body; body.SetUserData(obj); Now I have to ...
You just have to do it C-style, i.e. pass the pointer to a function with returns the specific item you want. C++ objects aren't the same as python objects. Also Python doesn't even have the definition of your c++ object, so even if they looked the same in memory, python could use it as it doesn't know what its internal...
6,526,983
6,528,131
Free memory from a long vector
What I wanted to do is to release the memory used by a vector (say vector<vector<int>>) and I used the swap trick, i.e., v.swap(vector<vector<int>>()). However, what I observed that the swap trick work well for short vectors but NOT for long ones, for example I tried one vector of length 10,000,000, which took 1.4G in...
James, In silico, and Max all are correct with their remarks. You expect memory to be freed when you call batch.swap(tmp), since tmp is empty. I just ran your program on 64 bit Linux, compiled using gcc 4.6.0. When observing the memory consumption with top, it goes 2 GB -> 1.8 GB -> 1.8 GB. However, when adding a batch...
6,527,064
6,527,211
std::function<> and the Intel compiler version 11.1
I'm having trouble working with lambda functions in the Intel compiler, in particular, the following code won't compile: template<typename T> std::function<T (int)> make_func(T x) { return [=](int index) -> T { return x; }; } The error I get is error: namespace "std" has no member "function" The code com...
I get the same behavior with icc 11.1 on a system where gcc 4.5.2 is installed. g++'s header <functional> is protected with #ifdef __GXX_EXPERIMENTAL_CXX0X__ which is not defined when icc is used. I would consider switching to boost::function in this setup, which of course works with icc.
6,527,287
6,527,380
Can I delete an object owned by another with a callback from the object to be deleted?
I have one class (A) which knows when it should be deleted. I believe an object cannot directly delete itself (i.e., you can't call a destructor from inside it) so I've used a callback. Here is the pseudo-code of my current solution: class A { Owner* owner; // is set in constructor A(Owner* ow) : owner(ow) {} ...
An object cannot directly delete itself There is no particular reason why an object cannot delete itself, you have to be careful not to access any member after the object has been deleted, but there are circumstances where it makes sense. I have done that with some fire-and-forget objects encapsulating a thread or t...
6,527,391
6,527,903
Why isn't Darwin's strtod thread safe?
The following test always produces failures or bus errors for me on my Intel Mac Mini. Compiler: uname -a: Darwin vogon13 9.8.0 Darwin Kernel Version 9.8.0: Wed Jul 15 16:55:01 PDT 2009; root:xnu-1228.15.4~1/RELEASE_I386 i386 g++ -v: Target: i686-apple-darwin9 Configured with: /var/tmp/gcc/gcc-5493~1/src/configure --d...
strtod is not thread safe. It's never been stated in any specs that it was thread-safe. You should be using strtod_l, which takes a locale. In all likelehood there is a shared data structure that is being clobbered by it's use in the threaded code. locale_t c_locale = newlocale (LC_ALL_MASK, "C", 0); r = strtod_l(nptr,...
6,527,583
10,929,742
zlib's uncompress() strangely returning Z_BUF_ERROR
I'm writing Qt-based client application. It connects to remote server using QTcpSocket. Before sending any actual data it needs to send login info, which is zlib-compressed json. As far as I know from server sources, to make everything work I need to send X bytes of compressed data following 4 bytes with length of unco...
Turns out it was server-side bug. More details in bitcoin forum thread.
6,527,929
6,527,963
Template Specialization of Template method
OK I have: template<typename T> class Reader { class Input { template<typename C> void operator()(C& val) const { /* Do Some Work */ } }; }; Unfortunately the generic version of "Do Some Work" does not work for me. Nor it is easy to modify because it is in the mi...
Just write it like normal template<typename T> template<typename C> void Reader<T>::Input::operator()(C& val) const // LINE 13 { /* Do Some Work */ } Defining the generic version out of class doesn't help you with providing special versions of it though, or I do miss the goal of yours here.
6,527,945
6,527,980
Using third party classes in a C++ header file
Suppose there's a third party class named (including namespace) other::OtherClass. And this is the header file. class MyClass { public: ... private: other::OtherClass other_class_; ... } If this header file was shipped in production, would this be considered exposing the implementation to the client? O...
Vendors have to expose some amount of their library to clients through the header files they provide. That being said, there are techniques for hiding data and functions within an implementation. One of the more common techniques is to provide public proxy classes and factory functions, which expose only a mimimal amou...
6,528,081
6,528,216
How the compiler interprets preincrement/decrement and postincrement/decrement
When someone asks about the difference between post-increment/decrement and pre-increment/decrement, the response is usually that the prefix versions add one to the variable and return the new value of the variable whereas the postfix versions add one to the variable and return the old value. While messing around, I f...
In C++, the prefix increment/decrement expressions "return" lvalues and the postfix versions return rvalues. In C both forms return rvalues. However, be aware that the behavior is undefined if you try to writing to a variable more than once between two sequence points. So the distinction doesn't really matter anyway.
6,528,223
6,556,665
NSString weakly holding const char * of std::string
What's the safest way for a NSString to weakly contain a const char * belonging to a std::string? Both examples below work on a simple test, in logs, and as presented in a NSTableView, but I'm concerned about strange behavior down to road. It may be the extra null character of c_str() is simply ignored (because of the...
The documentation for initWithBytesNoCopy:length:... clearly states that the length will be the number of bytes used, so the null termination character will always be ignored. Hence the contents of the memory returned by data() and c_str() is equally suitable. With that in mind: The lifetime guarantees of the memory re...
6,528,461
6,528,485
Freeing abstract class pointers
In C++ I have a class A that has an abstract class pointer to allow for polymorphism contained in a class B, I have another pointer to an abstract class C that allocates a concrete instance of a child class of class B into that memory and I need to call a cleanup (see question below) function from class C to deallocate...
I'm using my crystal ball because it's hard to follow your question but you probably need virtual destructors.
6,528,499
6,528,545
Is it okay to forgo getters and setters for simple classes?
I'm making a very simple class to represent positions in 3D space. Currently, I'm just letting the user access and modify the individual X, Y and Z values directly. In other words, they're public member variables. template <typename NumericType = double> struct Position { NumericType X, Y, Z; // Constructors,...
The idea behind using getters and setters is to be able to perform other behavior than just setting a value. This practice is recommended because there are a multitude of things you might want to retrofit into your class. Common reasons to use a setter (there are probably more): Validation: not all values allowed by ...
6,528,538
6,529,444
Google Mock: object of abstract class type "xyz" is not allowed?
Using Visual Studio 2010 C++ with GMock. Trying to create a stub object for a third party class that is used by my classes but I'm getting the following error: Error: object of abstract class type "ThirdPartyClassFake " is not allowed. The third party class is defined like: namespace ThirdPartyNamespace { class __...
Specifically the problem was that although I implemented ThirdPartyClass's virtual methods in my mock object, I neglected to implement ThirdPartyBaseClass's virtual methods. This was causing the error. Once I added MOCK_METHOD calls for those methods the error went away.
6,528,624
6,716,542
link libmysql.lib with gcc or dev c++ in windows
i've been trying to link mysql with c++ below is the code for ref the file called sqlfunction.cpp has following code which helps connect mysql #include <mysql.h> #include "rlmodbusclient.h" #include "modbusdaemon.h" MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; bool Opendb(char *pc,char *user, char *pass, char *db) { ...
The general problem is that the libmysql.lib library is in the Microsoft-specific lib format, which mingw cannot link against. It seems that reimp.exe can convert such libraries and needs dlltool to do so. It probably couldn't find it because it is not in your PATH. Try set PATH=%PATH%;C:\MinGW\bin reimp.exe "C:\Progra...
6,528,628
6,528,649
Using C isdigit for error checking
While using the boolean check for the int num this loop doesn't work. The lines after it go unrecognized. Enter and integer like 60 and it just closes. Did I use isdigit wrong? int main() { int num; int loop = -1; while (loop ==-1) { cin >> num; int ctemp = (num-32) * 5 / 9; int...
When you call isdigit(num), the num must have the ASCII value of a character (0..255 or EOF). If it's defined as int num then cin >> num will put the integer value of the number in it, not the ASCII value of the letter. For example: int num; char c; cin >> num; // input is "0" cin >> c; // input is "0" then isdigit(nu...
6,528,678
6,528,736
A stack of function pointers: how to call the function?
I have a stack of function pointers (all of void type & with no parameters). I am having difficulty finding out how I then call/execute a function that is in the stack? If you look at the simple example below everthing compiles & works except for the last line typedef class InstructionScreen; typedef void (InstructionS...
You need an instance to call a member function. Try this: InstructionScreen screen; MemberFuncPtr step = instructionStep.top(); (screen.*step)(); To run a function in the stack from within another member function, you can use: MemberFuncPtr step = instructionStep.top(); (this->*step)();
6,528,992
6,529,005
Class Constructor arguments C++
I am creating a pair1 class for a x and y Cartesian coordinate system. x and y are doubles. I need to have 3 constructors. No arguments, defaults x and y to zero. One arguement assigns x and defaults y to zero. One arugeument defaults x to zero and assigns y. I'm not sure if I am setting up the class right. I get the ...
1) no arguments, defaults x and y to zero. That's easy 2) one arguement assigns x and defaults y to zero. 3) one arugeument defaults x to zero and assigns y. That's a problem. How do you know, when you only have one parameter, which of the two is meant to be called? That's why you get a compilation error. Ins...
6,529,003
6,529,058
.crt section? What does this warning mean?
I've got this warning recently (VC++ 2010) warning LNK4210: .CRT section exists; there may be unhandled static initializers or terminators I'm assuming this is the Critical Section. It's been a while since my Operating Systems course, so I can't really figure out what this means. If I remember right, the Critical Sec...
No, CRT = C Run Time. It is support library that any program needs to get the job done. Stuff like strcpy() lives there. You get a '.CRT section' in your .obj file when your code contains global variables that need to be initialized before your program starts running. The CRT takes care of that. That is nothing unu...
6,529,177
6,587,917
Capturing reference variable by copy in C++0x lambda
According to the answers and comments for this question, when a reference variable is captured by value, the lambda object should make a copy of the referenced object, not the reference itself. However, GCC doesn't seem to do this. Using the following test: #include <stddef.h> #include <iostream> using std::cout; us...
This has just been fixed in gcc-4.7 trunk and gcc-4.6 branch. These should be available in gcc-4.7.0 (a while from now - still in stage 1) and gcc-4.6.2 (alas 4.6.1 just came out.) But the intrepid could wait for the next snapshots or get a subversion copy. See audit trail for details.
6,529,338
6,529,572
Templates and headers
So do any of the future standards of c++ plan to resolve the issue of having to combine the declaration and implementation?
There's a very good reason why the template implementation needs to go into the header. A template is not code - it's only a template for the automatic generation of code. The code doesn't get created until you try to use it with the template parameters filled in. The compiler needs to have the full template body in or...
6,529,571
6,537,548
In Boost.Statechart, what's the difference between state and simple_state?
In implementing a state machine using Boost.Statechart, I came across a problem arising from attempting to access the outer context of a simple_state from its constructor. A comment in simple_state.hpp tells me: // This assert fails when an attempt is made to access an outer // context from a constructor of a ...
There are a number of other things that you can do from a state<> derived constructor that you cannot do from a simple_state<> derived constructor. There are a list in the documentation for the state class. I found posting events to be the big benefit of deriving from state<>. It's been a while since I used it, but I d...
6,529,653
6,529,693
inheritance makefile C++ undefined symbol first referenced
I am having a compilation problem. The following are the files and the inheritance. dateType.h, dateTypeImp.cpp: define and implement dateType class addressType.h, addressTypeImp.cpp: define and implement addressType class personType.h, personTypeImp.cpp: define and implement personType class extPersonType.h, extPerso...
The key part of the error message is: Undefined symbol extPersonType::.... Basically, the symbols for class extPersonType are not part your program. If you look at the makefile, you'll see that extPersonTypeImp.o: extPersonTypeImp.cpp g++ -c -Wall extPersonTypeImp.cpp is missing and that you need to add extPers...
6,529,874
6,529,885
No Template Parameter Needed in Return Type
template <typename Type> class Foo { Foo& Bar() { return *this; } }; Why does this compile? Shouldn't I have to specify the template parameter in the return type? Foo<Type>& Bar() { return *this; }
Foo<Type> is implied because the definition of Bar is within the definition of the class. If it were outside the class definition then you'd have to define it explicitly: template <typename Type> Foo<Type>& Foo<Type>::Bar() { return *this; }
6,529,917
6,529,973
new directory is not created
I am unable to create a directory using the following program : #include <direct.h> #include <iostream> using namespace std; int main() { if(_mkdir("d:\ff") == 0) { cout << "success"; } else { cout << "fail"; } } This program outputs fail .why is it so ? The compiler that i am using is microsoft visual c++ ...
You need to escape your back slash. See this http://msdn.microsoft.com/en-us/library/6aw8xdf2%28v=vs.80%29.aspx for list of escape sequences in C strings.
6,529,993
6,530,140
Is there any way is ther to create a ".O" file without main() function in ".C" file
In linux : C++ Is there any way is ther to create a ".O" file without main() function in ".C" file . iam using "cc -c file.c -o file.o " with sun compiler " gcc -Wall -c file.c " with g++ compiler may i know 1) what command we need to use for with EDG compiler and any other C++ compielrs in LINUX 2) In w...
For almost any compiler, -cshould produce a .o file by default. You can use the same syntax as with your sun compiler : -o is supported as well by gcc. This should work just fine: gcc -Wall -c file.c -o file.o Note that on windows, .ofiles are usually named .obj as a visual convention : it might be a good idea to st...
6,530,008
6,530,067
To compare two strings and remove the same characters from string 1 and print the string 2 using C++
I am a newbie in programing and stuck at a point where I have to compare the two strings using C++: string 1 and string 2 for the same characters and then delete those characters from string 1 and print the string 2. Looking forward for your help. My code goes like this: #include<string> #include<iostream> #include<con...
Compare each char in string2 with all chars of string1. If that char from string2 doesn't match any in string1 then append this char to a new string else continue without appending. Continue this for all chars in string2. Now assign the new string as string1. This uses extra o(n) space but is simpler.
6,530,111
6,530,144
expected unqualified id before '\0'
I tried following things but I am getting the error typedef '\0' DEFAULT_VALUE; Error: expected unqalified id before '\0'` typedef NULL DEFAULT_VALUE; Error: expected unqalified id before __null what I am doing wrong here?
The keyword typedef defines synonym for existing type. Neither \0 nor NULL are type. May be you want something as follows: #define DEFAULT_VALUE NULL
6,530,120
6,530,180
creating the file with the same name as input
cout << "Enter your full name"; char* name ; cin >> name; if( _mkdir("c:\\names") == 0 ) { cout << "directory successfully created"; } else { cout << "there was a problem creating a directory"; } Now i want to create a file ( a .txt file ) in the directory names with the same name as the name of...
Use std::string instead of char*. As it is your code has Undefined Behavior. Use std::getline instead of >>. With >> only the first whitespace-separated "word" is input. Then, compose the full path in a std::string. The standard string class supports concatenation, so this should be easy. Say, if that string is path, s...
6,530,272
6,531,884
QuaZip removing files inside archive
Is it possible to remove files inside zip archive with quazip ?
Unfortunately there is no function to do that. As a work-around you can open the zip archive and then use RAW reading and writing to copy the files you want not to be deleted and put them in a new zip archive. Then delete the old archive. This is not a very clean solution... Oh and it's not efficient either. For very h...
6,530,355
6,530,429
Is memory allocation a system call?
Is memory allocation a system call? For example, malloc and new. Is the heap shared by different processes and managed by the OS. What about private heap? If memory allocation in the heap is managed by the OS, how expensive is this? I would also like to have some link to places where I can read more about this topic.
In general, malloc and new do not perform a system call at each invocation. However, they use a lower-level mechanism to allocate large pages of memory. On Windows, the lower mechanism is VirtualAlloc(). I believe on POSIX systems, this is somewhat equivalent to mmap(). Both of these perform a system call to alloca...
6,530,397
6,531,776
ofstream doesn't work on Windows 7 hidden file
I realize that ofstream doesn't work on Windows 7 hidden file. Here is the quick test code. #include <fstream> #include <iostream> #include <tchar.h> #include <windows.h> int main() { { std::ifstream file2(_T("c:\\a.txt")); if (file2.is_open()) { std::cout << "ifstream open" << std:...
Yes. As noted in the underlying CreateFile documentation, " If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM attribute." Or more readable: CreateFile fails if both CREAT...
6,530,476
6,530,502
problem with const reference return and STL vectors
I am having issues with the following snippet of code string const& symbol::at(int index) const { assert(index<symbol_data.vector::size()); return symbol_data.vector::at(index); } Here, symbol_data is a private member of the class and is a vector ::at is a member function in the symbol class that I hav...
Your code as I'm writing this: string const& symbol::at(int index) const { assert(index<symbol_data.vector::size()); return symbol_data.vector::at(index); } Instead of symbol_data.vector:: write just symbol_data.. Cheers & hth.,
6,530,565
6,549,098
Getting another process command line in Windows
I am trying to get another process' command-line parameters (on WinXP 32bit). I do the following: hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE, FALSE, ProcList.proc_id_as_numbers[i]); BytesNeeded = sizeof(PROCESS_BASIC_INFORMATION); ZwQueryInformationProcess(hProcess, ProcessB...
Duplicate of How to query a running process for it's parameters list? (windows, C++) , so I'll just copy my answer from there over here: You can't reliably get that information. There are various tricks to try and retrieve it, but there's no guarantee that the target process hasn't already mangled that section of memor...
6,530,612
6,530,636
C/C++ character literals on ASCII and EBCDIC systems
After reading the PNG specification I was a little bit surprised. I've read character literals should be hardcoded with binary values like 0x41 not in (the programmer friendly) 'A'. The problem seems to be that character literals are differently encoded during compilation on different systems with different underlying ...
The programmer friendly version is the only way to be sure that the character constant 'A' is properly encoded for the target environment. Using 0x41 guarantees that the value is 65 only. EBCDIC systems are thankfully rare, and getting rarer, so this distinction is fairly academic in some ways. However, understandabl...
6,530,747
6,530,886
Compile time comparison of template parameter
I have a requirement that, I should use a specific class if an integer passed as one of the template parameter is greater than a certain value. Otherwise, I should get a compile time error... It is something like the following: enum Time { Day, Week, Month }; template<Time t, int length> class Timer { } Now, I have ...
Pass the result of length >= 8 as a bool template argument to helper template. Provide specialization for true only. Having said that, this sounds like homework, so I'll leave the coding to you. Cheers & hth.
6,530,949
7,897,963
Is it worth experimenting with different heap allocators on Linux for multi core servers for nginx or haproxy
I am doing some experiments to find out the ceiling of my requests per second rate of haproxy and nginx on RHEL or Centos. Part of my setup in nginx uses embedded LUA in the form of LuaJIT. My question is this: Does anybody have any experience or advice about the usefulness of doing some testing of these apps after bu...
Experiments at a previous employer showed that the standard Linux and Solaris malloc/free implementations were not particularly efficient in high-concurrency multicore environments. We realized significant performance improvements by creating a custom allocator. I think it is definitely worthwhile to do experiments wit...
6,531,073
6,531,134
Is there anything wrong with the program
#include <iostream> #include <cstring> using namespace std; int main() { char sor[6] = "hello"; char des[6] = "hello"; strcat(des,sor); cout << des; } When i start the debugging of the program it gives the following error along with the console output (behind it) : why is it so ? If there is anything wrong wi...
While increasing the size of the string char-array would help you in this situation, let me propose to actually use C++ features; don't code C when you want to code C++: #include <iostream> #include <string> using namespace std; int main() { string sor = "hello"; string des = "hello"; des += sor; cout << des; }...
6,531,185
6,534,856
Qt or C++ checking for NULL condition
I am writing an application with a submit button but I want to check if the textfield has been filled if not do not submit. Not quite sure how the code should go. My code currently looks like if(flightNumber == NULL) { flightNumbertext.text.color = 'red'; } I am designing this for a Qt Quick application written in ...
After a bit of playing, I think this will work for you if (flightNumber.text.trim().length == 0) { flightNumbertext.text.color = 'red'; } The function trim() is like QString::trimmed(). It removes both leading and trailing spaces from the string.
6,531,243
6,531,327
Why does CPU usage increase when my application is minimized?
I'm programming a calculator. When the window is maximized, the CPU usage is about 12%, but when it is minimized, the CPU usage rises to about 50%. Why is this happening and how can I prevent this? Here is the piece of code that I think is causing the problem. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wPara...
My guess is that your main loop runs without any delays if active is false. The thread infinitely spins through that loop and keeps one of your two processors cores busy (that's why you see 50% CPU load). If active is true, the swap operation waits for the next vsync and delays your loop until your next screen refresh ...
6,531,483
6,531,563
Reverse engineering your own code c++
I have a compiled program which I want to know if a certain line exist in it. Is there a way, using my source code, I could determine that? Tony commented on my message so I'll add some info: I'm using the g++ compiler. I'm compiling the code on Linux(Scientific)/Unix machine I only use standard library (nothing down...
objdump is a utility that can be used as a disassembler to view executable in assembly form. Use this command to disassemble a binary, objdump -Dslx file Important to note though that disassemblers make use of the symbolic debugging information present in object files(ELF), So that information should be present in yo...
6,531,486
6,580,767
Program making use of FindWindowEx stops working on Server 2003, why?
I have a simple program that uses FindWindowEx & strncmp() inside a callback passed to EnumChildWindows, to find a dialog created by a third party application, and press a button. This code works fine on my Windows 7 Ultimate PC, but if I run it on Windows Server 2003 it no longer works. I have used Spy++ and the windo...
Solved. @sebf: Its 2011; support Unicode, idiot!
6,531,571
6,555,230
How to get a control custom resource data
You can get common controls custom resource data ( see controlData section: http://msdn.microsoft.com/en-us/library/aa380902(v=VS.85).aspx ) by handling WM_CREATE and accesing lpCreateParams member of CREATESTRUCT. Is there any way to access the data after a control was created?
Looks like I found the answer. We can use FindResource->LoadResource->LockResource functions to get pointer to the dialog resource data. The pointer returned by LockResource will point to DLGTEMPLATEEX structure. This will allow to iterate through dialog controls to find the needed dialog item ( DLGITEMTEMPLATEEX ) and...
6,531,575
6,531,675
In what cases do global operators get hidden in C++?
I'm rearranging the namespaces of code in relatively large C++ project. One difficulty I keep running into is that global operator overloads become inaccessible sometimes. Things like stream operators (<< and >>) and equality operators (==), Sometimes the only changes that cause this is moving from say "namespaceA" to ...
You're probably forgetting how name lookup works. When you're using operator<<, it's almost always as a << b, not ::parent::namespaceA::operator<<(a,b). That unqualified use means that it's looked up via Argument Dependent Lookup (aka Koenig Lookup). So, operators from the global namespace will be hidden by operators f...
6,531,658
6,531,717
Qt application hanging up with 100% CPU
I have a simple Qt program running on Windows XP - its just a data logging program. It reads any data sent to it on the serial port and then it pushes this to the GUI and logs it to a text file. The thing is, if I run the program for an hour (roughly, sometimes more) it will hang up on me. The GUI locks out and the pr...
Run the application until it freezes and then attach a debugger. Look through the threads and check where each one of them is. This should give some clues on what's going on. For threads that are stopped within framework code an investigation of the call stack should show if your code is involved. Make sure that you do...
6,531,696
6,531,820
Using streams to initialise c++ objects
I am reading Game Coding Complete and it suggests to have two init() functions, one being your usual init() call, the other taking a stream. It doesn't go into alot of detail about it though, and I am left a little confused. class AnimatinPath { public: AnimationPath(); Initialize(std::vector<AnimationPathPoints>...
'Stream' is actually not important. Second init function with a stream parameter means object serialization. Take a look at this SO post: How do you serialize an object in C++? You could google for 'object serialization' for more information.
6,531,700
6,531,758
When will a C++11 compiler make RVO and NRVO outperform move semantics and const reference binding?
Consider the case when "whole" objects with move semantics enabled are returned from functions, as with std::basic_string<>: std::wstring build_report() const { std::wstring report; ... return report; } Can I then realistically be expected to make the "best" choice whether to use the returned string with ...
std::move(build_report()) is wholly unnecessary: build_report() is already an rvalue expression (it is a call of a function that returns an object by value), so the std::wstring move constructor will be used if it has one (it does). Plus, when you return a local variable, it gets moved if it is of a type that has a mo...
6,531,774
6,531,835
How to compare objects of POD types
This example : #include <iostream> #include <cstring> struct A { int a; bool b; }; bool foo( const A a1, const A a2 ) { return ( 0 == std::memcmp( &a1, &a2, sizeof( A ) ) ); } int main() { A a1 = A(); a1.a = 5;a1.b = true; A a2 = A(); a2.a = 5;a2.b = true; std::cout<<std::boolalpha ...
The first one is not working because of padding in the struct. The padding is having different bit patterns for both objects. If you use memset to set all the bits in the object before using it, then it will work: A a1; std::memset(&a1, 0, sizeof(A)); a1.a = 5;a1.b = true; A a2; std::memset(&a2, 0, sizeof(A)); a2.a = ...
6,531,845
6,531,935
Is it possible to convert my loop into parallel_for fnc invocation?
I'm having a for loop which I would like to convert into parallel_for fnc invocation. My code meets all the criteria (described in Parallel_Programming_with_Microsoft_Visual_C_plus_plus,p.7) for this conversion to be successfull, yet I find it difficult to implement. Here is my example: //"Oridinary" for //numbers_from...
MSDN says that there is a step parameter. Use it.
6,531,906
6,532,138
the output is not what i typed.It is --> (畳慨汩朠灵慴찀쳌쳌쳌)
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { char x[20]; cout << "enter something\n"; cin.getline(x,20); ofstream o("d:/tester.txt"); //o.write( (char*)&x , sizeof(x) ); for(int i = 0 ; i<=19 ; i++ ) { o.put(x[i]); } } I am not getting that output in the file the one whi...
Your program involves undefined behavior. The x array is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user. I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears tha...
6,532,064
6,532,144
Redirect stdout to an edit control (Win32). Mark II
I've seen a question exactly like this already exists: Redirect stdout to an edit control (Win32) However, the solution given requires the programmer to implement a my_printf function that does a {printf; read from pipe to edit control}. I cannot do that because my printf's are in a external library. Ideally, I'm think...
As far as I'm aware you can't get 'notifications' with a pipe. If you do want to do that maybe you should use WM_COPYDATA instead which would also provide a simpler solution. You will get a message when text is posted to your window which you can then append to the edit control.
6,532,074
6,532,246
Recursive generic function used as a predicate, compilation failure
I am writing a function to compare the contents of two lists. The order of the elements don't matter, so I sort them before I compare. The lists can be of normal types list<int>, but also be lists of lists list<list<int> >. Here is a complete stripped down example: #include <list> template <typename T> bool lessThanIn...
Wrap the function in std::ptr_fun with explicit type arguments: lhs.sort(std::ptr_fun<T, T>(lessThanInAnyOrder<T>));
6,532,173
6,532,216
"CopyConstructible" requirement for C++ stl container element
Regarding to the requirement for C++ stl container element, the standard says: the element type should be CopyConstructible, and there is a table for CopyConstructible requirements. Also by various books (Josuttis, etc.), the generated copy should be "equivalent to" the source. I think I need some clarity here. What i...
Deep or shallow copy both work. For instance, shared_ptr always does a shallow copy (with some extra reference counting stuff), and you can use them in containers just fine. It depends on the semantics of copy-operation. Equivalent means your program should not depend on whether it works with the original or with the c...
6,532,400
6,532,492
Linking files in g++
Recently I have tried to compile a program in g++ (on Ubuntu). Usually i use Dev-C++ (on Windows) and it works fine there as long as I make a project and put all the necessary files in there. The error that occurs when compiling the program is: $filename.cpp: undefined reference to '[Class]::[Class Member Function]' ...
You probably tried to either compile and link instead of just compiling source files or somehow forgot something. Variation one (everything in one line; recompiles everything all the time): g++ -o myexecutable first.cpp second.cpp third.cpp [other dependencies, e.g. -Lboost, -LGL, -LSDL, etc.] Variation two (step by s...
6,532,410
6,534,935
Safe Array - Set count zero
will the following code work, if the safe array count to be returned is zero? Should I do anything else? HRESULT GetAlarms(FAULT_TYPE eAlarmType, long alarmLevel, VARIANT* pvarAlamLst) { pvarAlamLst->vt = VT_ARRAY |VT_VARIANT; pvarAlamLst->parray = NULL; return S_OK; }
pArray is a LPSAFEARRAY and should be treated as such. Therefore you need the SAFEARRAY functions (macros). SAFEARRAY doesn't have a concept of "count" as such, it's a variable-dimension array. A one-dimensional SAFEARRAY can have size 0, but a 2D SAFEARRAY would have size 0x0 (or 1x0). In particular, MSDN documents VT...
6,532,767
6,532,815
Does pthread_cond_wait and pthread_mutex_unlock conflict?
I am implementing manual reset event using pthread in Linux which is similar to WaitForSingleEvent in Windows. I found this post pthread-like windows manual-reset event and follow it, however there a thing that confuse me: void mrevent_wait(struct mrevent *ev) { pthread_mutex_lock(&ev->mutex); while (!ev->tr...
The standard says: Upon successful return, the mutex has been locked and is owned by the calling thread. Which means that when returning, pthread_cond_wait atomically locks the associated mutex. The workflow is like this: You lock a mutex pthread_cond_wait atomically blocks and unlocks the mutex (so other threa...
6,532,812
6,532,842
various forms of getline()
I read that this form of getline: getline(char *buf, streamsize num) But I recently came across this getline function: getline(cin,x); where x is a string. How is this ?
The first one is a member function of std::istream. And the second one is a free standalone function. You've overloaded functions for both. http://www.cplusplus.com/reference/iostream/istream/getline/ http://www.cplusplus.com/reference/string/getline/
6,532,916
6,533,404
How to validate a float number against format specifier?
I want to validate a user input against format specifier.For example format specifiers %4.5f , %4f , %10.5f, etc., If i specify %5.2f as format specifier I should able to validate user input whether its satisfies the given format %5.2f or not? Note : I am using C++ in windows environment.
You will want to do string matching against a regular expression. The expression should be: [0-9]{n}\.[0-9]{m} Here n and m are the number of digits to want. You can build a regular expression from a string, so just make the pattern string from your parameters and then construct the regex; it's all in <regex> on C++0x...
6,532,923
6,533,372
How to marshal a list in C#
I have to send a list from C# to C++.The C# list is List<string>MyList and the C++ code accepts it as list<wstring>cppList.How to use marshalas for this. Thanks
It is always wiser not to use complex type marshaling between native code and managed code. In case of List, these type totally differ from each other as they have different memory layout for each item. So the best way is to write a utility function in a native dll that accepts array of string(char*) and manually build...
6,533,015
6,533,084
How to disable highlight brackets in GVim
I am trying to highlight my own class name and function name in C++ via GVim. I read and followed the link from stackoverflow. Please also check out the result link I copied the following settting in my cpp.vim where is under syntax directory. " Highlight Class and Function names syn match cCustomParen "(" cont...
You should edit your .vimrc file. Simply add this line to the file: let g:loaded_matchparen= 1
6,533,041
6,533,085
what is wrong with this program?
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { string x; getline(cin,x); ofstream o("f:/demo.txt"); o.write( (char*)&x , sizeof(x) ); } I get the unexpected output.I don't get what i write in a string function. Why is this ? Please explain . Like when i wri...
You are treating an std::string like something that it is not. It's a complex object that, somewhere in its internals, stores characters for you. There is no reason to assume that a character array is at the start of the object (&x), and the sizeof the object has no relation to how many characters it may indirectly hol...
6,533,098
6,535,113
How to determine what compiler does with a metaprogram? (for boost.proto)
How do I determine what my compiler (g++) is doing with template code? I am using boost.proto (an expression-template library) to evaluate some maths expressions at compile time. The code evaluates the expressions correctly, but I would like to see whether the compiler has expanded out the expression to the equivalent...
There are several ways to see a C++ code after the templates instantiation pass: Use gcc -fdump-tree-original (or even -fdump-tree-all to see more passes) Use Elsa C++ parser: http://scottmcpeak.com/elkhound/sources/elsa/ Use Clang and an LLVM C backend - the latter will give the most unreadable code, but it is still ...
6,533,233
6,533,474
Default argument of type float = gibberish
I have some trouble using a default argument of type float: #include <wchar.h> #include <iostream> template<typename T> void fun(T t = 1e-05); template<typename T> inline void fun(T t) { std::cout << t << std::endl; } int wmain(int argc, wchar_t* argv[]) { fun<float>(); _getwch(); return 0; } It pr...
Looks to be an issue with a default template argument and conversion between double and float. The issue doesn't occur if you aren't using templates. Stick an "f" at the end of that default template argument such that it treats the value as a "float" instead of a double. That seems to fix it. template<typename T> void...
6,533,329
6,535,587
What is the use of "morph into" in qt?
In qt gui editor, any gui component can be morphed into certain type of other gui components. But realistically speaking what is the practical use of this option? can it be done dynamically? if yes then what is the advantage of doing that?
The practical use is to quickly convert widgets into other, similar widgets. Let's say you have a group box filled with some widgets and you realize that you rather want a tab widget. Without morphing you would need to create a tab widget select all widgets in the group box copy or move them to the first page of your ...
6,533,380
6,533,534
Use a Qt library from a C application
Is there a way to write a qt library such that I can then use it (statically linked is fine) in a C application? My C code is huge, old and will not convert to C++ without an inordinate amount of work. I say this as other similar questions seem to answer "just make your C code a Qt app". That's not an option. I hope I ...
You can put as much Qt in a library as you wish, including full UI capability. The rub is that since you want to access it from C code, you must provide your own access functions and your C functionality will be constrained to whatever level of access you provide. You can even pass Qt object pointers between C and C++ ...
6,533,487
14,155,331
Echo Suppression library?
I'm looking for an echo suppression library to put into a VoIP application (using pjsip). Open Source or commercial. The application is written in C++ (Windows, Mac and soon to come Linux). I have tried several echo cancelers (both free and commercial), without good results. So I'm looking for something simpler that wi...
After months of research, we gave up both common open source and commercial AEC implementations. Then we moved our media stack to Google's Voice Engine (part of Chromes WebRTC code base), and guess what - AEC works very well most of the time (we still have some problems with Apple/OS X when using external speakers).
6,533,570
6,538,230
Implementation of Non Local Means Noise reduction algorithm in image processing
I am working over implementation of Non Local Means noise reduction algorithm in C++ . There are papers on this algorithm (such as this paper), but they are also not very clear on it. I know, it is using the weighted mean but I don't know what is the use of research window here and how is it related to comparison win...
From the paper you refer to, when determining the result value for a given pixel p, all the other pixels of the image will be weighted and summed according to the similarity between their neighborhoods and the neighborhood of the pixel p. But that is computationally very expensive. So the authors restrict the number of...
6,533,989
6,535,731
Would you recommend C++ Coding Standard by Todd Hoff?
Hallo at the moment I am looking for a good C++ coding standards, which I can stick with. In internet I could find a lot of coding standards. Some rules are common in most of them. But there are also differences. I found C++ Coding Standard by Todd Hoff (http://www.maultech.com/chrislott/resources/cstyle/CppCodingSta...
Regarding Hoff: Horrendous naming conventions The naming conventions are very non-standard. In most places I have worked and most conventions I have looked at, member functions and member data follow the same rule: All lower case, words separated by underscores. Those InitialCaps identifiers are hard to read, even for ...
6,534,041
6,536,204
How to check whether operator== exists?
I am trying to create an example, which would check the existence of the operator== (member or, non-member function). To check whether a class has a member operator== is easy, but how to check whether it has a non-member operator==? This is what I have to far : #include <iostream> struct A { int a; #if 0 ...
C++03 The following trick works and it can be used for all such operators: namespace CHECK { class No { bool b[2]; }; template<typename T, typename Arg> No operator== (const T&, const Arg&); bool Check (...); No& Check (const No&); template <typename T, typename Arg = T> struct EqualExists { enum { ...
6,534,196
6,534,342
Unable to make program calculate correctly
I am trying to make a program which does a very basic calculation, but for some reason i can't get the code right. It is supposed to calculate the miles per gallon for one trip. You can then add this info multiple times (for different trips) and for each time it should calculate the total miles per gallon (i.e. the ave...
You can not calculate average of averages the way you do it. In your code you are dividing by the counter EACH iteration, while you should divide it only at the end. Best way to do what you need is something like this: ... double totalMiles = 0; double totalGallons = 0; ... while (x != -1) { milePerRe = x/y; ...
6,534,460
6,534,537
What happens when you don't follow the practice of argv and argc
Possible Duplicates: main(int argc, char *argv[]) Main's Signature in C++ If i write: int main(int argc, char** argv) i get proper commandline input. What would happen if i wrote say, int main(int foo, double fooDouble, fooType FooVar) Is this OS-dependent or does it depend on the compiler?
Given that it does compile, it will still only be called with the argc and argv arguments. So your fooDouble will get the pointer value of argv, and FooVar will get whatever value is in that register/stack space used for that argument position (which may not have been initialized by the callee, so it may hold any unde...
6,534,605
6,535,212
Learning Intel's TBB
Could anyone recommend good book about Intel's threading library and how to use it?
The O'Reilly book indeed does have poor reviews. I haven't come across any other books, but what will really help you with learning TBB is: To go through the reference manual one concept at a time and make tiny code samples of your own. The TBB samples are HUGE, and weren't very helpful when I tried learning it. I made...
6,535,182
6,535,254
troubleshooting _mkdir failure
#include <iostream> #include <direct.h> using namespace std; int main() { if( _mkdir("d:\\a\\b") == 0 ){ cout << "success"; } else if ( _mkdir("d:\\a") == EEXIST ) { cout << "Directory was not created because dirname is the name of an existing file, directory, or device."; } else if ( _mkd...
The double slashes are correct. Check the error number to find out why it is failing: Each of these functions returns the value 0 if the new directory was created. On an error the function returns –1 and sets errno as follows: EEXIST - Directory was not created because dirname is the name of an existing file, direct...
6,535,258
6,536,536
C++ exceptions and signal handlers
I am reading The Design and Evolution of C++, by Bjarne Stroustrup. Regarding exeception handling and asynchronous signals it is mentioned as below: Can exceptions be used to handle things like signals? Almost certainly not in most C environments. The trouble is that C uses functions like malloc that are not re-entran...
In my opinion that part doesn't really make much sense with current C++. In C++ there is no way to use an exception as a signal because signals are meant to be executing an handler and then (possibly) continue execution. C++ exceptions however don't work this way. Once you get to the exception handler the stack has bee...
6,535,284
6,535,378
Linux pipe : Capturing realtime output of ping via popen
Linux/C/pipes: How can I capture the output of ping command using popen(Or similar system calls). Currently popen will wait until ping is finished. Then output will be dumped together. Pseudo code: fp= popen("ping x.x.x.x", "r"); while(!feof(pFp)) { if(fgets(fp ...) // <==currently the code blocks here until ping f...
It's not waiting until ping is finished. Rather, ping is waiting until the stdout buffer fills up before writing anything. The only ways to avoid this involve pseudo-ttys. Either you should abandon popen and write the code to run the ping child process yourself and use a pseudo-tty to communicate (this is easy with the...
6,535,565
6,535,597
Non-terminating while loop
I was just wondering something. I have the following code: #include <iostream> using namespace std; int main() { int number, largest, counter = 1; while (counter <= 10) { cout << "Enter a number: "; cin >> number; if (counter = 1) { largest = number; ...
if (counter = 1) this should be if (counter == 1) otherwise, you're going to reset your counter to 1 each iteration.
6,536,164
6,536,443
Implicit internal linkage not the same as explicit internal linkage ("static")?
Today I encountered a pecularity which, although probably not really important, nevertheless puzzles me. Maybe I'm just not understanding C++ correctly, too. Some arrays inside a source file point to string literals, like so: const char* a[] = { "a", "b", "c" }; const char* b[] = { "d", "e"}; const char* c[] = { "f", "...
Your arrays are not declared const, hence they aren't implicitly internal linkage either. What you have is non-const arrays of pointers-to-const. That said, I don't know why this affects whether the strings end up in .rdata or .data.
6,536,251
6,536,360
Manifest of a native C++ application?
I can't claim that I am an expert in what a .Net Assembly Manifest is, but I think I have a more or less consistent understanding of it. However the fact that when compiling my native C++ application MSVC is Embedding Manifest... doesn't fit in my understanding. What do manifests have to do with native C++ applications...
Manifests are additional metadata attached to the executable (either embedded into resources, or distributed standalone as .manifest files) — they're used for things like side-by-side assemblies, or UAC compatibility settings. Take a look at manifest file reference on MSDN.