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
3,181,040
3,181,111
Dynamic memory and constructor exceptions
Early today I discovered function try-catch blocks (from here in fact) and then went on a bit of a research spree - apparently they're main use is it catch exceptions throw in by a constructor initialiser list. Anyway, this sent me thinking about failing constructors and I've got to a stage where I just need a little c...
Try/catch function blocks are frowned upon, in the same way as goto --there might be some corner case where they make sense, but they are better avoided: when an object fails to be constructed, best thing you can do is fail and fail fast. On you specific questions, when an exception is thrown in a constructor, all full...
3,181,081
3,181,093
file reading: feof() for binary files
I am reading a binary file. and when it reaches the end. it seems it is terminated by feof() function. is it because there is no EOF character for binary files? if so how can i solve it. currently my code is using a while loop while (!feof(f)) when it reaches the end of file at position 5526900. it doesn't stop. it ju...
You should not use feof() to loop on - instead, use the return value of fread() - loop until it returns zero. This is easy to see if you consider reading an empty file - feof() returns the EOF status AFTER a read operation, so it will always try to read bogus data if used as a loop control. I don't know why so many peo...
3,181,156
3,259,932
Can a PyQt program consume a DBus interface that exposes custom C++ types (marhsalled via Qt's MetaType system)? If so, how?
I have a Qt/C++ application that exposes some custom C++ classes via DBus methods (by registering them as MetaTypes, and using annotations in the xml), and I want my PyQt program to consume these methods. The problem I see is that the exposed types are C++ classes, not python, so how can I make python aware of these cl...
There is no such thing as 'C++ classes' in D-Bus, it is language-agnostic. All methods, functions, etc. have type signatures expressible in basic D-Bus types (see the spec). Just call those classes, and it should work.
3,181,211
3,181,240
Prefix/Postfix increment operators
I'm wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++ operator for an object. Let's suppose we have the following class X: class X{ private: int i; public: X(){i=0;} X& operator ++ (){ ++i; return *this; } /...
This is a correct implementation. It is typical that a postfix operator will be worse on performance because you have to create another copy before doing the increment (and this is why I've gotten in the habit of always using prefix unless I need something else). With return-by-reference, you're returning an l-value re...
3,181,367
3,181,389
What is an easy way to test whether any process of a given id is presently running on Linux?
In C++, I have a resource that is tied to a pid. Sometimes the process associated with that pid exits abnormally and leaks the resource. Therefore, I'm thinking of putting the pid in the file that records the resource as being in use. Then when I go to get a resource, if I see an item as registered as being in use, I...
To check for existence of process with a given id, use kill(pid,0) (I assume you are on POSIX system). See man 2 kill for details. Also, you can use waitpid call to be notified when the process finishes.
3,181,641
3,181,660
How can I delete a file upon its close in C++ on Linux?
I wish for a file to be deleted from disk only when it is closed. Up until that point, other processes should be able to see the file on disk and read its contents, but eventually after the close of the file, it should be deleted from disk and no longer visible on disk to other processes.
Open the file, then delete it while it's open. Other processes will be able to use the file, but as soon as all handles to file are closed, it will be deleted. Edit: based on the comments WilliamKF added later, this won't accomplish what he wants -- it'll keep the file itself around until all handles to it are closed, ...
3,181,646
3,181,676
Accessibility: Managed vs Unmanaged code
I'm about to begin working on a Accessibility project for Windows (targeting XP through 7) and would like some advice on the pros an cons of using managed code vs unmanaged code. Basically the software will need to be able to read text from open windows, access menus, and other common functions programs like a JAWS or ...
Definitely managed code Even if you run into situations where you're comfortable using COM/unmanaged you can use COM/unmanaged for those modules. .NET offers seamless interop between managed and unmanaged code. with .NET 4.0 and C# 4.0 interop is even better .. And above all else make sure you design a loosely coup...
3,181,766
3,181,803
How far to go with a strongly typed language?
Let's say I am writing an API, and one of my functions take a parameter that represents a channel, and will only ever be between the values 0 and 15. I could write it like this: void Func(unsigned char channel) { if(channel < 0 || channel > 15) { // throw some exception } // do something } Or do I take ad...
If you wanted this simpler approach generalize it so you can get more use out of it, instead of tailor it to a specific thing. Then the question is not "should I make a entire new class for this specific thing?" but "should I use my utilities?"; the latter is always yes. And utilities are always helpful. So make someth...
3,181,910
3,220,369
Is it possible to use custom c++ classes with overloaded operators in QtScript?
Does anyone know if it is possible to have a C++ class with overloaded operators such as +,-,* and declare it somehow (this is where the magic happens) to a QtScriptEngine such that js-expressions like "a+b" are evaluated as they would be on the C++ side?
It seems to be impossible. At least that is what I received as an answer in the #qt-labs IRC. However, I think I found a viable alternative: ChaiScript. It embeds itself wonderfully into C++, plays well with Qt and allows for the overloading of operators, and even better the direct use of any(?) C++ data type.
3,182,224
3,183,101
C++ objects serialization for Linux
I'm doing a program that needs send and receive data over the network. I never dealt with object serialization. I readed about some recommendations about Boost and Google Protocol Buffers. For use in Linux which is the best? If you know some other I will appreciate your help. Thanks.
I've used Boost.Serialization to serialize objects and transmit them over a socket. It's a very flexible library, objects can be serialized intrusively if you have access to them class Foo { public: template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & _foo; ...
3,182,299
3,182,336
How do event listeners work?
Do they repeatedly check for the condition and execute if the condition is met. Ex, how the OS knows exactly when a USB device is plugged in, or how MSN knows exactly when you get an email. How does this work? Thanks
At the low level, the OS kernel "knows" when something happens, because the device in question sends the CPU a hardware interrupt. So when, say a network packet arrives, the network controller sends an interrupt, and the OS kernel responds as appropriate. At the program level, it works quite differently - most applicat...
3,182,316
3,182,333
what is the proper way to delete a pointer in an array?
//the setup tiles = new Tile **[num_bands]; for( int i = 0 ; i < num_bands ; i++ ) tiles[i] = new Tile *[num_spokes]; for(int i=0; i < num_bands; i++){ for(int ii=0; ii < num_spokes; ii++){ tiles[i][ii] = 0; } } //the problem delete tiles[1][1]; When I delete a tile, tiles[1][1] still holds an a...
delete isn't supposed to null the pointer; it's your own responsibility to do that if you want to. Basically, delete just means "I no longer need the memory at this address, so you can use it for something else." - it doesn't say anything about what value pointers that pointed to the freed address will have.
3,182,443
3,182,833
More on the mediator pattern and OO design
So, I've come back to ask, once more, a patterns-related question. This may be too generic to answer, but my problem is this (I am programming and applying concepts that I learn as I go along): I have several structures within structures (note, I'm using the word structure in the general sense, not in the strict C str...
I don't think you've provided enough info above to be able to make an informed decision as to which is best. From looking at your other questions it seems that most of the communication occurs between components within an Army. You don't mention much occurring between one Army and another. In which case it would seem t...
3,182,733
3,182,787
What is the pointer-to-pointer technique for the simpler traversal of linked lists?
Ten years ago, I was shown a technique for traversing a linked list: instead of using a single pointer, you used a double pointer (pointer-to-pointer). The technique yielded smaller, more elegant code by eliminating the need to check for certain boundary/edge cases. Does anyone know what this technique actually is?
I think you mean double pointer as in "pointer to a pointer" which is very efficient for inserting at the end of a singly linked list or a tree structure. The idea is that you don't need a special case or a "trailing pointer" to follow your traversal pointer once you find the end (a NULL pointer). Since you can just de...
3,182,843
3,182,864
Writing stl compatible iterators
I'm trying to convert an iterator class I have to be stl compatible so that it can be used with the stl algorithms. In the following simple (and frankly useless) example, which should print the values 0 to 5 inclusive, I am getting the following errors, ISO C++ forbids incrementing a pointer of type ‘Iterator (*)()‘ an...
You are passing the functions begin and end to std::for_each, instead of the iterators that these functions would return: std::for_each(begin,end,print); It should be: std::for_each(begin(),end(),print); Also note that the empty throw statements, like in if(val==-1 || val==6) throw;, will not do anything good. You ha...
3,182,927
3,182,969
Automata based alternative to re2
I am needing to implement regular expressions in a C++ program I am writing, and I wanted to use re2 but I could not compile it on windows. Does anyone know of another regular expression library or whatever it's called that compiles easily on windows and isn't a "backtracking" regex engine, but an automata-theory based...
Regular expressions are part of the TR1 standard, so chances are you already have a <tr1/regex> header that contains a std::tr1::regex class and related functions.
3,183,319
3,183,585
save gdb display to a variable
Is there a way to store the output of the last command in gdb to a string? What I would like to do is store the address information of selected machine level instructions. Redirecting the output is not a solution as it would generate too much output. A simulator would also be a solution, but I'd like to see if it would...
Not possible as far as I know, which is kind of surprising considering all the Lisp background of the author :) You'd need either redirection (grep, sed, and awk make wonders on large files, and there's always perl), or your own instruction decoding based on $pc, which I assume is not an option. Then I don't really und...
3,183,430
3,183,500
remove_vertex when the graph VertexList=vecS
I have a Boost Graph with VertexList=vecS. typedef adjacency_list <listS, vecS, undirectedS, TrackInformation, LinkInformation> TracksConnectionGraph; Now I want to iterate through my vertices and remove those that have a specific property. How can I do this? The problem is whenever I call remove_vertex, the iterator ...
I don't think it is possible (in a reasonable time) with vecS as a template parameter. Look what Boost documentation says: If the VertexList template parameter of the adjacency_list was vecS, then all vertex descriptors, edge descriptors, and iterators for the graph are invalidated by this operation. <...> If you need...
3,183,670
3,183,690
Can I combine setter and getter in one method, in C++?
I would like to combine setter/getter in one method, in C++, in order to be able to do the following: Foo f; f.name("Smith"); BOOST_CHECK_EQUAL("Smith", f.name()); I don't know how can I declare such a method inside Foo class: class Foo { public: // how to set default value?? const string& name(const string& n /* ...
class Foo { public: const string& name() const { return name_; } void name(const string& value) { name_ = value; } private: string name_; };
3,183,678
3,183,709
Operator overloading
From language design point of view , What type of practice is supporting operator overloading? What are the pros & cons (if any) ?
EDIT: it has been mentioned that std::complex is a much better example than std::string for "good use" of operator overloading, so I am including an example of that as well: std::complex<double> c; c = 10.0; c += 2.0; c = std::complex<double>(10.0, 1.0); c = c + 10.0; Aside from the constructor syntax, it looks and ac...
3,183,710
3,183,731
Forward declaration with friend function: invalid use of incomplete type
#include <iostream> class B; class A{ int a; public: friend void B::frndA(); }; class B{ int b; public: void frndA(); }; void B::frndA(){ A obj; std::cout << "A.a = " << obj.a << std::endl; } int main() { return 0; } When trying to compile this code, some errors occurred. E.g. invalid use of incomplete ty...
Place the whole of the class B ... declaration before class A. You haven't declared B::frndA(); yet. #include <iostream> using namespace std; class B{ int b; public: void frndA(); }; class A{ int a; public: friend void B::frndA(); }; void B::frndA(){ A obj; //cout<<"A.a = "<<obj.a<<endl; } ...
3,183,826
3,184,063
Deletion of objects send by signals, Ownership of objects in signals, Qt
Here, my signal declaration: signals: void mySignal(MyClass *); And how I'm using it: MyClass *myObject=new myClass(); emit mySignal(myObject); Here comes my problem: Who is responsible for deletion of myObject: Sender code, what if it deletes before myObject is used? Dangling Pointer The slot connected to signa...
You can connect a signal with as many slots as you want so you should make sure that none of those slots are able to do something you would not want them to do with your object: if you decide to pass a pointer as a parameter then you will be running in the issues you describe, memory management - here nobody can to th...
3,183,889
3,193,683
How can I embed a licence.licx file in a cpp executable?
We are using a third party UI component which requires a licence.licx file. The problem is that the executable is a cpp project and embedding the licence.licx file into the dll which actually uses the third party component does not seem to work. By "does not work" I mean that we get runtime licensing errors when execut...
It seems that the Assembly Linker can add resources to any PE file, including the EXE generated by the native C++ compiler. You'd do this as a post-build step.
3,184,030
3,184,348
Is using implicit conversion for an upcast instead of QueryInterface() legal with multiple inheritance?
Assume I have a class implementing two or more COM interfaces (exactly as here): class CMyClass : public IInterface1, public IInterface2 { }; QueryInterface() must return the same pointer for each request of the same interface (it needs an explicit upcast for proper pointer adjustment): if( iid == __uuidof( IUnknown ...
COM has no rules regarding interface identity, only of object identity. The first rule of QI says that a QI on IID_Unknown on two interface pointers must return the same pointer if they are implemented by the same object. Your QI implementation does this correctly. Without a guarantee for interface identity, a COM me...
3,184,088
3,184,189
Help using semphores and threads
I am using the pthread library to simulate a threaded buffer. I am also using semaphores as a solution to accessing critical section variables one at a time. The main problem is that the producer is filling the entire buffer and the consumer is then emptying the entire buffer. Is this code correct? I was assuming tha...
This is a well known problem with Mutexes. A Mutex is an expensive operation that requires lots of cycles. When you unlock the mutex the other thread has a TINY opportunity in which to exit its lock and gain a lock. Basially you need to spend less time in the mutex to give the other thread an opportunity to run. Ba...
3,184,118
3,184,129
new, delete ,malloc & free
This question was asked to me in an interview: In C++, what if we allocate memory using malloc and use delete to free that allocated memory? what if we allocate the memory using new and free it using free? What are the problems that we would face if the above things are used in the code? My answer was there is no ...
If you do so you will run into undefined behavior. Never try that. Although new might be implemented through malloc() and delete might be implemented through free() there's no guarantee that they are really implemented that way and also the user can overload new and delete at his discretion. You risk running into heap...
3,184,133
3,184,320
Garbage values when writing and reading to a text file
Can Some one help me the problem with this code? I am getting bunch of garbage value ! fstream fs("hello.txt"); if(fs.is_open()) { string s = "hello"; string line; fs << s; while(getline(fs,line)) { cout << line; } cin.get(); } fs.close(); Thank you very much but when I try ...
If hello.txt is empty prior to running the program then it seems to work for me. If the file contains more than 6 or 7 characters then your hello world code will overwrite the first 6/7 chars with "world" followed by the line terminator (which might be 1 or 2 chars depending on the platform). The reminder of the file w...
3,184,205
3,269,905
Undefined reference to external variable
Having problems with a custom logging system I've made. I am declaring an ofstream within my main file so that it is accessible by static functions within my class. This works for my static function (ilra_log_enabled). However, this does not work on my overloaded function for the class. I receive a undefined reference ...
I moved the variables to within the class and resolved the problem. Still not sure as to what was wrong with the previous method.
3,184,345
3,202,213
fopen problem - too many open files
I have a multithreaded application running on Win XP. At a certain stage one of a threads is failing to open an existing file using fopen function. _get_errno function returns EMFILE which means Too many open files. No more file descriptors are available. FOPEN_MAX for my platform is 20. _getmaxstdio returns 512. I che...
I think in win32 all the crt function will finally endup using the win32 api underneath. So in this case most probably it must be using CreateFile/OpenFile of win32. Now CreatFile/OpenFile api is not meant only for files (Files,Directories,Communication Ports,pipes,mail slots,Drive volumes etc.,). So in a real applicat...
3,184,395
3,184,619
Get previous value of QComboBox, which is in a QTableWidget, when the value is changed
Say I have a QTableWidget and in each row there is a QComboBox and a QSpinBox. Consider that I store their values is a QMap<QString /*Combo box val*/,int /*spin box val*/> theMap; When comboBoxes value or spin boxes value is being changed I want to update theMap. So I should know what was the former value of the combo...
How about creating your own, derived QComboBox class, something along the lines of: class MyComboBox : public QComboBox { Q_OBJECT private: QString _oldText; public: MyComboBox(QWidget *parent=0) : QComboBox(parent), _oldText() { connect(this,SIGNAL(editTextChanged(const QString&)), this, SLOT(myT...
3,184,401
3,184,423
varargs(va_list va_start) doesn't work with pass-by-reference parameter
Possible Duplicate: Are there gotchas using varargs with reference parameters Hi, I have a problem with varargs. Look at my code(Microsoft Visual Studio 2005 or 2008). #include <stdarg.h> struct Test { int a; }; void T1(int n, ...) { va_list args; va_start(args, n); char* p = va_arg(args, char*); va_end(args);...
You cannot use references with va_start according to C++ Standard 18.7/3: The restrictions that ISO C places on the second parameter to the va_start() macro in header are different in this International Standard. The parameter parmN is the identifier of the rightmost parameter in the variable parameter list of th...
3,184,445
3,184,473
How to clear directory contents in c++ on Linux (basically, i want to do 'rm -rf <directorypath>/*'
I am writing a c++ program on Linux (Ubuntu). I would like to delete the contents of a directory. It can be loose files or sub-directories. Essentially, i would like to do something equivalent to rm -rf <path-to-directory>/* Can you suggest the best way of doing this in c++ along with the required headers. Is it pos...
Boost remove_all http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/index.htm
3,184,453
3,338,915
extract every audio-channel in a quicktime file
I want to extract every audio channel in a quicktime movie with the QuickTime-API. That means if the file has 5.1 surround, i want 6 audio files in the end. But at the moment I don't know how to manage that. Until now I have: OSStatus err = noErr; MovieAudioExtractionRef extractionSessionRef = nil; Boolean allChannelsD...
Have you checked with this?
3,184,682
3,184,716
map iterator in template function unrecognized by compiler
I have the following code. template<class key,class val> bool has_key(key chkey,std::map<key,val> map){ for (std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc it!=map.end(); ++it){ if(chkey == it->first) return true; } return false; } GCC is giving me the following error. objects...
You need the typename keyword: for (typename std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc it!=map.end(); ++it){ See also: Why do we need typename here? This is because you are in a template definition and iterator is a dependent name. This has been asked before. g++ "is not a type" error ...
3,184,844
3,202,295
SIP RTP Stack for IVR Application
I have an IVR application which plays the prompts and records the user message and detects the DTMF. Currently the application is based on SS7 signaling and uses the PSTN based media boards for media play / record functionality. Now I have to move this application to IP based solution. For this, I need any open-source ...
Radvision has a extensive sip stack and it can be used seamlessly if you are ready to pay for it. I would suggest you can go for option 1 but you may have to tweak the code a lot to get the correct interfaces depending on the platform you are going to use it on. Exclude GPL license based software if you dont intend to...
3,184,893
3,184,971
Use next_permutation to permutate a vector of classes
Is it possible to use std::next_permutation() to permutate the elements of a vector of a class i created? How does the comparison parameter in next_permutation() work?
Is it possible to use std::next_permutation() to permutate the elements of a vector of a class i created? Yes! Try this #include<iostream> #include<vector> #include<algorithm> int main() { typedef std::vector<int> V; //<or_any_class> V v; for(int i=1;i<=5;++i) v.push_back(i*10); ...
3,184,939
3,185,008
why does creating a local type vector fail
#include <iostream> #include <vector> int main() { class Int { public: Int(int _i) : i(i) {} private: int i; }; std::vector<Int> VI; } I try to compile the above code and got the following error message: foo.cc: In function 'int main()': foo.cc:13: error: 'main()::...
The standard explictly prohibits using local classes to instantiate templates in 14.3.1[temp.arg.type]/2. A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter. This will be changed in C++0x.
3,185,132
3,185,346
How to combine a function and a predicate in for_each?
How can you call a Function over some part of a container, using for_each() ? I have created a for_each_if() to do a for( i in shapes ) if( i.color == 1 ) displayShape(i); and the call looks like for_each_if( shapes.begin(), shapes.end(), bind2nd( ptr_fun(colorEquals), 0 ), ...
To use a regular for_each with an if you would need a Functor that emulates an if condition. #include <algorithm> #include <vector> #include <functional> #include <iostream> #include <boost/bind.hpp> using namespace std; struct incr { typedef void result_type; void operator()(int& i) { ++i; } }; struct is_odd {...
3,185,243
3,185,297
Regarding C++ class access/manipulation in C
I've been reading questions on Stack Overflow for a few weeks now... this'll be my first question. So recently I've looked into making C access/manipulate a C++ class. I understand that ideally one shouldn't compile components in C and C++ separately under normal circumstances, but this isn't an option at the moment. I...
If you have a series of functions that are not object-orientated or in a namespace, there's no need to wrap them again. Your c_ series of functions are redundant. Any C++ function that is extern C, has global (i.e., not namespace/static member) linkage, and only takes C-compat datatypes (normally we use opaque pointers...
3,185,374
3,185,683
observable container for C++
Is there an implementation of container classes for C++ which support notification in a similar way as ObservableCollection for C#?
There is no standard class like you describe, but Boost.Signals is quite a powerful notification library. I would create a wrapper for objects that raises a signal when it is changed, along the lines of this: #include <boost/signals.hpp> #include <vector> #include <iostream> // Wrapper to allow notification when an ob...
3,185,380
3,185,666
Boost.Test output_test_stream fails with templated output operator
I have a class: class foo { private: std::string data; public: foo &append(const char* str, size_t n) { data.append(str,n); } // for debug output template <typename T> friend T& operator<< (T &out, foo const &f); // some other stuff }; template <typename T> T& operator<< (T &out, foo const &f...
So I think I have an explanation, but no solution yet. output_test_stream implements its stream functionality by subclassing wrap_stringstream. The insertion-operator for this is a free function-template that looks like this: template <typename CharT, typename T> inline basic_wrap_stringstream<CharT>& operator<<( basic...
3,185,582
3,185,650
Template subclass pointer problem
In a moment of madness, I decided to write a quadtree C++ template class. I've run into some weird compiler error that I don't understand with regard to subclasses and pointers to templates. I've found some hacky work arounds, but I wondered if anyone could shed some light on why my code wouldn't compile... I'm on Lin...
You need typename std::set< Leaf* >::iterator it = m_leaves.begin(); typename std::set< Leaf* >::iterator endit = m_leaves.end(); The type of std::set depends on another template argument and you have to tell the compiler that this is actually a type. gcc 4.5.0 produces a better error message. The second error is sim...
3,185,593
3,185,957
Is the primary implementation of *any* popular programming language interpreter written in C++?
At the moment I am considering whether or not to rewrite a programming language interpreter that I maintain in C++. The interpreter is currently implemented in C. But I was wondering, is the primary implementation—because, certainly, people have made versions of many interpreters using a language other than the one use...
I wrote an interpreter in C++ (after many in C over the years) and I think that C++ is a decent language for that. About the implementation I only would travel back in time and change my choice of implementing the possibility to have several different interpreters running at the same time (every one multithreaded) simp...
3,185,672
3,185,759
Boost multi-index with slow insertion performance
I have the following code (which largely follows the first example here: http://www.boost.org/doc/libs/1_42_0/libs/multi_index/doc/examples.html)). For some reason, with only 10000 insertations to the multi-index, it takes several minutes to run the program. Am I doing something wrong or is this expected? struct A { ...
Are you by any chance compiling in debug mode? It finishes near instantly with the default release configuration in Visual Studio 2008. If you're compiling in debug mode and you almost followed the example to the letter, including the pre-processor stuff and still had this part: #ifndef NDEBUG #define BOOST_MULTI_INDEX...
3,186,074
3,186,257
On Passing a 2D-Array into a function
This is not so much a question on, "How do I pass it into the function?" but rather, "Is this acceptable?" void func( int **ptr ); int main( int argc, char* argv[] ) { int arr[][3] = {{1, 2,}, {3, 4}, {5, 6}}; int *pArr = *arr; (&pArr[0])[1] = 3; func(&pArr); cin.get(); return 0; } void fu...
Let's dissect this carefully, since array-to-pointer conversions are sometimes confusing. int arr[][3] = {{1, 2,}, {3, 4}, {5, 6}}; arr is now an array of 3 arrays of 3 ints. int *pArr = *arr; *arr uses the array arr in expression, so it decays to a pointer to the first element of arr -- that is pointer to array of 3...
3,186,226
3,186,255
Why shouldn't I put "using namespace std" in a header?
Someone once hinted that doing this in a header file is not advised: using namespace std; Why is it not advised? Could it cause linker errors like this: (linewrapped for convenience) error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >:: ~basic_string<ch...
Because it forces anyone who uses your header file to bring the std namespace into global scope. This could be a problem if they have a class that has the same name as one of the standard library classes.
3,186,238
3,186,258
How do I assign a pointer to a variable?
Suppose we have a variable k which is equal 7: int k=7; int t=&k; But this does not work. What's the mistake?
&k takes the address of k. You probably mean int *t = &k; I have a good read for you: Alf P. Steinbach's pointer tutorial.
3,186,243
3,186,292
Strange behaviour with templates and #defines
I have the following definitions: template<typename T1, typename T2> class Test2 { public: static int hello() { return 0; } }; template<typename T> class Test1 { public: static int hello() { return 0; } }; #define VERIFY_R(call) { if (call == 0) printf("yea");} With these, I try to compile the following: VER...
The comma inside a macro can be ambiguous: an extra set of parentheses (your second example) is one way of disambiguating. Consider a macro #define VERIFY(A, B) { if ( (A) && (B) ) printf("hi"); } then you could write VERIFY( foo<bar, x> y ). Another way of disambiguating is with typedef Test1<int,int> TestII; VERIFY_...
3,186,450
3,186,811
Unicode Woes! Ms-Access 97 migration to Ms-Access 2007
Problem is categorized in two steps: Problem Step 1. Access 97 db containing XML strings that are encoded in UTF-8. The problem boils down to this: the Access 97 db contains XML strings that are encoded in UTF-8. So I created a patch tool for separate conversion for the XML strings from UTF-8 to Unicode. In order to ...
There is no special requirement for working with Greek characters. The real problem is that the characters were stored in an encoding that Access doesn't recognize in the first place. When the application stored the UTF8 values in the database it tried to convert every single byte to the equivalent byte in the database...
3,186,472
3,186,584
TypeLoadException while calling C++ method in C# file
I have a main program written in C# which creates and uses objects written in C++. One of these objects, MODULE, uses a Behavior class (C++), which contains a lot of parameters, initialized by an interface managed by the C# main. One of these parameters is a system::Collection::Generic < AnotherObject>, let's call it L...
You are showing exceptions that the debugger suffers when it tries to display the list instance. It isn't going help either you or us to diagnose the problem, you'll need to take a look at the exception that the code generates. If that doesn't help, post what you see in the exception's message and stack trace propert...
3,186,540
3,186,586
visibility problems with namespaces
I have two source files, one named main.cpp (where the namespace M is defined) and the file engines.h (where several names are defined). main.cpp includes engines.h. engines.h need to use the stuff inside M, and M needs to use the stuff inside engines.h. I get an error doing using namespace M; in engines.h.
You cannot do using namespace M before the namespace was defined. If there is a cyclic dependency, you need to solve it by using one or more techniques Forward declare if your uses don't need to know the members or size of classes, but just handle with pointers or references to them: namespace M { class MyCow; } Defi...
3,186,577
3,186,599
Returning references from a C++ methods
Dear friends, i'm concerned if i'm making a bad use of references in C++ In the following method GCC complains warning "reference to local variable ‘me’ returned" MatrizEsparsa& MatrizEsparsa::operator+(MatrizEsparsa& outra){ MatrizEsparsa me(outra.linhas(),outra.colunas()); return me; } But, with the following ch...
No. ref still refers to me which will be destroyed at the end of the call. You should return a copy of your result (not prefixed by &). MatrizEsparsa MatrizEsparsa::operator+(const MatrizEsparsa& outra) const { return MatrizEsparsa(outra.linhas(),outra.colunas()); } I also added two const specifiers (to the parame...
3,186,926
3,187,324
Shared global variable in C++ static library
I have a MS C++ project (let's call it project A) that I am currently compiling as a static library (.lib). It defines a global variable foo. I have two other projects which compile separately (call them B and C, respectively) and each links the shared static library A in. Both B and C are dll's that end up loaded in t...
Yes, you have to make A a shared DLL, or else define it as extern in B and C and link all three statically.
3,186,984
3,186,988
What does ~ mean in C++?
Specifically, could you tell me what this line of code does: int var1 = (var2 + 7) & ~7; Thanks
It's bitwise negation. This means that it performs the binary NOT operator on every bit of a number. For example: int x = 15; // Binary: 00000000 00000000 00000000 00001111 int y = ~x; // Binary: 11111111 11111111 11111111 11110000 When coupled with the & operator it is used for clearing bits. So, in your example it m...
3,187,019
3,187,085
Does C++ enforce return statements?
Okay, little oddity I discovered with my C++ compiler. I had a not-overly complex bit of code to refactor, and I accidentally managed to leave in a path that didn't have a return statement. My bad. On the other hand, this compiled, and segfaulted when I ran it and that path was hit, obviously. Here's my question: Is th...
Personally I think this should be an error: int f() { } int main() { int n = f(); return 0; } but most compilers treat it as a warning, and you may even have to use compiler switches to get that warning. For example, on g++ you need -Wall to get: [neilb@GONERIL NeilB]$ g++ -Wall nr.cpp nr.cpp: In function 'in...
3,187,148
3,187,358
Generating permutations via templates
I'd like a function, or function object, that can generate a permutation of its inputs with the permutation specified at compile time. To be clear, I am not looking to generate all of the permutations, only a specific one. For instance, permute<1,4,3,2>( a, b, c, d ) would return (a,d,c,b). Obviously, it is straight...
C++0x provides variadic templates, which you should be able to use to handle an arbitrary length permutation. They were added specifically because the current version of C++ doesn't have a clean way of dealing with this kind of problem.
3,187,293
3,187,486
double pointer memory allocation
I am currently trying to allocate the same amount of memory for a double pointer. I take in a char** and want to use a bubble sort on that char** . So I create a temp char** and now I'm wondering how to correctly allocate enough memory so that I can return that temp char** to another method. I know the way I'm alloca...
Here is the working copy of the program: #include <cstdio> #include <cstdlib> #include <cstring> char** bubble_sort(const char **filenames, int n) { int i; char **new_list; new_list = (char**) malloc(sizeof(*new_list) * n); for (i = 0; i < n; i++) { new_list[i] = (char*) filenames[i]; }...
3,187,625
3,187,661
Call QueryInterface before CoCreateInstance?
Is the above possible? Can I do this: IUnknown *punk; punk->QueryInterface(IID_MyInterface, (void**)&m_pMyInterface); I thought that this would tell me if the MyInterface is supported m_pMyInterface...
If you really mean what you've written above, then no: because your punk is an uninitialized pointer. Normally you need to call CoCreateInstance to create an instance of something; after that you can call QueryInterface on that instance, to ask what interface[s] it supports.
3,187,728
3,187,732
Does gcc emit different output in one-liners with/without braces
I tried to use astyle to format the code base I've to work with. When I use the option --add-brackets the executable is not identical (If I only use -t and/or -b the output is identical). if(a) return b is modified to if(a) { return b } So my question is. Does gcc generate the same output if I only add and/or de...
1, No 2, Use the - s flag to see the assembler ( or Using GCC to produce readable assembly? to get more readable assembler)
3,187,770
3,188,607
Partially initialize variable defined in other module
I'm considering a certain solution where I would like to initialize a cell of an array that is defined in other module (there will be many modules initializing one table). The array won't be read before running main (so there is not problem with static initialization order). My approach: /* secondary module */ extern...
This works with MSVC compilers but with GNU C++ does not (at least for me). GNU linker will strip all the symbol not used outside your compilation unit. I know only one way to guarantee such initialization - "init once" idiom. For examle: init_once.h: template <typename T> class InitOnce { T *instance; static u...
3,187,843
3,188,108
Use Public Variable Globally
I'm attempting to modify a MIPS simulator to display the contents of its registers during run time. My question refers to the way in which I plan to do this. So... I have a file, file1.cpp and file2.cpp. There is a local public variable in file1.cpp called typedef long ValueGPR; ValueGPR reg[33]; that I want to ac...
Cogwheel's answer is correct, but your comment indicates some possibility of confusion, so perhaps it's better to clarify a bit: file1.h: #ifndef FILE1_H_INCLUDED #define FILE1_H_INCLUDED typedef long ValueGPR; extern ValueGPR reg[]; #define NUM_REGS 33 #endif file1.c: #include "file1.h" ValueGPR reg[NUM_REGS]; fi...
3,188,156
3,188,175
Difference between classes and namespaces?
I'm looking at namespaces and I don't really see a difference between these and classes. I'm teaching myself C++ I've gotten several books online, so I know I'm not learning the most effectively. Anyway, can someone tell me the difference between the two, and what would be the best time to use a namepace over a class? ...
Classes and structs define types. You can create an object of a type. Namespaces simply declare a scope inside which other types, functions, objects, or namespaces can exist. You can't create an object of type std (unless of course you created a type called std, which would hide the std namespace). When you define a f...
3,188,352
3,191,582
Changing the dataype of a Mat class instance in OpenCV C++ Interface
How can i change the datatype used in storing the pixels in a Mat class instance? For example after reading an image using the line below Mat I = imread(file,0); i obtain a grayscale image with pixels of type unsigned char. I want to change this to a double. What's the best way to do the conversion? I wasn't able to fi...
It is very simple. See the documentation at OpenCV website. Basically do Mat double_I; I.convertTo(double_I, CV_64F);
3,188,439
3,188,481
question on struct in c++
I have the following code #include <iostream> #include<string> #include <sstream> using namespace std; struct product{ int weight; float price; }; int main(){ string mystr; product prod; product *pointer; pointer=&prod; getline(cin,pointer->price); return 0; } but it shows me the mist...
The mistake is that getline returns string, not float. string str; getline(cin, str); pointer->price = atof(str.c_str());
3,188,554
3,188,591
How to get OpenGL running on OSX
I normally program on Windows, but I got a macbook pro from my school, so I'm trying to make an OpenGL app for OSX. I downloaded and installed XCode, but I have no clue how to get a simple OpenGL app going. I would prefer not to use Objective-C, but I definitely don't want to use GLUT. Can someone point me in the right...
The biggest difference between OpenGL on OS X compared to pretty much everything else is the location of the header files. On OS X: #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> If you want to stay away from Objective-C/Cocoa and GLUT you can try SDL which is a cross platform gaming library (w...
3,188,706
3,188,806
How to delete certain characters from multiple text files, in a thread safe way?
What is the best way, to develop a multi threaded program, to delete certain characters from multiple text files that are passed in as parameters? Thus, when someone passes as a.out axvc f1 f2 f3 f4 , the goal is to delete all occurences of the characters a,x,v,c from the file f1, f2, f3 and f4.
Are you not able to just make use of normal utilities like sed to help you do this? Even if you aren't, are you sure that the CPU use is a significant enough portion of the processing time that it wouldn't be dwarfed by the file I/O? Most likely doing it in multiple threads won't save you much time at all vs doing it s...
3,188,793
3,188,818
When should the STL algorithms be used instead of using your own?
I frequently use the STL containers but have never used the STL algorithms that are to be used with the STL containers. One benefit of using the STL algorithms is that they provide a method for removing loops so that code logic complexity is reduced. There are other benefits that I won't list here. I have never se...
Short answer: Always. Long answer: Always. That's what they are there for. They're optimized for use with STL containers, and they're faster, clearer, and more idiomatic than anything you can write yourself. The only situation you should consider rolling your own is if you can articulate a very specific, mission-critic...
3,189,117
3,189,438
How to listen to dll function calls
is there any way to "listen" to when a function of a dll is called? I would like to know what functions of a dll is called and the parameters etc.... is it possible? thanks!
Check out WinApiOverride32. This is a really powerful monitor, with support of COM and .NET and easily customizable (you can monitor DLL internal functions as well). Also, you can write a custom DLL to override some APIs called by the target.
3,189,199
3,189,257
Declaring and initializing variable in for loop
Can I write simply for (int i = 0; ... instead of int i; for (i = 0; ... in C or C++? (And will variable i be accessible inside the loop only?)
It's valid in C++. It was not legal in the original version of C. But was adopted as part of C in C99 (when some C++ features were sort of back ported to C) Using gcc gcc -std=c99 <file>.c The variable is valid inside the for statement and the statement that is looped over. If this is a block statement then it is vali...
3,189,202
3,189,272
Deleting nodes in a doubly linked list (C++)
I have problems understanding why when I create two or more nodes (as shown below), the function void del_end()will only delete the char name[20] and not the whole node . How do I fix this problem without memory leak? #include <iostream> using namespace std; struct node { char name[20]; char profession[20]; ...
Your code has some problems, the worst being here: temp2=temp->prv; delete temp2; temp->nxt= NULL; You're deleting the next-to-last node, leaving any pointers to it dangling, and losing the last node. But if you post more of the real code, we can tell you more. EDIT: Here's a slightly cleaned-up version of del_end (an...
3,189,306
3,190,365
Boost thread_interrupted exception terminate()s with MinGW gcc 4.4.0, OK with 3.4.5
I've been "playing around with" boost threads today as a learning exercise, and I've got a working example I built quite a few months ago (before I was interrupted and had to drop multi-threading for a while) that's showing unusual behaviour. When I initially wrote it I was using MingW gcc 3.4.5, and it worked. Now I'm...
Solved. It turns out adding the complier flag -static-libgcc removes the problem with 4.4.0 (and has no apparent affect with 3.4.5) - or at least in this case the program returns the expected results.
3,189,429
3,189,922
Redirecting ostream to file not working
I have a custom logging system which allows me to send information to a log file and the console depending on the verbosity currently selected. Right now, the trouble I am having is with the output to the file, with output to the console working fine. Here is an example: ilra_talk << "Local IP: " << systemIP() <<...
I see nothing totally wrong with the code, though I personally would have made two changes: Put the logfile.flush() into the ilra::~ilra(). Logging and buffering are no friends. Change static ofstream logfile to static ofstream *logfile: allocated/delete it in ilra_log_enabled() and add NULL check in the << operators....
3,189,436
3,189,464
Access class functions from another thead?
I have a function in my class that creates a thread and gives it arguments to call a function which is part of that class but since thread procs must be static, I can't access any of the class's members. How can this be done without using a bunch of static members in the cpp file to temporarily give the data to be mani...
Usually you specify the address of the object of myclass as arg type and cast it inside the ThreadProc. But then you'll be blocked on how passing the int argument. void ThreadProc(void *arg) { myclass* obj = reinterpret_cast<myclass*>(arg); //Can't do this obj->SetNumber(???); } As you said this is maybe not ...
3,189,475
3,190,304
Minor (unimportant) defect in the standard?
This question has no practical issues associated with it, it is more a matter of curiosity and wanting to know if I am taking things too literally ;). So I have been trying to work towards understanding as much of the c++ standard as possible. Today in my delving into the standard I noticed this (ISO/IEC 14882:2003 21...
Yes, it was a defect and yes, this was the fix. http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#259
3,189,545
3,189,588
Proper way to make a global "constant" in C++
Typically, the way I'd define a true global constant (lets say, pi) would be to place an extern const in a header file, and define the constant in a .cpp file: constants.h: extern const pi; constants.cpp: #include "constants.h" #include <cmath> const pi=std::acos(-1.0); This works great for true constants such as pi....
It all depends on your application size. If you are truly absolutely sure that a particular constant will have a single value shared by all threads and branches in your code for a single run, and that is unlikely to change in the future, then a global variable matches the intended semantics most closely, so it's best t...
3,189,900
3,191,252
Fetching remote database info from a client application
What would be the preferred method of pulling content from a remote database? I don't think that I would want to pull directly from the database for a number of reasons. (Such as easily being able to change where it is fetching the info from and a current lack of access from outside the server.) I've been thinking of u...
I've got a similar problem at the moment, and the approach I'm taking is to communicate from the client app with a database via a SOAP web service. The beauty of this approach is that on the client side the networking involved consists of a standard HTTP request. Most platforms these days include an API to perform basi...
3,189,944
3,190,001
SSL handshake yields BIO errors
Fairly new to socket programming, but I've been assigned with a whopper of project. My issue is this: I try initiating an SSL handshake with both SSL_accept() and SSL_connect(), as well as renegotiating the handshake and then attempting to reconnect with SSL_renegotiate() and SSL_do_handshake() in succession, but all ...
It is hard to tell without seeing any code but the error 'unsupported method' means that you are problably trying to call a function with the wrong BIO as parameter. In other words, you cannot call BIO_write with an accept BIO (one created with, eg, a call to BIO_new_accept()). An accept BIO is for, well, accepting con...
3,189,998
3,190,084
C++: Two classes needing each other
I'm making a game and I have a class called Man and a class called Block in their code they both need each other, but they're in seperate files. Is there a way to "predefine" a class? Like Objective-C's @class macro?
It's called a circular dependency. In class Two.h class One; class Two { public: One* oneRef; }; And in class One.h class Two; class One { public: Two* twoRef; }; The "class One;" and "class Two;" directives allocate a class names "One" and "Two" respectively; but they don't define any other details be...
3,190,096
3,190,130
C++ constant temporary lifetime
Can you please tell me if such code is correct (according to standard): struct array { int data[4]; operator const int*() const { return data; } }; void function(const int*) { ... } function(array()); // is array data valid inside function? Thank you
Yes. The temporary object is valid until the end of the full expression in which it is created; that is, until after the function call returns. I don't have my copy of the standard to hand, so I can't give the exact reference; but it's in 12.2 of the C++0x final draft.
3,190,158
3,190,264
What am I doing wrong? (multithreading)
Here s what I'm doing in a nutshell. In my class's cpp file I have: std::vector<std::vector<GLdouble>> ThreadPts[4]; The thread proc looks like this: unsigned __stdcall BezierThreadProc(void *arg) { SHAPETHREADDATA *data = (SHAPETHREADDATA *) arg; OGLSHAPE *obj = reinterpret_cast<OGLSHAPE*>(data->objectptr); ...
The problem is that you're passing the same dat structure to each thread as the argument to the threadproc. For example, When you start thread 1, there's no guarantee that it will have read the information in the dat structure before your main thread starts loading that same dat structure with the information for threa...
3,190,275
3,190,515
Using C++ Macros To Check For Variable Existence
I am creating a logging facility for my library, and have made some nice macros such as: #define DEBUG myDebuggingClass(__FILE__, __FUNCTION__, __LINE__) #define WARING myWarningClass(__FILE__, __FUNCTION__, __LINE__) where myDebuggingClass and myWarningClass both have an overloaded << operator, and do some helpful t...
Declare a global Widget* const widget_this = NULL; and a protected member variable widget_this in the Widget class, initialized to this, and do #define DEBUG myDebuggingClass(__FILE__, __FUNCTION__, __LINE__, widget_this)
3,190,514
3,190,555
popen equivalent in c++
Is their any C popen() equivalent in C++ ?
You can use the "not yet official" boost.process if you want an object-oriented approach for managing the subprocess. Or you can just use popen itself, if you don't mind the C-ness of it all.
3,190,569
3,190,658
Determine type of templated function result at compile-time?
I'm not sure this is possible, but is there a way, using template programming magic, to define a function that has different return values depending on what input it takes? Potentially: template<typename resultType> resultType GetResult(const std::string &key); // where the value of key may change resultType template<...
No. You cannot make the return type, defined at compile-time, depend on a run-time value. You could return a boost::variant or a boost::any, though.
3,190,571
3,190,676
How do I use an int& parameter with a default value?
I have to add a default int& argument (Eg iNewArgument) to an existing function definition in a header file: What is the syntax to initialize the last argument to make it take a default value? .. virtual int ExecNew (int& param1, int& RowIn,int& RowOut, char* Msg = '0', bool bDebug=true, int& iNewArgu...
Your example indicates that you are creating a virtual function. Default arguments in virtual (especially pure) functions are not a good idea, because they are not considered when you call an overridden function. struct A { virtual void f(int = 4711) = 0; }; struct B : A { virtual void f(int) { /* ... */ } }; No...
3,190,700
3,190,799
Error with C++ operator overloading, in Visual Studio AND Xcode
I am working on a C++ assignment for class that wants me to overload the ">>" operator. I am encountering errors linking in both Visual Studio 2005 and Xcode 3.2.2. The C++ code is separated into a few files. The prototypes are stored in overload.h, the implementations are stored in overload.cpp, and main() is in overl...
The error undefined symbol is a linker error. It means that when you are linking all your code into a single executable / library, the linker is not able to find the definition of the function. The main two reasons for that are forgetting to include the compiled object in the library/executable or an error while defini...
3,190,934
3,190,976
Inheritance Costs in C++
Taking the following snippet as an example: struct Foo { typedef int type; }; class Bar : private Foo { }; class Baz { }; As you can see, no virtual functions exist in this relationship. Since this is the case, are the the following assumptions accurate as far as the language is concerned? No virtual function tab...
According to the standard, Bar is not a POD (plain old data) type, because it has a base. As a result, the standard gives C++ compilers wide latitude with what they do with such a type. However, very few compilers are going to do anything insane here. The one thing you probably have to look out for is the Empty Base Op...
3,191,124
3,191,142
Passing class template as a function parameter
This question is a result of my lack of understanding of a situation, so please bear if it sounds overly stupid. I have a function in a class, like: Class A { void foo(int a, int b, ?) { ---- } } The third parameter I want to pass, is a typed parameter like classA<classB<double > > obj Is this possible? If not, ...
Doesn't it work if you just put it there as a third parameter? void foo(int a, int b, classA< classB<double> > obj) { ... } If it's a complex type it might also be preferable to make it a const reference, to avoid unnecessary copying: void foo(int a, int b, const classA< classB<double> > &obj) { ... }
3,191,331
3,191,474
Multithreading not taking advantage of multiple cores?
My computer is a dual core core2Duo. I have implemented multithreading in a slow area of my application but I still notice cpu usage never exceeds 50% and it still lags after many iterations. Is this normal? I was hopeing it would get my cpu up to 100% since im dividing it into 4 threads. Why could it still be capped a...
Looking at your code, you are making a huge number of allocations in your tight loop--in each iteration you dynamically allocate two, two-element vectors and then push those back onto the result vector (thus making copies of both of those vectors); that last push back will occasionally cause a reallocation and a copy o...
3,191,500
3,191,505
Enumeration relying on integer boolean conversion
In my compiler project, I have an enumeration that goes like enum Result { No, Maybe, Yes }; I have put No explicitly at the first position, so that i can rely on the boolean evaluation to false. If my compiler is not sure about something, and has to wait for facts until runtime, its analysis functions will retu...
I'd feel guilty about it as well, because from reading the code above what would you expect the boolean typesEqual() expression to return for a Maybe? Would it return true? Maybe! Would it return false? Maybe! We don't know - that's the entire point of the enum. That's why it makes sense to explicitly compare to No, ev...
3,191,535
3,191,542
Pushing a static array into a std::vector?
I'm trying to do the following: I have: std::vector<std::vector<GLdouble[2]>> ThreadPts(4); then I try to do: GLdouble tmp[2]; while(step--) { fx += dfx; fy += dfy; dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; tmp[0] = fx; tmp[1] = fy; ThreadPts[currentvector].push_ba...
A C-style array is not assignable, so it cannot be used as the value type of a vector. If you are using at least C++11, you can #include <array> and use std::array. (Historically available in Visual C++ 2008 SP1 as std::tr1::array). typedef std::vector<GLdouble[2]> pointList; // Becomes typedef std::vector<std::array<G...
3,191,610
3,192,421
Writing a keyboard driver that accepts input from code
The ultimate goal of this project is to send low level input (so that it looks like it is coming from the keyboard) to my windows machine. I know C++, Python, and Java. Though I would love to do this in python, C++ will probably be the only option. I have been searching around the internet and have found something call...
Download DDK or WDK and look at kbfiltr sample. You can't use Python or Java. Drivers are typically written in C. If you have no driver development background it will be not so easy (you need to read a lot of docs to understand what you are actually doing). Good luck!
3,191,727
3,191,773
Better way to copy several std::vectors into 1? (multithreading)
Here is what I'm doing: I'm taking in bezier points and running bezier interpolation then storing the result in a std::vector<std::vector<POINT>. The bezier calculation was slowing me down so this is what I did. I start with a std::vector<USERPOINT> which is a struct with a point and 2 other points for bezier handles. ...
Have all the threads put their results into a single contiguous vector just like before. You have to ensure each thread only accesses parts of the vector that are separate from the others. As long as that's the case (which it should be regardless -- you don't want to generate the same output twice) each is still workin...
3,191,854
3,191,865
Automatic Evaluation Strategy Selection in C++
Consider the following function template: template<typename T> void Foo(T) { // ... } Pass-by-value semantics make sense if T happens to be an integral type, or at least a type that's cheap to copy. Using pass-by-[const]-reference semantics, on the other hand, makes more sense if T happens to be an expensive type to...
Yes. All the time. I use it myself. Yes, use Boost.Utility's Call Traits :) Usage would be... template <typename T> void foo(boost::call_traits<T>::param_type param) { // Use param } As far as I know, non-class templates are passed-by-value unless it is faster to not. Thanks to partial template specialization, it...
3,191,912
3,192,002
Making worker threads?
Is there a way to make "worker threads" Basically I tried creating threads every time I needed them and this resulted in being slower than with 1 thread becase creating a new thread all the time is expensive. Would there be a way to create worker threads when the application first starts, then give them work when neces...
Yes, you can create the threads up front and have them wait for signals to go and start their work. These signals can be message queues or semaphores or any other sort of inter-thread communication method. As an example, we once put together a system under UNIX which had a master thread to receive work over the net and...
3,191,925
3,211,153
On the fly font coloring in Tclsh via c++
I am an amateur try to hack together a little project. It is a simple note storage and retrieval console app on Windows Vista (and XP - i'm hoping to run the whole thing off a USB Stick). I use Sqlite as the store and Tcl/SQL scripts to add notes (and tags!) and also retrieve them by tag. 3 tables and a "Toxi" schema....
A header isn't enough by itself. On the other hand, you really don't need to go to all that much work since this page indicates that the API is actually really simple. Here's the C code that you need: #include <tcl.h> #include <windows.h> static int MySetConsoleColorCmd( ClientData clientData, Tcl_Interp *interp, ...
3,192,052
3,192,189
Critique my concurrent queue
This is a concurrent queue I wrote which I plan on using in a thread pool I'm writing. I'm wondering if there are any performance improvements I could make. atomic_counter is pasted below if you're curious! #ifndef NS_CONCURRENT_QUEUE_HPP_INCLUDED #define NS_CONCURRENT_QUEUE_HPP_INCLUDED #include <ns/atomic_counter.hp...
I think you will run into performance problems with a linked list in this case because of calling new for each new node. And this isn't just because calling the dynamic memory allocator is slow. It's because calling it frequently introduces a lot of concurrency overhead because the free store has to be kept consisten...
3,192,097
3,192,321
Fastest way to calculate cubic bezier curves?
Right now I calculate it like this: double dx1 = a.RightHandle.x - a.UserPoint.x; double dy1 = a.RightHandle.y - a.UserPoint.y; double dx2 = b.LeftHandle.x - a.RightHandle.x; double dy2 = b.LeftHandle.y - a.RightHandle.y; double dx3 = b.UserPoint.x - b.LeftHandle.x; double dy3 = b.UserPoint.y - ...
There is another point that is also very important, which is that you are approximating your curve using a lot of fixed-length straight-line segments. This is inefficient in areas where your curve is nearly straight, and can lead to a nasty angular poly-line where the curve is very curvy. There is not a simple compromi...
3,192,491
3,192,538
How to get a list of hosts connected to a mysql server
I am trying to get a list of hosts connected to a mysql server. How can i get this? What should i do after connecting to the mysql server. Code snippets will really help. Also whats the best api to use to connect to mysql using c++?
One way you could do it is to execute the query show processlist, which will give you a table with Id, User, Host, db, Command, Time, State and Info columns. Remember that your show processlist query will be part of the output.
3,192,631
3,192,964
How to design a big class header file in c++?
I have a big C++ class, which includes 5 other classes inside, and some of them have other classes inside. The total length of a header (.h) file is very big and it is unreadable. This is what I'm trying to do: // Foo.h file #ifndef __INCLUDE_FOO_H #define __INCLUDE_FOO_H namespace foo { class Foo { public: #include ...
Instead of making the inner classes inner classes, you're better off leaving them on their own, eventually in their own namespace: // in file foo/bar.h namespace foo_detail { class Bar { }; }; // in file foo.h #include "foo/bar.h" class Foo { private: foo_detail::Bar theBar; }; This way your Foo cla...
3,193,020
3,193,099
Calling C++ static member functions from C code
I have a bunch of C code. I have no intention to convert them into C++ code. Now, I would like to call some C++ code (I don't mind to modify the C++ code so that they are callable by C code). class Utils { public: static void fun(); } class Utils2 { public: static std::wstring fun(); } If I tend to call them ...
// c_header.h #if defined(__cplusplus) extern "C" { #endif void Utils_func(); size_t Utils2_func(wchar_t* data, size_t size); #if defined(__cplusplus) } #endif //eof // c_impl.cpp // Beware, brain-compiled code ahead! void Utils_func() { Utils::func(); } size_t Utils2_func(wchar_t* data, size_t size) { std::wst...