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 |
|---|---|---|---|---|
2,871,601 | 2,871,613 | Inheritance and static variables | Here is my code -
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
int a;
};
//int Base::a = 5;
class Derived : public Base
{
public:
int static a;
};
int main()
{
Derived d;
cout<<d.a;
getch();
return 0;
}
I get a linker error here. But when I do it the other way ro... | All static members have to be explicitly defined/initialized outside the class.
In the second example you do this correctly (int Base::a=5), but in the first example you don't do this for Derived::a, adding the following line to the first example should solve it:
int Derived::a = 5;
|
2,871,905 | 3,203,888 | OpenAL - determine maximum sources | Is there an API that allows you to define the maximum number of OpenAL "sources" allowed by the underlying sound hardware?
Searching the internet, I found 2 recommendations :
keep generating OpenAL sources till you get an error. However, there is a note in FreeSL (OpenAL wrapper) stating that this is "very bad and may... | update:
I can't find a way to determine what the maximum number of sources a device supports, but I think I've found how to determine the maximum a context supports(ALC_MONO_SOURCES). It would follow that a context supports the same number as its parent device.
//error checking omitted for brevity
ALCdevice* device = ... |
2,871,906 | 2,871,943 | Containers of auto pointers | I know containers of auto pointers should not be used and can cause problems. What is the actual reason for that? Is there any other kind of "smart" pointer which is safe to use in a container?
| Container elements should be truly copyable; auto_ptr's are not. If you make a copy, the original is modified (it loses ownership). A boost::shared_ptr can be copied, as the two pointers will share ownership afterwards. Thus, it can be used in a STL container.
|
2,872,073 | 2,872,095 | Is throwing an exception a healthy way to exit? | I have a setup that looks like this.
class Checker
{ // member data
Results m_results; // see below
public:
bool Check();
private:
bool Check1();
bool Check2();
// .. so on
};
Checker is a class that performs lengthy check computations for engineering analysis. Each type of check has a resultan... | I don't think this is a good idea. Exceptions should be limited to, well, exceptional situations. Yours is a question of normal control flow.
It seems you could very well move all the redundant code dealing with the result out of the checks and into the calling function. The resulting code would be cleaner and probabl... |
2,872,155 | 2,874,560 | Howcome some C++ functions with unspecified linkage build with C linkage? | This is something that makes me fairly perplexed.
I have a C++ file that implements a set of functions, and a header file that defines prototypes for them.
When building with Visual Studio or MingW-gcc, I get linking errors on two of the functions, and adding an 'extern "C"' qualifier resolved the error. How is this po... | The error indicates that nothing is wrong with your implementation file or header (as used by the implementation file) - the link error strongly suggests that the functions actually generated were generated with c++ linkage - Its the UI file thats incorrectly looking for the C-Linkage versions of the functions. Patchin... |
2,872,841 | 2,872,881 | Do I have to start from beginning? | If I have:
std::size_t bagCapacity_ = 10;
std::size_t bagSize = 0;
A** bag = new A*[bagCapacity_];
while (capacity--)
{
bag[capacity] = new A(bagSize++); //**here I'm loading this array from the end is it ok?**
}
And also can I delete those object from starting at the end of the array?
while (capacity--)
{
delete... | here I'm loading this array from the end is it ok?
Yes, that is fine. You can fill the elements anyway you like.
delete[] bag[capacity];
This code is wrong. bag[capacity] is of type A* which is allocated using new and not new[] hence you should not do delete[] you should do only delete bag[capacity]; to delete indivi... |
2,872,958 | 2,872,970 | RegQueryValueEx not working with a Release version but working fine with Debug | I'm trying to read some ODBC details from a registry and for that I use RegQueryValueEx. The problem is when I compile the release version it simply cannot read any registry values.
The code is:
CString odbcFuns::getOpenedKeyRegValue(HKEY hKey, CString valName)
{
CString retStr;
char *strTmp = (char*)malloc(MA... | You need to initialize cbData - set it to be MAX_DSN_STR_LENGTH - 1 before calling RegQueryValueEx().
The problem is likely configuration-dependent because the variable is initialized by the compiler in one configuration and left uninitialized in another.
Also you'll be much better of using std::vector for the buffer ... |
2,873,128 | 2,876,218 | C++/Qt Apps on Ovi Store? | Can one develop C++/Qt based application for Symbian and N series phone and upload the same to Ovi store ?.
I hear conflicting stories. I understand the existence of Smart Installer etc.
But my question is as of today can I code and ship apps to Ovi store ?.
If not any clue how long before it becomes a reality ?.
Ank... | Today it is not possible to publish applications developed with Qt in Ovi Store. The problem is, that today very few phones have Qt installed. For this, Nokia created the smart installer, that would be asked to install the correct version of Qt from the internet, but still not stable. Something can be done is to link t... |
2,873,255 | 2,873,282 | TCP Message Structure with XML | I'm sending messages over TCP/IP and on the other side I parse TCP message.For example this is one of the sent messages.
$DKMSG(requestType=REQUEST_LOGIN&requestId=123&username=metdos&password=123)$EDKMSG
Clarification:
$DKMSG( //Start
)$EDKMSG //End
requestType //Parameter
REQUEST_LOGIN //Parameter Value... | This looks like a homegrown format. You should use something out-of-the-box instead, like JSON, XML, protocol buffers, or even the young upstart: BERT, which even specifies an RPC protocol that uses the format. These formats all have parsers written for them in several languages, and they are all supported on C++.
|
2,873,381 | 2,874,901 | How to call a C++ function that takes a reference from C# code | HI,
I have a C++ function like the following:
int ShowJob(const JobData& data);
How does this translate to a DLLImport statement which I can use to call the function from C#?
| This could only work if JobData is a structure. You're dead in the water if it is a class, you cannot create a C++ class instance in C#. You don't have access to the constructor and destructor.
The "const" keyword is an attribute checked by the C++ compiler, it has no relevance to C# code. A C++ reference is a poi... |
2,873,579 | 2,873,607 | c++ generic pointer to (member?) function | I can't seem to declare a generic pointer to function.
Having these 2 functions to be called:
void myfunc1(std::string str)
{
std::cout << str << std::endl;
}
struct X
{
void f(std::string str){ std::cout<< str << std::endl;}
};
and these two function callers:
typedef void (*userhandler_t) (std::string);
s... | boost::bind creates objects that behave like functions, not actual function pointers. Use the Boost.Function library to hold the result of calling boost::bind:
struct example
{
boost::function<void(std::string)> userhandler_;
...
};
|
2,873,692 | 2,874,755 | For programming content, what simple-to-use-and-setup PHP based blog are the preferred ones? | I've since long wanted a place I can toss my programming related nuggets at. Every day I feel I solve something that I'll surely hit again in a not so distant future, but by then I most certainly will have forgotten about the previous solution I came up with.
So I need to blog it down, quick and dirty, for my own docum... | I've always used WordPress for this and have had great results. If you go that route, there are two syntax highlighter plugins in particular I'd recommend looking into.
Syntax Highlighter Evolved
http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/
This one uses square brackets ([ ]) to denote your code blo... |
2,873,714 | 2,873,735 | Is it possible to use a DLL created using C# in an unmanaged VC++ application? | I have a DLL that I wrote in C# and I want to use it both with C# applications and applications written in unmanaged VC++. Is this possible?
| To supplement other answers here, here's the MS support article which describes your scenario.
http://support.microsoft.com/kb/828736
|
2,873,721 | 2,875,350 | Oracle Extended Stored Procedure with C++ | I am currently adding Oracle 10.2.0. as a viable database to a product. The product originally allows connection to SQL Server and I have found some extended stored procedures.
Is it possible to produce similar extended stored procedures for Oracle with C++?
If so, how do I accomplish this? Example code would be much a... | You will need to use Oracle External Procedures.
Here is a discussion on getting the environment set up properly - it's tricky.
Asktom.com has an interesting discussion.
Be aware there are several security issues to be concerned with.
|
2,873,802 | 2,873,883 | Specify template parameters at runtime | Consider the following template class
class MyClassInterface {
public:
virtual double foo(double) = 0;
}
class MyClass<int P1, int P2, int P3>
: public MyClassInterface {
public:
double foo(double a) {
// complex computation dependent on P1, P2, P3
}
// more methods and fields (dependent on P1, P2, P3)
}
... | Here's what you can do:
MyClassInterface* Factor(int p1, int p2, int p3) {
if (p1 == 0 && p2 == 0 && p3 == 0)
return new MyClass<0,0,0>();
if (p1 == 0 && p2 == 0 && p3 == 1)
return new MyClass<0,0,1>();
etc;
}
Note that this does not even remotely scale to floating point values. It scales only to a known... |
2,874,164 | 2,874,196 | Hold a network connection although IP address change | Is it possible to hold an open TCP connection with a client, while the IP address of the client is externally changed?
For example, the connection is establishes against address X, but somewhen while the connection is open, the client-side user asks for IP renew and gets another IP address. Can the connection remains a... | No, it cannot.
Even if the local side could be massaged to understand that the connection is suddenly between different addresses, the remote side will not understand and will refuse to work with it.
You'd need to re-add the old IP address to continue using the connection.
To do so:
Linux: ip addr add 172.16.10.20/22 ... |
2,874,198 | 2,874,352 | Using boost::random to select from an std::list where elements are being removed | See this related question on more generic use of the Boost Random library.
My questions involves selecting a random element from an std::list, doing some operation, which could potentally include removing the element from the list, and then choosing another random element, until some condition is satisfied.
The boost c... | I assume that MyClass & mc = myList.begin() + index; is just pseudo code, as begin returns an iterator and I don't think list iterators (non-random-access) support operator+.
As far as I can tell, with variate generator your three basic options in this case are:
Recreate the generator when you remove an item.
Do filte... |
2,874,403 | 2,882,131 | Strip OLE header information (MS Access / SQL Server) | I have a C++ application that needs to support binary database content (images, etc). When using MS Access or MS SQL Server this data is wrapped inside an OLE object. How do I strip this OLE header information? Note that I can't just look for the beginning of a specific tag as the content can be png, jpg and a whole he... | Using MS Access 2007 (I need to test other MS databases) the format seems to be:
84 bytes
file name + \0
full path + \0
5 bytes + [2] bytes (the third byte of those five bytes)
temp path + \0
4 bytes
actual data (if not using a link to the file)
So far I simply parse and strip the part before the actual data, but I'm ... |
2,874,441 | 2,874,533 | Deleting elements from std::set while iterating | I need to go through a set and remove elements that meet a predefined criteria.
This is the test code I wrote:
#include <set>
#include <algorithm>
void printElement(int value) {
std::cout << value << " ";
}
int main() {
int initNum[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> numbers(initNum, initN... | This is implementation dependent:
Standard 23.1.2.8:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
Maybe you could try this -- this is standard conforming:
for (auto it = numbe... |
2,874,527 | 2,878,811 | libiconv - iconv_open() default behavior? | According to the documentation of iconv_open() over: http://www.gnu.org/software/libiconv/documentation/libiconv/iconv_open.3.html
"//TRANSLIT" means that when a character cannot be represented in the target character set, it can be approximated through one or several characters.
and:
"//IGNORE" means that characters t... | The default behaviour is to stop conversion and return -1, with errno set to EILSEQ if an character that cannot be converted to the target character set is encountered.
(ie. This is different to both //TRANSLIT and //IGNORE).
|
2,874,540 | 2,875,651 | How to query a CGI based webserver from an app written in MFC (MSVC 2008) and process the result? | I am exploring the option of querying a web-page, which has a CGI script running on its end, with a search string (say in the form of http://sw.mycompany.com/~tools/cgi-bin/script.cgi?param1=value1¶m2=value2¶m3=value3 ), and displaying the result on my app (after due processing of course). My app is written in ... | CInternetSession internet_session;
CHttpConnection* connection = NULL;
CHttpFile* file = NULL;
TRY {
connection = internet_session.GetHttpConnection("www.somehost.com", (INTERNET_PORT)80);
// URI needs to be a relative path here
file = connection->OpenRequest(CHttpConnection::HTTP_VERB_GET, "/some/file/on/... |
2,874,576 | 2,874,584 | Simple map<> instantiation, I can't compile, please help | Why I can't compile this code?
#include <map>
using namespace std;
class MyTest {
template<typename T> void test() const;
};
template<typename T> void MyTest::test() const {
map<string, T*> m;
map<string, T*>::const_iterator i = m.begin();
}
My compiler says:
In member function ‘void MyTest::test() const’:... | You have a dependent name, you need to append typename to the const_iterator because its type depends on the type of T.
template<typename T> void MyTest::test() const {
map<string, T*> m;
typename map<string, T*>::const_iterator i = m.begin();
}
C++ faq on depenent names
|
2,874,589 | 2,874,686 | Unoverloadable C++ operators | What operators can not be overloaded in C++?
| From Wikipedia:
Operator Name Syntax
Bind pointer to member by reference a.*b
Member a.b
Scope resolution a::b
Size of sizeof(a)
Ternary a ? b : c
Type identification ... |
2,874,824 | 2,874,867 | Using C++ classes in .NET | I have a set of classes that I've written in C++ for a code base that will run in Linux commandline. They primarily use the STL and no fancy features of the language. They've been tested, and work.
I need to write a GUI app for the .NET framework that does things using logic I've written in those classes, but run on ... | Yes, you can - you can use C++ code (as long as it doesn't depend on Linux-specific functionality) in a .NET application. C++/CLI is a superset of C++, offering access to the .NET managed classes and other features. Take your existing code, build it as a DLL (managed if you can, unmanaged if not), then create the GUI p... |
2,875,333 | 2,875,540 | Can any function be a deleted-function? | The working draft explicitly calls out that defaulted-functions must be special member functions (eg copy-constructor, default-constructor, etc, (§8.4.2.1-1)). Which makes perfect sense.
However, I don't see any such restriction on deleted-functions(§8.4.3). Is that right?
Or in other words are these three examples v... | The C++0x spec (§[dcl.fct.def.delete]) doesn't deny such constructs, and g++ 4.5 recognize all 3 of them.
x.cpp: In function 'int main()':
x.cpp:4:8: error: deleted function 'int Foo::bar(int)'
x.cpp:21:11: error: used here
x.cpp:9:5: error: deleted function 'int baz(int)'
x.cpp:22:2: error: used here
x.cpp:9:5: error:... |
2,875,536 | 2,875,626 | huge C file debugging problem | I have a source file in my project, which has more than 65,536 code lines (112,444 to be exact). I'm using an "sqlite amalgamation", which comes in a single huge source file.
I'm using MSVC 2005. The problems arrives during debugging. Everything compiles and links ok. But then when I'm trying to step into a function wi... | According to a MS moderator, this is a known issue with the debugger only (the compiler seems to handle it fine as you pointed out). There is apparently no workaround, other than using shorter source files. See official response to very similar question here
|
2,875,580 | 2,875,627 | Variable arguments and function overloading | I am trying to improve SQLite error handling in an existing C++ program. I have a custom type SQLiteException, and I want to write a macro to print the line number, file name, and error messages from SQL.
I have the following functions defined:
LogMessage(LPCTSTR message); // Does the real work. Appends a timestamp t... | Well, these are variable arguments - meaning that zero arguments is also acceptable. In that case the compiler will not be able to pick between your first and third function as their first argument is identical.
|
2,875,740 | 2,875,769 | Pointing class property to another class with vectors | I've got a simple class, and another class that has a property that points to the first class:
#include <iostream>
#include <vector>
using namespace std;
class first{
public:
int var1;
};
class second{
public:
first* classvar;
};
Then, i've got a void that's supposed to point "classvar" to the intended iter... | The problem is that b[0].classvar is a pointer. To access members of a class through a pointer, you must use the -> operator, not ..
The reason b[0].classvar[0].var1 works is because the index operator [] for pointers makes this equivalent to (*(b[0].classvar + 0)).var1. In other words, it adds 0 to the pointer and t... |
2,875,801 | 2,875,822 | Is long long in C++ known to be very nasty in terms of precision? | The Given Problem:
Given a theater with n rows, m seats, and a list of seats that are reserved. Given these values, determine how many ways two friends can sit together in the same row.
So, if the theater was a size of 2x3 and the very first seat in the first row was reserved, there would be 3 different seatings that t... | Unless you're overflowing or underflowing, it definitely sounds like something is wrong with your code. For integral types, there are no precision ambiguities in c or c++
|
2,875,872 | 3,483,744 | gluLookAt alternative doesn't work | I'm trying to calculate a lookat matrix myself, instead of using gluLookAt().
My problem is that my matrix doesn't work. using the same parameters on gluLookAt does work however.
my way of creating a lookat matrix:
Vector3 Eye, At, Up; //these should be parameters =)
Vector3 zaxis = At - Eye; zaxis.Normalize... | I assume you have a right handed coordinate system (it is default in OpenGL).
Try the following code. I think you forgot to normalize up and you have to put "-zaxis" in the matrix.
Vector3 Eye, At, Up; //these should be parameters =)
Vector3 zaxis = At - Eye; zaxis.Normalize();
Up.Normalize();
Vector3 xaxis = Vector3... |
2,875,908 | 2,875,919 | Nested If (x) checks - Better way to write this? | There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes.
For example, I have
if (a)
{
if (a->b())
{
if (a->b()->c())
{
a->b()->c()->DoSomething();
}
}
}
I really don't like the look of this. Is there a way to... | Why would the latter not work?
In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops.
In fact, you could write:
a && a->b() && a->b()->c() && a->b()->c()->DoSomething();
|
2,875,985 | 2,876,025 | C++ - No match for 'operator=' when compiling using GCC | I recently tried building my own shared and weak pointers. Code that compiles using Visual Studio doesn't compile in GCC (4.5.0) with the following error:
main.cpp: In function 'int main()':
main.cpp:18:27: error: no match for 'operator=' in 'wp1 = weak_ptr<int>(((const shared_ptr<int>&)((const shared_ptr<int>*)(& sp1)... | Your assignment operator requires a reference, not a const reference:
weak_ptr& operator= (weak_ptr& p)
However, the expression weak_ptr<int>(sp1) results in a temporary, which can only be converted to a const reference, since it is an rvalue. Think about it this way: you cannot modify the result of an expression, yet... |
2,876,274 | 2,876,353 | C++ OpenGL Window Kit | Besides Qt, GTK, wxWidgets... What are the recommendations for a cross platform, open source GUI framework library that works with OpenGL?
| Its not quite a GUI framework. But GLFW is good for an OpenGL window with some extra features like keyboard and joystick handling.
I found the other framework I was looking for. It is SFML. I only used it briefly but I do remember liking it very much. It does contain a lot of nice extras going a step further than G... |
2,876,357 | 2,876,374 | Determine the line of code that causes a segmentation fault? | How does one determine where the mistake is in the code that causes a segmentation fault?
Can my compiler (gcc) show the location of the fault in the program?
| GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:
gcc program.c -g
Then use gdb:
$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>
Here is a nice tutorial to get you started with GDB.
Where the segfault occurs is generally... |
2,876,413 | 2,876,523 | C++ - gcc-specific warnings | Got the following warning output when using GCC 4.5.0 & MinGW.
Warning: .drectve `-aligncomm:___CTOR_LIST__,2 ' unrecognized
Warning: .drectve `-aligncomm:___DTOR_LIST__,2' unrecognized
What does it mean? I guess it's version-specific, because GCC 4.3.4 under cygwin didn't give that warning on the same project.
If any... | Hmmm, Google does wonders:
GCC failure
Broken on Cygwin
The advice, try reloading and rebuilding GCC or load a prior version.
|
2,876,465 | 2,876,553 | Edit strings vars in compiled exe? C++ win32 | I want to have a few strings in my c++ app and I want to be able to edit them later in the deployed applications (the compiled exe), Is there a way to make the exe edit itself or it resources so I can update the strings value?
The app checks for updates on start, so I'm thinking about using that to algo send the comma... | Another idea is to move the strings into a "configuration" file, such as in XML or INI format.
Modifying the EXE without compilation is hacking and highly discouraged. You could use a hex editor, find the string and modify it. The new text must be have a length less than or equal to the original EXE.
Note, some v... |
2,876,535 | 2,876,678 | Simple and efficient distribution of C++/Boost source code (amalgamation) | My job mostly consists of engineering analysis, but I find myself distributing code more and more frequently among my colleagues. A big pain is that not every user is proficient in the intricacies of compiling source code, and I cannot distribute executables.
I've been working with C++ using Boost, and the problem is t... | There is a utility that comes with boost called bcp, that can scan your source and extract any boost header files that are used from the boost source. I've setup a script that does this extraction into our source tree, so that we can package the source that we need along with our code. It will also copy the boost sou... |
2,876,559 | 2,877,033 | Why is there garbage in my TCHAR, even after ZeroMemory()? | I have inherited the following line of code:
TCHAR temp[300];
GetModuleFileName(NULL, temp, 300);
However, this fails as the first 3 bytes are filled with garbage values (always the same ones though, -128, -13, 23, in that order). I said, well fine and changed it to:
TCHAR temp[300];
ZeroMemory(temp, 300);
GetModuleFi... | ZeroMemory works in terms of bytes, whereas you have an array of 300 TCHARs. This makes me assume you're working with widechar (not multi-byte) compilation option.
You should use:
ZeroMemory(temp, 300 * sizeof(TCHAR));
Or in your specific case:
ZeroMemory(temp, sizeof(temp));
However be careful with the latter. It's ... |
2,876,641 | 2,880,062 | So can unique_ptr be used safely in stl collections? | I am confused with unique_ptr and rvalue move philosophy.
Let's say we have two collections:
std::vector<std::auto_ptr<int>> autoCollection;
std::vector<std::unique_ptr<int>> uniqueCollection;
Now I would expect the following to fail, as there is no telling what the algorithm is doing internally and maybe making inter... | I think it's more a question of philosophy than technic :)
The underlying question is what is the difference between Move and Copy. I won't jump into technical / standardista language, let's do it simply:
Copy: create another identical object (or at least, one which SHOULD compare equal)
Move: take an object and put i... |
2,876,720 | 2,879,322 | C++ library to load Excel (.xls) files | I'm looking for a free C++ library that can load .xls files in both Windows and Linux. If I had to make a choice, Linux would be the bare minimum.
I've tried LibXL, but got this amazing error:
"can't read more cells in trial version"
So now I'm on the hunt for a free version :), unfortunately xlsLib doesn't provide th... | We have had success with: ExcelFormat
|
2,877,084 | 2,877,116 | Why does this code crash? | The following code causes a stack overflow but I don't see why...
int _tmain(int argc, _TCHAR* argv[])
{
cout << "start";
char bmp[1024][768][3];
for (int p = 0; p < 9000; ++p)
{
for(int i = 0; i < 1024; ++i)
{
for(int j = 0; j < 768; ++j)
{
bmp[i][j][0] = 20;
}
... | I would say it is likely because 1024 * 768 * 3 is 2,359,296 which is probably too big for the local stack.
You should instead allocate that on the heap.
|
2,877,175 | 2,877,601 | method chaining including class constructor | I'm trying to implement method chaining in C++, which turns out to be quite easy if the constructor call of a class is a separate statement, e.g:
Foo foo;
foo.bar().baz();
But as soon as the constructor call becomes part of the method chain, the compiler complains about expecting ";" in place of "." immediately after... | You have forgotten the actual name for the Foo object. Try:
Foo foo = Foo().bar().baz();
|
2,877,220 | 2,877,489 | Is typeid of type name always evaluated at compile time in c++? | I wanted to check that typeid is evaluated at compile time when used with a type name (ie typeid(int), typeid(std::string)...).
To do so, I repeated in a loop the comparison of two typeid calls, and compiled it with optimizations enabled, in order to see if the compiler simplified the loop (by looking at the execution ... | I don't really know the answer to your question but if you use is_same<> metafunction instead of typeid you might get more desirable results. Even if you don't have access to this metafunction, it is very easy to write one:
template < typename T1, typename T2 >
struct is_same
{
enum { value = false }; // is_same re... |
2,877,234 | 2,877,285 | How to have transactions on objects | How I can imitate transactions on objects. For example, I want to delete the item from one collection and then add the same item to other collection as an atomic action. It is possible to do a lot of checks when something failed and to roll back everything but this is annoying.
Is there any technique (no difference wha... | For small, simple objects, you can use a copy-modify-swap idiom. Copy the original object. Make the changes. If all the changes succeeded, swap the copy with the original. (In C++, swap is typically efficient and no-fail.) The destructor will then clean up the original, instead of the copy.
In your case, you'd cop... |
2,877,295 | 2,877,357 | Get OS in c++ win32 for all versions of win? | How to get the OS version for all windows, at least the name for win95,98,me,xp,vista,7?
Im using visual c++ 2010 and I want to include this feature in a pure win32 app.
| Use GetVersionEx
http://msdn.microsoft.com/en-us/library/ms724451%28v=VS.85%29.aspx
|
2,877,319 | 2,877,498 | Why doesn't luazip extract files when called from c++ application? | I have a c++ application that interfaces with lua files. I have a lua file that extracts zip files, which works when I run it using SciTe or the Lua command line. But when I try to run it from a c++ application it doesn't seem to work.
require "zip"
function ExtractZipFiles(zipFilename, destinationPath)
zipFile, ... | First of all check for errors:
if (luaL_dofile(L, "ExtractZipFiles.lua"))
{
std::cerr << "Lua error : " << lua_tostring(L, -1) << std::endl;
}
Apart from that, my guess is that Lua can't locate the zip module -- check your package paths settings, read about require in the Lua manual.
In general, you need to check ... |
2,877,687 | 2,877,712 | Visual Studio C++: Seeing the ASM code? | I'd like to see all the asm produced by Visual Studio C++ to learn a bit about ASM, compilers, etc. I know with GCC, you can do it with the -S argument, but not in VS. How do I go about doing this?
| The easiest way to do this is to start your program in the integrated debugger, then turn on the assembly language view. This shows the assembly language interleaved with your original source code.
Back when I used VS, this was Alt+F7 or something but it's probably changed. The advantage of doing this (over using -S eq... |
2,877,961 | 2,879,166 | How do you measure the effect of branch misprediction? | I'm currently profiling an implementation of binary search. Using some special instructions to measure this I noticed that the code has about a 20% misprediction rate. I'm curious if there is any way to check how many cycles I'm potentially losing due to this. It's a MIPS based architecture.
| Look it up in the docs for your CPU. If you can't find this information specifically, the length of the CPU's pipeline is a fairly good estimate.
Given that it's MIPS and it's a 300MHz system, I'm going to guess that it's a fairly short pipeline. Probably 4-5 stages, so a cost of 3-4 cycles per mispredict is probably a... |
2,878,073 | 2,878,338 | Where are the function address literals in c++? | UPDATE: After some additional reading, what I really wanted was guaranteed early binding (which should translated to an immediate call for non-virtual functions and non-PIC code), which can be done by passing a (member) function as a template parameter. The problem I had was that gcc < 4.5 and icc 11.1 can generate som... | If you use a function pointer type in your template and instantiate it with a fixed function, then the compiler should use a direct call for that function pointer call.
|
2,878,259 | 2,878,320 | Texture coordintes for a polygon and a square texture | basically I have a texture. I also have a lets say octagon (or any polygon). I find that octagon's bounding box. Let's say my texture is the size of the octagon's bounding box. How could I figure out the texture coordinates so that the texture maps to it. To clarify, lets say you had a square of tin foil and cut the oc... | See Texture mapping an NGon?.
|
2,878,401 | 2,878,687 | C++ class is not recognizing string data type | I'm working on a program from my C++ textbook, and this this the first time I've really run into trouble. I just can't seem to see what is wrong here. Visual Studio is telling me Error: identifier "string" is undefined.
I separated the program into three files. A header file for the class specification, a .cpp file ... | You have forgotten to #include the string header and you need to fully qualify your usage of string to std::string, the amended code should be.
// File Car.h -- Car class specification file
#ifndef CAR_H
#define CAR_H
#include <string>
class Car
{
private:
int year;
std::string make;
int speed;
public:
... |
2,878,933 | 2,879,122 | Unable to create unmanaged object using new keyword in managed C++ | I've created a class with a boost::unordered_map as a member,
Linkage.h
#ifndef LINKAGE_H
#define LINKAGE_H
#include <boost/unordered_map.hpp>
class Linkage
{
private:
boost::unordered_map<int, int> m_IOMap;
public:
....
};
Linkage.cpp
#include "stdafx.h"
... // methods
and in the managed side of C++,... | Eventually this works when I explicitly instantiate it inside the constructor:
#include "stdafx.h"
Linkage::Linkage()
{
template boost::unordered_map<int, int>;
}
|
2,879,055 | 2,879,073 | How to think in Python after working in C++? | I'm brand new to Python and trying to learn it by replicating the following C++ function into python
// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
void equivalentWords(vector <string> words, ofstream & outFile) {
outFile << "Equivalent ... | Keeping things simple, this is O(N) complexity and should be sufficient if you don't have GBs of word data. Note that set() and dict() basically is a hashed index (free and builtin!).
index = {}
for word, s_word in words:
index[s_word] = index.get(s_word, []) + [word]
for similar_words in index.values():
print... |
2,879,145 | 2,879,164 | C++ performance, for versus while | In general (or from your experience), is there difference in performance between for and while loops?
What if they are doubly/triply nested?
Is vectorization (SSE) affected by loop variant in g++ or Intel compilers?
Thank you
| Here is a nice paper on the subject.
|
2,879,222 | 2,879,263 | Using a macro for fstream file input as part of a class | I have a class that processes a file, and as part of the constructor with one argument I want to input a file using fstream.
I basically want it do something like this
class someClass{
public:
someClass(char * FILENAME)
{
fstream fileToProcess;
fileToProcess.open(<FILENAME>, fstre... | You don't need a macro, and you don't have to explicitly call open.
using std::fstream;
class someClass
{
fstream fileToProcess;
public:
someClass(char * filename)
: fileToProcess(filename, fstream::in | fstream::out | fstream::app)
{
}
};
|
2,879,438 | 2,928,462 | Integrate code generation with eclipse c++ build | I am using Eclipse for C++ development on windows. I have also written a code generator that take an xml file and produces several C++ files. The project I am working on is currently setup to use the internal builder. What I would like to do is to run the code generator as part of the build process.
My problem is th... | You can add a Builder to your project.
|
2,879,537 | 2,879,610 | How to use fgets if you don't know the number of characters to be read? | I need to read a file and send the text from it to a string so I can parse it. However, the program won't know exactly how long the file is, so what would I do if I wanted to use fgets(), or is there a better alternative?
Note:
char *fgets(char *str, size_t num, FILE *stream);
| Don't forget that fgets() reads a line at a time, subject to having enough space.
Humans seldom write lines longer than ... 80, 256, pick a number ... characters. POSIX suggests a line length of 4096. So, I usually use:
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp))
{
...process line...
}
If you ... |
2,879,548 | 2,879,851 | Is it appropriate to set a value to a "const char *" in the header file | I have seen people using 2 methods to declare and define char *.
Medhod 1: The header file has the below
extern const char* COUNTRY_NAME_USA = "USA";
Medhod 2:
The header file has the below declaration:
extern const char* COUNTRY_NAME_USA;
The cpp file has the below definition:
extern const char* COUNTRY_NAME_USA = ... | The first method is indeed wrong, since it makes a definition of an object COUNTRY_NAME_USA with external linkage in the header file. Once that header file gets included into more than one translation unit, the One Definition Rule (ODR) gets violated. The code will fail to compile (more precisely, it will fail to link)... |
2,879,555 | 2,879,561 | C++ Standard Library: How to write wrappers for cout, cerr, cin and endl? | I do not like using namespace std, but I am also tired of having to type std:: in front of every cout, cin, cerr and endl. So, I thought of giving them shorter new names like this:
// STLWrapper.h
#include <iostream>
#include <string>
extern std::ostream& Cout;
extern std::ostream& Cerr;
extern std::istream& Cin;
ext... | Why not
using std::cin;
using std::cout;
and so on? Then in your code you can use cin, cout, and so on, without accidentally injecting all of the rest of the std namespace into your code.
|
2,879,665 | 2,880,263 | GTKMM/C++ Window Event on losing/regaining focus? | How can I call a function whenever my GTKMM app loses or regains focus?
| Connect handlers to the window's focus-in-event and focus-out-event.
|
2,880,248 | 2,880,433 | std::string.resize() and std::string.length() | I'm relatively new to C++ and I'm still getting to grips with the C++ Standard Library. To help transition from C, I want to format a std::string using printf-style formatters. I realise stringstream is a more type-safe approach, but I find myself finding printf-style much easier to read and deal with (at least, for th... | With the current standard (the upcomming standard differs here) there is no guarantee that the internal memory buffer managed by the std::string will be contiguous, or that the .c_str() method returns a pointer to the internal data representation (the implementation is allowed to generate a contiguous read-only block f... |
2,880,578 | 2,880,603 | pass by const reference of class | void foo(const ClassName &name)
{
...
}
How can I access the method of class instance name?
name.method() didn't work. then I tried:
void foo(const ClassName &name)
{
ClassName temp = name;
... ....
}
I can use temp.method, but after foo was executed, the original name screwed up, any idea?
BTW, the membe... | If I understand you correctly, you want to call name.method() inside foo() and the compiler doesn't let you. Is ClassName::method() a non-const method by any chance? Since name is declared as a const parameter to foo(), you can only call const functions on it.
Update: if ClassName::method() is non-const, but does not a... |
2,880,670 | 2,880,743 | Can I add Boost source+header files to my own (Open Source) project? | Is it allowed by the Boost License to just add the source code of the stuff I need to my project (accompanied by the license of course?). I couldn't find any "descriptive" confirmation. I would have seperate Include/boost and Source/boost directories for easy access.
PS: Seeing as boost::filesystem is going into C++0x ... | Yes you can do that. The license is very liberal. The only condition is that if you redistribute your software in source form you need to include a complete copy of the license.
|
2,880,852 | 2,880,872 | How to simulate Func<T1, T2, TResult> in C++? | In C#, I use Func to replace Factories. For example:
class SqlDataFetcher
{
public Func<IConnection> CreateConnectionFunc;
public void DoRead()
{
IConnection conn = CreateConnectionFunc(); // call the Func to retrieve a connection
}
}
class Program
{
public void CreateConnection()
... | Use either std::tr1::function<IConnection*()> or boost::function<IConnection*()> as the equivalent of Func<IConnection>.
When you come to assign the function, you'll need to bind a object and a function together;
f.CreateConnectionFunc = this.CreateConnection;
would become
f.CreateConnectionFunc = std::tr1::bind(&Prog... |
2,880,881 | 2,880,904 | Unresolved symbol when inheriting interface | It's late at night here and I'm going crazy trying to solve a linker error.
If I have the following abstract interface:
class IArpPacketBuilder
{
public:
IArpPacketBuilder(const DslPortId& aPortId);
virtual ~IArpPacketBuilder();
// Other abstract (pure virtual methods) here...
};
and I instantiate it lik... | You have only declared the constructor and destructor of IArpPacketBuilder, not defined them. The linker needs the definitions too. Note that C++ has no concept of abstract interface - IArpPacketBuilder is a plain old class which happens to contain some pure virtual methods, thus making its direct instantiation impossi... |
2,880,903 | 2,881,987 | Simple string parsing with C++ | I've been using C++ for quite a long time now but nevertheless I tend to fall back on scanf when I have to parse simple text files. For example given a config like this (also assuming that the order of the fields could vary):
foo: [3 4 5]
baz: 3.0
I would write something like:
char line[SOME_SIZE];
while (fgets(line, ... | This is a try using only standard C++.
Most of the time I use a combination of std::istringstream and std::getline (which can work to separate words) to get what I want. And if I can I make my config files look like:
foo=1,2,3,4
which makes it easy.
text file is like this:
foo=1,2,3,4
bar=0
And you parse it like this... |
2,880,912 | 2,884,119 | performance: is it better to read all files once, or use b::fs functions over and over again? | I'm conflicted between a "read once, use memory+pointers to files" and a "read when necessary" approach. The latter is of course much easier (no additional classes needed to store the whole dir structure), but IMO it is slower? I'm trying to list the filenames and relative paths (so the compiler can do with them what i... | You can safely assume that the operating system will cache the directory contents anyway, so that access through file system APIs will come down to memory operations.
So the answer to your question "is it faster?" is likely "No, not measurably".
OTOH, consider that a directories contents can change over time, even in v... |
2,880,981 | 2,880,991 | Get a char from a CString | I have created a function that has as input a char szMyChar; (using it in a switch statement).
Now I have a CString having just a char, lets say CString strString = "A";
An option to call the function could be:
if (strString == "A")
CallMyFunc('A');
though it is clumsy. I tried atoi (returns 0) and casting though nei... | Either I'm not quite understanding what you're asking, or it's as simple as:
CallMyFunc(strString[0]);
See Accessing Individual Characters in a CString for more information.
|
2,881,102 | 2,881,234 | Is the use of union in this matrix class completely safe? | Unions aren't something I've used that often and after looking at a few other questions on them here it seems like there is almost always some kind of caveat where they might not work. Eg. structs possibly having unexpected padding or endian differences.
Came across this in a math library I'm using though and I wondere... | Although I do exactly the same in my Matrix-class I think this is implementation dependent, reading the standard to the letter:
Standard 9.5.1:
In a union, at most one of the data
members can be active at any time,
that is, the value of at most one of
the data members can be stored in a
union at any time. [Not... |
2,881,184 | 2,881,212 | How to find where program crashed | I have a program that crashes (attempting to read a bad memory address) while running the "release" version but does not report any problems while running the "debug" version in the visual studio debugger.
When the program crashes the OS asks if I'd like to open up the debugger, and if I say yes then I see an arrow poi... | You need to build your program with Debug info enabled (which you can do even for release builds) and that debug info (*.pdb files) must be accessible to the debugger (just copy it beside the executable).
The VS should be able to show you the source, stack and everything else.
|
2,881,239 | 2,881,415 | How can I avoid encoding mixups of strings in a C/C++ API? | I'm working on implementing different APIs in C and C++ and wondered what techniques are available for avoiding that clients get the encoding wrong when receiving strings from the framework or passing them back. For instance, imagine a simple plugin API in C++ which customers can implement to influence translations. It... | You could pass arround a std::pair instead of a char*:
struct utf8_tag_t{} utf8_tag;
std::pair<const char*,utf8_tag_t> getTranslatedWord(std::pair<const char*,utf8_tag_t> englishWord);
The generated machine code should be identical on a decent modern compiler that uses the empty base class optimization for std::pair.
... |
2,881,268 | 2,881,314 | How a member func can know *programmatically* the 'name of the object' that is calling it? | Let say we have a class MyClass that has and a memberfunc().
An object is created for this MyClass, say ObjA.
i.e MyClass ObjA;
ObjA calls memberfunc().
Can we get this name 'ObjA' inside memberfunc() programatically?
Note: I know how to get the type of the object, i.e 'MyClass', using RTTI (Run-Time Type Identific... | There are several issues here:
Objects don't call anything, code does.
Objects don't have a name. An object is usually assigned to a variable, often to more than one variable, often to no variable at all, such as an array element.
Getting access to the call stack might give you some idea of the calling class that owns... |
2,881,305 | 2,881,463 | Internal class and access to external members | I have question with this same title here but now as I'll present in code below this seems to behave in the opposite way to the way explained to me in my first question with the same title. Ok code:
class LINT_rep
{
private:
char* my_data_; //stores separately every single digit from a number
public:
class Iter... | Access rights for nested classes to members of the enclosing classes are changing in the upcoming C++0x standard. In the current standard, 11.8 says:
The members of a nested class have no special access to members of an enclosing class
In the draft for C++0x, this changes to
A nested class is a member and as such ha... |
2,881,454 | 2,881,745 | "Unhandled exception"/"Access violation writing location" error with referenced array pointers | I'm trying to fill a pointer matrix with values from a text file. It's a double pointer to a simple struct with 2 ints, time and tons.
void get_changes(change** &c){
ifstream file("change_data_time.prn"); //data file, time only, size is the same as tons
string line, var; //string placeholders... | I would rewrite the code to get rid of the manual memory management around change** c.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
struct MaxtrixElement
{
double time;
};
std::istream& operator >> (std::istream& in, MaxtrixElement& dest)
{
double d;
// er... |
2,881,517 | 2,881,537 | Uses for the capacity value of a string | In the C++ Standard Library, std::string has a public member function capacity() which returns the size of the internal allocated storage, a value greater than or equal to the number of characters in the string (according to here). What can this value be used for? Does it have something to do with custom allocators?
| You are more likely to use the reserve() member function, which sets the capacity to at least the supplied value.
The capacity() member function itself might be used to avoid allocating memory. For instance, you could recycle used strings through a pool, and put each one in a different size bucket based on its capacity... |
2,881,624 | 2,882,077 | C++ - Totally suspend windows application | I am developing a simple WinAPI application and started from writing my own assertion system.
I have a macro defined like ASSERT(X) which would make pretty the same thing as assert(X) does, but with more information, more options and etc.
At some moment (when that assertion system was already running and working) I rea... | It is important to understand how Windows UI programs work, to answer this question.
At the core of the Windows UI programming model is of course "the message" queue". Messages arrive in message queues and are retrieved using message pumps. A message pump is not special. It's merely a loop that retrieves one message at... |
2,882,014 | 2,882,021 | Is there any way to convert C++ program into ASP.NET? | Is there any way to convert C++ program into ASP.NET?
| No there is not.
You have some options though:
You can create a managed C++ / CLI DLL from your C++ code.
You can create a C++ Win32 DLL and use p/invoke to import the DLL functions into your ASP.NET page.
Re-write your code in C# or another .Net language.
|
2,882,062 | 2,882,145 | Why does compiler complain when I try to convert to a base-class? | BaseClass.h
class BaseClass
{
...
};
SubClass.h
#include "BaseClass.h"
class SubClass : public BaseClass
{
...
};
MyApp.h
class BaseClass;
class SubClass;
class MyApp
{
SubClass *pObject;
BaseClass *getObject()
{
return pObject;
}
};
I get a compiler error: error C2440: 'return' : cannot convert from 'SubC... | In "MyApp.h", you only have forward declarations of the classes, so it's not known that one derives from the other. You will need to include the "SubClass.h" before the body of getObject(); either include it from "MyApp.h", or move the body of getObject() into a source file and include it from there.
|
2,882,068 | 2,882,083 | Do you recommend Enabling Code Analysis for C/C++ on Build? | I'm using Visual Studio 2010, and in my C++/CLI project there are two Code Analysis settings:
Enable Code Analysis on Build
Enable Code Analysis for C/C++ on Build
My question is about the second setting.
I've enabled it and it takes a long time to run and it doesn't find much.
Do you recommend enabling this feature?... | Never did anything for me. In theory, it's supposed to help catch logical errors, but I've never found it to report anything.
|
2,882,177 | 2,882,371 | C++ - Dialog box question | This is a more concrete question that is connected with my previous one.
I have an application that uses a timer. The code is written the way the my WM_TIMER handler call a DialogBoxParam(...) with some custom message handler (let's call it DlgProc).
This is done somewhat the following way:
case WM_TIMER:
{
... | 1) You should disable the timer after the first WM_TIMER signal is caught if you want to show only one single dialog box. You can do this using KillTimer().
2) Windows wants to keep the GUI up-to-date. Whenever a region on the screen should be updated, it is invalidated using InvalidateRect or InvalidateRgn. Now, for e... |
2,882,706 | 2,882,819 | How can I write a power function myself? | I was always wondering how I can make a function which calculates the power (e.g. 23) myself. In most languages these are included in the standard library, mostly as pow(double x, double y), but how can I write it myself?
I was thinking about for loops, but it think my brain got in a loop (when I wanted to do a power w... | Negative powers are not a problem, they're just the inverse (1/x) of the positive power.
Floating point powers are just a little bit more complicated; as you know a fractional power is equivalent to a root (e.g. x^(1/2) == sqrt(x)) and you also know that multiplying powers with the same base is equivalent to add their ... |
2,882,721 | 2,882,745 | how to Clean up(destructor) a dynamic Array of pointers? | Is that Destructor is enough or do I have to iterate to delete the new nodes??
#include "stdafx.h"
#include<iostream>
using namespace std;
struct node{
int row;
int col;
int value;
node* next_in_row;
node* next_in_col;
};
class MultiLinkedListSparseArray {
private:
char ... | If you inserted object pointers on those arrays(initially you are initializing them to NULL), you need to iterate them to delete each single object.
As always, one delete for each new.
|
2,882,763 | 2,882,813 | C++ .NET DLL vs C# Managed Code ? (File Encrypting AES-128+XTS) | I need to create a Windows Mobile Application (WinMo 6.x - C#) which is used to encrypt/decrypt files. However it is my duty to write the encryption algorithm which is AES-128 along with XTS as the mode of operation. RijndaelManaged just doesn't cut it :( Very much slower than DES and 3DES CryptoServiceProviders :O
I ... | Writing a "managed" program will have equal performance in C++ or C# or VB, since they all compile to IL anyway.
I don't know, but if you write an unmanaged C++ class library and invoke it from managed C# app you may loose some performance during the p/invoke but your speed increase (from going unmanaged) may be enoug... |
2,882,957 | 2,883,026 | Dynamic stack allocation in C++ | I want to allocate memory on the stack.
Heard of _alloca / alloca and I understand that these are compiler-specific stuff, which I don't like.
So, I came-up with my own solution (which might have it's own flaws) and I want you to review/improve it so for once and for all we'll have this code working:
/*#define allocate... | Sorry, but you'd be better off using alloca than doing that kind of stuff. Not only it's x86 specific, but also, it'll probably give unexpected results if compiled with optimizations on.
alloca is supported by many compilers, so you shouldn't be running into problems anytime soon.
|
2,883,164 | 2,895,561 | OpenSSL certificate lacks key identifiers | How do i add these sections to certificate (i am manualy building it using C++).
X509v3 Subject Key Identifier:
A4:F7:38:55:8D:35:1E:1D:4D:66:55:54:A5:BE:80:25:4A:F0:68:D0
X509v3 Authority Key Identifier:
keyid:A4:F7:38:55:8D:35:1E:1D:4D:66:55:54:A5:BE:80:25:4A:F0:68:D0
Curently my code build... | Found solution - add these lines to code
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_subject_key_identifier, "hash");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_authority_key_identifier, "keyid:always");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
|
2,883,353 | 2,883,458 | Constant embedded for loop condition optimization in C++ with gcc | Will a compiler optimize tihs:
bool someCondition = someVeryTimeConsumingTask(/* ... */);
for (int i=0; i<HUGE_INNER_LOOP; ++i)
{
if (someCondition)
doCondition(i);
else
bacon(i);
}
into:
bool someCondition = someVeryTimeConsumingTask(/* ... */);
if (someCondition)
for (int i=0; i<HUGE_IN... | It's possible that the compiler might write the code as you did, but I've never seen such optimization.
However there is something called branch prediction in modern CPU. In essence it means that when the processor is asked to execute a conditional jump, it'll start to execute what is judged to be the likeliest branch ... |
2,883,810 | 2,883,977 | What effect does static const have on a namespace member | // MyClass.h
namespace MyNamespace {
static const double GasConstant = 1.987;
class MyClass
{
// constructors, methods, etc.
};
}
I previously had GasConstant declared within the MyClass declaration (and had a separate definition in the source file since C++ does not support const initialization of non-... | The use of static at namespace scope is was* deprecated in C++. It would normally only ever be seen in a source file, where its effect is to make the variable local to that source file. That is, another source file can have a variable of exactly the same name with no conflict.
In C++, the recommended way to make variab... |
2,883,829 | 2,884,710 | Template compiling errors on iPhone SDK 3.2 | I'm porting over some templated code from Windows and I'm hitting some compiler differences on the iPhone 3.2 SDK.
Original code inside a class template's member function is:
return BinarySearch<uint32, CSimpleKey<T> >(key);
where BinarySearch is a method inherited from another template.
This produces the following er... | If CSimpleTable is the base class, you need to qualify your call with that base class name or alternatively with this. But since both of these depend on the template parameters, the compiler cannot lookup what the name BinarySearch means. It could be a static integer constant, which you compare against something else, ... |
2,883,841 | 2,886,943 | embedded dev. question - how to break free from a faulty serial port opening? | Under WindowsCE, C++ project, I'm trying to work with devices connected via both "real" serial ports and/or serial-to-usb wrappers ("virtual" serial ports); my problem is - when I try to open the port, if something goes wrong, the function never returns and the system goes into some non-responsive state and has to be e... | Why not perform the open in another thread? There's no reason to do anything else in that thread - just open the port and you can use the handle for the opened port in any other thread in your process.
However, I'm not sure what's so screwed up that your CreateFile() call seems to hang - I wonder if this happens even ... |
2,884,097 | 2,884,140 | Optimal (Time paradigm) solution to check variable within boundary | Sorry if the question is very naive.
I will have to check the below condition in my code
0 < x < y
i.e code similar to if(x > 0 && x < y)
The basic problem at system level is - currently, for every call (Telecom domain terminology), my existing code is hit (many times). So performance is very very critical, Now, I... | As always, profile first, optimize later. But, given that this is actually an issue, these could be things to look into:
"Unsigned and greater than zero" is the same as "not equal to zero", which is usually about as fast as a comparison gets. So a first optimization would be to do x != 0 && x < y.
Make sure that you d... |
2,884,170 | 2,884,211 | cast operator to base class within a thin wrapper derived class | I have a derived class that's a very thin wrapper around a base class. Basically, I have a class that has two ways that it can be compared depending on how you interpret it so I created a new class that derives from the base class and only has new constructors (that just delegate to the base class) and a new operator=... | Since your Derived is derived from Base publically, your Derived is already convertible to Base &. There's no need to implement anything extra.
Moreover, when it comes to conversion operator itself, whether you are doing it right or wrong is a moot question, since your conversion operator will never be used anyway. Th... |
2,884,172 | 2,884,242 | Algorithm for dividing very large numbers | I need to write an algorithm(I cannot use any 3rd party library, because this is an assignment) to divide(integer division, floating parts are not important) very large numbers like 100 - 1000 digits. I found http://en.wikipedia.org/wiki/Fourier_division algorithm but I don't know if it's the right way to go. Do you h... | Knuth, Donald, The Art of Computer Programming, ISBN 0-201-89684-2, Volume 2: Seminumerical Algorithms, Section 4.3.1: The Classical Algorithms
|
2,884,361 | 2,884,371 | How to templatize the container type in a function declaration? | I want to write a function that accepts any container holding strings. Something like this:
template <typename Container> void foo(Container<string>& stuff);
But this isn't the right syntax. What's the right syntax?
| You need a template template parameter:
template < template <typename> class Container> void foo (Container<string>& stuff);
|
2,884,797 | 2,885,843 | SWIG: Throwing exceptions from Python to C++ | We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code in our Python code here, here, here, and even on ... | (C)Python is written in C. It seems that it could be bad to throw exceptions "through" the interpreter.
My feeling is that it's probably safest to return a token of some sort from your API that can create an exception via a factory.
That's basically what we do here, although we're using C# instead of Python to generat... |
2,884,814 | 2,884,907 | Is using a C++ "Virtual Constructor" generally considered good practice? | Yes i know the phrase "virtual constructor" makes no sense but i still see articles like this
one: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=184
and i'v heard it mentioned as a c++ interview.
What is the general consensus?
Is a "Virtual Constructor" good practice or something to be avoided comple... | All the author has done is implement prototyping and cloning. Both of which are powerful tools in the arsenal of patterns.
You can actually do something a lot closer to "virtual constructors" through the use of the handle/body idiom:
struct object
{
void f();
// other NVI functions...
object(...?);
object(ob... |
2,885,117 | 2,885,140 | How do you stop in TotalView after an MPI Error? | I am using TotalView and am getting an MPI_Error. However, Totalview does not stop on this error and I can't find where it is occurring. I believe this also applies to GDB.
| Define an MPI_ErrHandler. It gets called in place of the default MPI handler and you can set a breakpoint there. Suggestions welcome on how to get it to print the same thing as the MPI error, or better yet, more information.
MPIErrorHander.hpp:
#define MPIERRORHANDLER_HPP
#ifdef mpi
#include <stdexcept>
#include <str... |
2,885,121 | 2,885,155 | How to create a step by step wizard in C++ (with unmanaged code) in Visual Studio 2010 | I would like to build a small wizard in C++ with no dependencies on any framework.
Apparently, is really simple, but I don't know where to start. Can you point me to good information (tutorials, etc) on it. Should I use MFC Application or a Win32 project? Is there any step by step guide ?
I'm using VS 2010. The major... | Look up Property Sheets in MFC http://msdn.microsoft.com/en-us/library/cfs4wk4e%28VS.80%29.aspx
|
2,885,132 | 2,885,201 | Multi-argument template functions, overloading and ambiguity errors | Lets say I'm writing a some kind of conversion operator, and I want to use it like that:
SomeType a;
AnotherType b = conv<AnotherType>(a);
First, I write the base (default) function:
template <typename T, typename U>
inline T conv(const U& a)
{
return T(a);
}
Full specialization (or a non-template overload) is no... | Implement the body in a class template and then you can partially specialize:
template < typename T, typename U >
struct convert
{
static T apply(U const& u) { return T(u); }
};
template < typename T, typename U >
T conv(U const& u) { return convert<T,U>::apply(u); }
template < typename T >
struct convert<Point<T>, ... |
2,885,244 | 2,885,258 | C++ How do I give a member variable in an abstract class a default value? | In the header, I'm defining bool isActive. In classes derived from this one, I would like to make isActive false by default. I tried doing this by adding
AbstractClass::isActive = false;
to the cpp file, but that causes the error "Expected constructor, destructor, or type conversion before '=' token."
| Initialize it in the class' constructor:
class AbstractClass {
bool isActive;
AbstractClass() : isActive(false) {
}
// ...
};
That the class contains abstract methods doesn't stop it from having a constructor that is used to initialize its member variables.
|
2,885,302 | 2,885,345 | Getting a type for a template instantiation? | I have the following situation:
I have a object of type MyClass, which has a method to cast itself to its base class. The class includes a typedef for its base class and a method to do the upcast.
template <class T, class B>
class BaseClass;
template <class T>
class NoAccess;
template <class T>
class MyClass : public... | You can define a factory function to use type deduction:
template< class Y >
Operator<Y> create_operator( Y &y ) {
return Operator<Y>( y );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.