question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,730,190
4,730,271
Raw Input an alternative keyboard hook?
Quick question -- I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it. For example I am using RAWINPUTDEVICE rid[1]; rid[0].usUsagePage = 0x01; rid[0].usUsage = 0x06; rid[0].hwndTarget = hWnd; rid[0].dwFlags = 0; RegisterRawInputDevices(rid, 1, sizeof(...
A Windows hook is mechanism that one can use to intercept events before they reach an application. Filter functions (functions that receive events) are classified according to the event type. If one wants to attach to a Windows hook, the filter function has to be installed using SetWindowsHookEx. I have to mention that...
4,730,312
4,730,480
How would one implement a variable sized cache object to reduce memory allocations in C++?
Before the performance people tear my head off: yes, I have done profiling before asking this :) I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course ...
But first, read this article by Andrei Alexandrescu on what he thinks he should have written in that chapter -- a way to build heaps using Heap Layers (by yours truly). I used Heap Layers to build Hoard, DieHard, and DieHarder, as well as the custom allocators used in our OOPLSA 2002 paper, Reconsidering Custom Memory ...
4,730,503
4,730,520
Casting const void* to const int*
I haven't used void* and const_correctness before so I am not understanding what I am doing wrong in the below code. All I want is to cast a void* returned by a member function of a const object to int*. Please suggest better approaches. Thank you. I get the following error passing 'const MyClass' as 'this' argument of...
I think the problem is not in the cast from your array to a void * but in trying to call obj.getArr() when obj is marked const and MyClass::getArr() is not a const member function. If you change your definition of that member function to const void *getArr() const { return static_cast<const void*>(arr); } Then this ...
4,730,563
4,730,617
How to output this 24 bit image in Qt
I have an unsigned char array that is defined like so: unsigned char **chars = new unsigned char *[H]; for(int i = 0; i < H; i++) { chars[i] = new unsigned char[W*3]; } Where H is the height of the image, and W is the width, and chars is populated in the rest of that function looping over rows x columns of the in...
You can create a QImage directly from a block of data without copying every pixel. Since your image is stored with separate rows, you need something like QImage image = new QImage(width,height,QImage::RGB888) for (int h=0;h<height;h++) { // scanLine returns a ptr to the start of the data for that row memcpy(i...
4,730,788
4,730,897
template class operator overloading problem
I'm trying to port some Visual C++ (VS2005) code so that it will compile under both VS2005 and C++ Builder XE. The code that follows compiles fine under VS2005 but under C++ Builder XE, I get the following error: [BCC32 Error] time_stamp.h(49): E2327 Operators may not have default argument values Here is the code in q...
[Replacing my previous answer!] This is probably related to http://www.parashift.com/c++-faq/templates.html#faq-35.16 . Since the function you want to define is in fact a template function (it depends on counter_type), you should declare it before the friend declaration, and then declare a function template instantiati...
4,731,011
4,731,057
Request for the detailed description of "Static Initialization Order Fiasco"
I read about the SIOF in the faq-lite and still I really don't understand why the issue happens. I have a static library(.a) and I use that library to use its static const data member object type. Then that static const data member object type I use and assign to a global variable(object). But it seems that global vari...
The static initialization order fiasco is fairly straightforward: static objects in a single translation unit are initialized in the order in which they are declared, but there is no guarantee as to the order in which static objects in different translation units are initialized with respect to each other. So, in you...
4,731,203
4,735,537
Why can't I pass a const object in a const argument function/method?
EDIT: Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here. Actually I'm trying to figure out why I need to use const_cast in this specific case: int ProjTreeItem::row() const { if (parentItem) { // instance of const object to test const ProjT...
I presume you mean the line parentItem->childItems.indexOf(item); doesn't compile. I also presume you wrote QList< ProjTreeItem* > childItems; in parentItem's type(class) definition. If I understand correctly, in the line parentItem->childItems.indexOf(item) you are going to convert ProjTreeItem const* into ProjTree...
4,731,272
4,731,393
Adding dll's to the project and making functions work
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual St...
You don't have a .lib-file to link against. Maybe this can help you http://www.coderetard.com/2009/01/21/generate-a-lib-from-a-dll-with-visual-studio/ or this: http://support.microsoft.com/default.aspx?scid=kb;en-us;131313 or this: http://www.asawicki.info/news_1420_generating_lib_file_for_dll_library.html when you hav...
4,731,372
4,731,458
Syntax for Templated Member Functions
Consider the following code: template <typename Datatype> class MyClass { void doStuff(); template <typename AnotherDatatype> void doTemplateStuff(AnotherDatatype Argument); }; template <typename Datatype> void MyClass<Datatype>::doStuff() { // ... } template <typename Datatype> template <typename An...
This is an excellent question. I don't know the specific reason that the standards committee decided to design templates this way, but I think it's a callback to lambda calculus and type theory. Mathematically speaking, there is an isomorphism between any function that takes two arguments and returns a value and a fu...
4,731,406
4,731,459
.(dot) access to static method
Following is a popular code: class A { public: static const string TYPE = "AEvent"; const string& getType() { return TYPE; } }; Above code could be use like this: if (aInstance.getType() == A::TYPE) { ... } It's fine. But it's not intuitiveness. Did not? Look at the next code: class A { public: stati...
As long as you're returning a static variable from static method it should be fine. It doesn't matter if you call it using dot or resolution operator. Either way it's part of the object as well as the class which should give you the same static variable.
4,731,656
4,731,672
Instantiate structure at assigned address (allocation assignment)
For a class I'm taking, we need to develop allocation utilities. Safety aside, I will be using far pointers to receive and assign addresses to some structures. I am also not allowed to use "memalloc" in this assignment. I referred to: Linked Lists in C without malloc to learn how to make a linked structure without usi...
Depending on what you want to do, you'll probably want to use a combination of the following tools: Placement new: You can construct objects at specific memory locations by using the following syntax: new (reinterpret_cast<void*>(0x500)) MyObject(/* ...ctor args... */); This does not allocate any new memory; instead i...
4,731,668
4,750,501
Calling an event handler after text has been modified in wxWidgets
I am trying to create a situation in my wxWidgets application where a user can type something into a text box, and if there are one or more characters in the text box, other controls become enabled. As such, I created an event handler that checks TextBox->IsEmpty() on the event wxEVT_COMMAND_TEXT_UPDATED. However, this...
As @ravenspoint mentioned, this event should have been fired after the change was made, but I also wanted to point out that even in the cases where an event is fired just before a change is made, the change is almost always passed into your event handler with the event parameter. So for this case, you may want to actua...
4,731,695
4,731,749
Are arrays covariant in their size?
Is there a way to use the new std::array type polymorphically in the size of the array? That is, if I have a function of the form void DoSomething(std::array<int, 5>& myArray) { /* ... */ } Then is it mathematically well-defined to do the following (even if it's not legal C++ code?) std::array<int, 10> arr; DoSom...
Directly? No. You can, however, use compile-time polymorphism to achieve something very similar, and you can write a reference wrapper that makes it easier to work with in the code: #include <array> #include <cstddef> template <typename T, std::size_t N> struct ref_array_of_at_least { template <std::size_t M> ...
4,731,736
4,750,835
Qt how to open a file in current dir ? or what's wrong with this?
I'm trying to open an xml file in the current location of the executable QString path = QDir::currentPath(); path.append("/acc.xml"); QFile file(path); if(!file.open(QIODevice::ReadOnly)) { insertItem("IO ERR"); } When I run it from Qt creator, everythin...
Try to use QCoreApplication::applicationDirPath() instead of QDir::currentPath(). For details see http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath
4,732,063
4,732,397
How to compile SWIG via windows
I've downloaded swigwin, sigwin for windows, and have been checking examples. However, most examples have to compile like this: swig -example.i. I tried doing this over the cmd prompt but it does not work. Can you please teach me how I can do this on windows?
You have to choose a language. To create a Python extension wrapper for C: swig -python example.i for C++: swig -python -c++ example.i See swig -help. You may also need to add swig to your path. Something like: path c:\swigwin-2.0.0;%path% Or add it through Control Panel, System, Advanced, Environment Variables (o...
4,732,487
4,744,342
Can the Funambol C++ API be used for Symbian Series 40 development?
Can I use the Funambol API for Symbian Series 40 development using C++, as the Series 40 SDK is not available for C++?
As far as I can tell - not with C/C++, as the SDK is Java ME based and apparently does not include JNI. But I believe Funambol also supports Java ME - so you may not need to use C/C++.
4,732,592
4,732,654
How to use lseek to read the last character of a file
I'm trying to read the characters from a file in reverse order using lseek. So far, I have: int finished = 1; char temp[1]; while (finished > 0) { lseek(fileID,0,2); finished = read(fileID, &temp, 1); cout << temp[0]; } But read always returns 0. Any ideas on what to do?
Surely the call to lseek() should be lseek(fileID, -1, SEEK_END); You are seeking to the end of file and you need to be one byte short.
4,732,693
4,732,884
WinAPI timed mutex lock
How to lock mutex (critical section) for some amount of time? Is there any API function for that? As far as I see there is nothing like that in windows. If so, is it possible to implement it manualy? Thanks.
The equivalent of pthread_mutex_timedlock() in Win32 is using a Mutex and specifying a timeout (other than INFINITE) in one of the wait-functions.
4,732,999
4,733,039
How does back_inserter work?
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL: template<class C> class back_insert_iterator { protected: C* container; public: typedef C container_type; typedef output_iterator_tag iterator_category; typedef void ...
They exist because STL algorithms work on iterators which must be post and pre incrementable and have a dereference operator. try to think what this does: (*back_inserter) = value; ++back_inserter;
4,733,000
4,733,023
problem signed char c++
This is the code: int main() { char c = 0x00; //c |= 0x0A; c |= 0xA0; while(c != 0x00) { cout << (c & 1) << endl; c = (c >> 1); } } Why does this code work when I do or with 0X0A and not with 0xA0, as a number 0xA0 is to big to fit a signed char but why am I not allowed to set the bits for 0xA0? When I pr...
It is because of the sign extension of when performing a right shift. 0xA0 <=> 10100000 binary (and is a negative number because the MSB is set to 1) (0xA0 >> 1) <=> 11010000 replace char c by unsigned char c or mask the MSB after the shift. int main() { char c = 0x00; //c |= 0x0A; c |= 0xA0; while(c != 0...
4,733,224
4,733,259
On Exception-Safety in a Function-Call
Is the call to f() exception-safe? inline std::auto_ptr<C> auto_new() { return std::auto_ptr<C>(new C()); } void f(std::auto_ptr<C> p1, std::auto_ptr<C> p2); // ... { f(auto_new(), auto_new()); } In other words, does it make any difference when it comes to the atomicity of the first and second auto_new...
Yes, it's exception safe; no, inline makes no difference to the sequence points guaranteed in the calling expression.
4,733,448
4,733,704
why copy constructor is called when passing temporary by const reference?
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation. class A { public: A(int i) {} private: A(const A&) {} }; void f(const A& a) { } int ...
You can find the answer to your question in Copy Constructor Needed with temp object or go directly to http://gcc.gnu.org/bugs/#cxx%5Frvalbind The C++ Standard says that a temporary object should be created in this context and its contents filled with a copy of the object we are trying to bind to the reference...
4,733,476
4,733,692
About template specialization
I need to provide an insertion/lookup/delete interface for a hash table. I wrote the hash table only to provide the internal bucket/entry management. The hash function should be supplied from outside. I am now stuck on how to expose the interface so that the hash table can handle byte arrays as well as fixed length dat...
I am getting confused here because I don't get where operator[] on the hash-table conflicts with operator[] on the data-type that you are storing in it. If your hash_table has operator[] this could either be a hash_map where you supply the key to operator[] or it could be that operator[] returns you the contents of a c...
4,733,613
4,756,457
omniORB::MaxMessageSize in omni 4
I am working on a porting project where omni3 has been used. Now we are integrating it with omni 4 which omniORB::MaxMessageSize function is not supported. Anyone know from which function we have to substitute it?
I got the solution. Substitute is CORBA::ULong giopMaxMsgSize
4,733,869
4,733,904
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"?
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)? Please explain the rationale, if possible. I read somewhere that != operator is better than comparison operators. also pre-increment operator is better than post-increment operator, since it doesn't require any temporary variable to store the i...
There are at least two differences: the first one will iterate 5 times (from 0 to 4), while the second one will iterate 6 times (from 0 to 5). This is a logic difference, and it depends on what you need to do. If what you meant for the second example was i<=4 (versus i!=5) you shouldn't bother: any compiler will alway...
4,733,876
4,733,935
Accessing "neighbor" classes created from 1 class possible?
Here's my problem: I have 1 class that creates two new instances of a two other classes, and now I would need to either have a direct availability from one of the instances to the other, is this possible and if so, how? so: in Class A: b = new B(5); // where 5 is an int data member of B c = new C(); and let B::bee() b...
Your C member should be a pointer or a reference (B *b or B &b). If it's a B it will copy your B object, so it will refer to a different instance (which has been created by copying the one you're interested into). Also, you'll need to pass your b object as a pointer or a reference, otherwise a new instance will be crea...
4,734,057
4,734,100
C++ template class inheritance
I have been porting some C++ code, which was written long time ago, and is normally compiled with Visual C++ (Visual Studio 7.1 version) and Intel C++ Compiler 11.0, the target platform is Linux (Suse x86-64), with GCC 4.3.2 and Intel C++ Compiler 11.1 The problem is that code like this FileA.h template<typename T, int...
foo1 is not a dependent expression so the base class, which is a dependent type, is not used to resolve the foo1 call. As you can't change the code, you are stuffed. If you could change the code you would need to change the expression to be dependent. Typically this is done by changing it to this->foo1().
4,734,129
4,734,167
returning an iterator from a function
I have the following example: #include <stdio.h> #include <map> #include <conio.h> typedef std::map<int,int> mi; typedef std::map<int,int>::iterator mit; mit myfind(mi mymap) { mit it = mymap.find(1); printf("in function: %d\n",it->second); return it; } void main() { mi a; a.insert(std::pair<int...
Your returned iterator is pointing somewhere into the local copy of mymap that was passed into myfind() (which is deallocated when the function returns). Try: mit myfind(mi &mymap) { ... This will pass a reference to mymap and no copy is made.
4,734,241
4,734,262
What does assignment to *this do (*this = val)?
I was browsing Qt sources, and noticed this QUuid &operator=(const GUID &guid) { *this = QUuid(guid); return *this; } I've never seen assignment to "this" before. What does assignment to "this" do?
That is not an assignment to this but to the object pointed by this. That will effectively call operator=( QUuid const & ) on the current object.
4,734,474
4,735,175
boost::asio, threads and synchronization
This is somewhat related to this question, but I think I need to know a little bit more. I've been trying to get my head around how to do this for a few days (whilst working on other parts), but the time has come for me to bite the bullet and get multi-threaded. Also, I'm after a bit more information than the questio...
1) Have a look at io_service::work. As long as an work object exists io_service::run will not return. So if you start doing your clean up, destroy the work object, cancel any outstanding operations, for example an async_read on a socket, wait for run to return and clean up your resources. 2) io_service::post will async...
4,734,633
4,734,978
Using GMock to verify a Destructor Call
Using GMock, how can I verify that a class's destructor is called? Is there a way, other than to wrap it in another class? The obvious method, EXPECT_CALL(object, ~classtype()) yields a compiler error (gmock cannot produce a mock method called gmock_~classtype).
An easy way to check for a destructor call: class MockFoo : public Foo { ... // Add the following two lines to the mock class. MOCK_METHOD0(Die, void()); virtual ~MockFoo() { Die(); } }; In your test function: MockFoo* foo = new MockFoo; ... { EXPECT_CALL(*foo, Die()); } More Details can be found h...
4,734,720
4,734,757
C++ modulus small program issue
I'm trying to write a very simple program in C++ that finds the modulus of two numbers as follows: #include <iostream> using namespace std; int n; int d; int modulus; int main() { cout<<"***Welcome to the MODULUS calculator***"; cout<<"Enter the numerator, then press ENTER: "; cin>>n; cout<<"Enter the denominator, then...
You get the error because the name of your global variable modulus clashes with std::modulus. To fix this, you can: Make modulus a local variable Rename the modulus variable Remove using namespace std and either import the names you need from std individually or qualify them with std::
4,734,735
4,734,868
What are global states? How do they affect testability and how to avoid them?
List down the various global states like global variable, singleton object etc., I read that they affect the testability of code. Can you explain alternatives to global states that help in improving the testability of the code?
Global variables and singletons are so similar from the testability viewpoint that they don’t have to be treated separately. Good OO design should be like bricks of Lego that fit together to create the resulting system. The main problem with globals is that you lose isolation. When you access your collaborators using g...
4,734,810
4,734,839
How can I create a data structure starting at a specified memory address (without using new)?
I asked a similar question before, but I only realized now that the answer I received isn't totally what I wanted. If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned a...
That's what placement new is for: foo* p = new(0x9000) foo(bar);
4,734,846
4,734,889
calling operators of base class... safe?
Is following pattern ok/safe ? Or are there any shortcomings ? (I also use it for equality operators) Derived& operator=(const Derived& rhs) { static_cast<Base&>(*this) = rhs; // ... copy member variables of Derived return *this; }
This is fine, but it's a lot more readable IMHO to call the base-class by name: Base::operator = (rhs);
4,734,890
4,735,068
Get specific edge with boost::graph
I'm using boost::graph and I have two vertex_descriptors. What is the quickest way to get the edge between them, without iterating over all the edges?
Ok, I found it out. boost::edge(u,v,g) returns pair<edge_descriptor, bool> where the bool is whether the edge exists. So in my case I know it does, so I use the expression: boost::edge(u,v,g).first
4,734,963
4,735,023
Does it make sense to modify an object as a whole using one of its behavior? Say inside the assignment operator overloading using this pointer?
I see a question on this operator (What does assignment to *this do (*this = val)?) but is it logical to modify an object as a whole from within one of its behavior? Does it makes sense in OOP world?
It makes sense when it makes sense from a design perspective. I'd expect Rect, Size and Point classes, for example, to support assignment. In this sense, these kinds of types (to me) should behave like plain-old-datatypes (PODs). But if I was modelling a traffic simulation with cars and trucks, I certainly would no...
4,734,964
4,735,082
push_back operation in c# containers
I need container like c++ vector. Often it is adviced to use List, but it dosen't support push_back operation. I know this is rather simple implementing an extension method for List container. But. Would Stack be a good alternative? Thanks!
It does support List<T>.Add. Isn't that what you are looking for?
4,735,107
4,735,179
Octlet, quad word or what?
I am translating some documentation on libraw1394 to Russian. The documentation on libraw1394 says: The basic data structures defined in the standard and used in this document are the quadlet (32 bit quantity) and the octlet (64 bit quantity)... There is no such unit like "octlet" in Russian. I used to use "qua...
octlet == 8-byte [8-байт ?] I wouldn't use "WORD" because a word can vary. It could be 1 byte, 2 bytes, 4 bytes... a Byte is always 8 bits.
4,735,242
4,735,463
C++ Avoiding library linking
I currently have a c++ setup like the following class FlowController { public: //... private: cntrl::OneWayValve _intake; } As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a...
What you could do is make your Valve library part of your OneWayValve library using a tool called a librarian. I don't know what OS/compiler you are using so I'm going to describe how do it using Visual Studio since that's the only system I've actually done this with (unless you want to count CP/M + LIB-80 :-) If you b...
4,735,500
4,736,797
What are alternatives to this typelist-based class hierarchy generation code?
I'm working with a simple object model in which objects can implement interfaces to provide optional functionality. At it's heart, an object has to implement a getInterface method which is given a (unique) interface ID. The method then returns a pointer to an interface - or null, in case the object doesn't implement th...
What about something like that ? struct Interface { virtual ~Interface() {} virtual std::type_info const& type() = 0; }; template <typename T> class InterfaceImplementer : public virtual Interface { std::type_info const& type() { return typeid(T); } }; struct FooInterface : InterfaceImplementer<FooInterf...
4,735,543
4,735,624
Tokenizer efficiency question
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code. I can't choose between two ways: 1) the tokenizer read all tokens: bool Parser::ReadAllTokens() { Token token; while( m_Lexer->ReadToken( &token ) ) { m_Tokens->push_back( token ); ...
Traditionally, compiler construction classes teach you to read tokens, one by one, as you parse. The reason for that, is that back in the days, memory resources were scarce. You had kilobytes to your disposal, and not gigabytes as you do today. Having said that, I don't mean to recommend you to read all tokens in advan...
4,735,778
4,735,879
Preventing classes from being instantiated on the stack or as data member
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem. I am writing a new module which defines an interface that tells the module how to behave in certain conditions. It's something like this (artifical example just to illustrate my problem): // Interface that should be imp...
This is fundamentally flawed- what if I want my main class to inherit and provide that callback? You're artificially limiting it for no real advantage. Use a std::function instead. class Module { public: Module (std::function<void()> ringAlert) : Alert(ringAlert) {} void dosomething() { if (something) a...
4,735,833
4,735,868
Porting C++ to C# - templates
I'm porting a C++ application to C#, and have run across templates. I've read up a little on these, and I understand that some templates are akin to .Net generics. I read the SO answer to this case which nicely summed it up. However, some uses of c++ templating don't seem to be directly related to generics. In the b...
Unfortunately .Net generics can only accept types. C++ Templates take other values that are considered constant expressions by the compiler, because they are effectively just macros that expand to more code. This means that your idea of turning the code into a method call is the best bet. You could make the method ca...
4,735,984
4,736,027
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ? #include <iostream> using namespace std; class A { public: int a, b; }; class B { public: A* array[10]; B() { for(int i = 0...
In b = B() you're constucting a new temporarty instance of class B, assigning a copy to b, then the temporary instance is descructed.
4,736,044
4,736,243
checking invariants in C++
Are there any established patterns for checking class invariants in C++? Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn'...
Answer #0: You can have unnamed local variables, but you give up control over the life time of the object - and the whole point of the object is because you have a good idea when it goes out of scope. You can use void Foo::bar() { invariants_checker<Foo>(this); // goes out of scope at the semicolon new invarian...
4,736,109
4,736,604
VC++ Visual Studio added .hpp files in subdirectory but get "Error: cannot open source file ..."
This is driving me nuts - I've added a number of .hpp files in subdirectories in the root of an existing VC++ projects source directory. Visual Studio complains "Error: cannot open source file ..." but if I right click on the and select open document, VS can display it. I've tried: "Rescan solution" which appears to ...
Workaround; Add the files to a directory outside of the project and then reference those directories in the "Additional Include Directories" in Properties -> Configuration Properties -> C/C++ -> General. Why I can't add additional directories within the project and have Visual Studio rescan them (like an Eclipse refre...
4,736,279
4,736,313
Updating a single value in a sorted data structure
I need a data structure that is able to: Add one value Get the lowest value Update one value I can achieve this using std::multiset, where the operations are imlemented as: multiset::insert() multiset::begin() first remove the item using multiset::erase() then add updated item using multiset::insert() One thing I ...
std::priority_queue will give you efficient insertions and lowest value queries, but updates will be slow. You can make updates efficient by storing pointers in both a PQ and a std::vector and using the vector to perform updates. To perform an update, mark the entry as stale and insert a new updated copy. Then when que...
4,736,283
4,745,260
Building a C++ project in CodeBlocks/Eclipse that uses yacc and lex
I have the following makefile, which is working fine, to build my application. How can I configure an IDE (say, codeblocks, eclipse) to compile this. The C/C++ files associated with yacc are giving some errors when I try from eclipse/codeblocks. Is there any way to make eclipse/codeblocks to use an object file for som...
If you already have Makefile, you can use 'Makefile project' in Eclipse. In this case Eclipse will use 'make' instead of internal builder to build the project.
4,736,377
4,736,412
What is a C extension?
What is the meaning of 'C extension'?
An extension in C is a feature supported by a C compiler that is not described (permitted, mandated) by the C standard. (And similarly for C++, since the question is tagged like that.) For example, GCC allows you to define a function within the body of another function; standard C does not. That is a C extension.
4,736,455
4,736,644
E2321 Declaration does not specify a tag or an identifier
I'm porting code from VS2005 to C++ Builder XE so that it will compile with both compilers. The following code compiles fine under VS2005 but under C++ Builder I get the subject error message with the inline function rawtime(); (E2321 Declaration does not specify a tag or an identifier). Here is the code: template<typ...
Without knowing what TIMESTATS_STMT expands to it's hard to say, but I bet the problem actually occurs on the line of the macro expansion and is being tagged to the following line, which appears fine to me.
4,736,485
4,736,527
srand(time(0)) and random number generation
srand(time(0)) is used in C++ to help in the generation of random numbers by seeding rand with a starting value. But, can you explain what it exactly does? Thanks.
srand() gives the random function a new seed, a starting point (usually random numbers are calculated by taking the previous number (or the seed) and then do many operations on that number to generate the next). time(0) gives the time in seconds since the Unix epoch, which is a pretty good "unpredictable" seed (you're ...
4,736,691
4,736,810
observer pattern -- passing information to the observer
please excuse any and all newbieness), I have the following task to perform: I have several classes (call these A) that constantly gather information from various sources (database, internet, etc). They can contain a potentially large amount of information on some topic.. I also have a bunch of classes (call these B) t...
You could solve this problem by making your observers template classes. You would then have to define a minimal interface (or concept actually) that you could call, say, a Fact that would define what a single item of data looks like. You could also define a concept AxisDescription that defines how axis are described (l...
4,736,698
4,737,732
Getting Java to talk to Python, C, C++, and Ruby
I have succeeded in getting ProcessBuilder to run external scripts, but I still have to get Java to communicate with the external scripts. I figure that I should get the input/output streams from the process, and use those to send and receive data. I'm having a the most trouble with giving input to the scripts. It seem...
The method getOutputStream() on the Process class returns a stream you can write to in Java that connects to the stdin stream of the process. You should be able to read this as you would normally read stdin for each language (e.g., cin for C++, scanf for C, STDIN.read for Ruby, don't know Python!) If this is what you'r...
4,736,718
4,738,943
MAC address:pad missing left Zeros
For example i have a MAC address that has a value of "0:22:3f:a:5d:16", how do i convert this to a human readable format like "00:22:3f:0a:5d:16"? My mac Address has missing leading zeros because i use string asd = ether_ntoa ((struct ether_addr *)p->add2);//p->add2 is a unsigned char[6] ether_nota removes the leading...
The implementation that causes it to print without zero padding is just a printf where they use %x instead of %02x. The struct ether_addr format is documented in the man page, and therefore its internals are not private. The structure ether_addr is defined in <net/ethernet.h> as: struct ether_addr { uint8_t ether...
4,736,738
4,737,778
How can you add a new keyword to clang, a keyword that would be treated as main?
How can a new keyword be added to clang? The new keyword should be a function qualifier. Where would the declaration part go? Thanks.
You have to add it to include/clang/Basic/TokenKinds.def, and then add a new case to ParseDeclarationSpecifiers(...). Probably an easier option would be to define a new attribute, and then use #define your_new_qualifier __attribute__((your_new_attribute)) Otherwise you'd have to add this qualifier support to the AST, w...
4,736,788
4,738,090
Memory leak when using CoCreateInstance
I am using COM to initialize a C# .NET class through c++ unmanaged code, and I am detecting a memory leak even in a very basic program: int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(NULL); ComClass::IClass1 *_comClass1; HRESULT hr = CoCreateInstance(__uuidof(ComClass::Class1), 0, CLSCTX_INPRO...
Yes, this is normal. The first call to CoCreateInstance will load the CLR into your process. Which creates the primary AppDomain to load the managed code, with a garbage collected heap, the loader heap and a smattering of internal data structures. Calling the Release() method on the interface pointer does not unload...
4,736,795
4,736,939
Matrices/Vectors in C++ with the R math standalone library?
All, I have been playing with the R math standalone library in C++. I quite like being able to generate random numbers and use distribution functions that I am comfortable with from R. My question is: is it possible to use the matrix operations (multiplication, transpose, inverse, Chol, etc) that are available in R ...
Most, if not all, of the things you mention are provided by LAPACK or BLAS Fortran code that R links to, not something R provides new code for itself. If you are interested in using C++ with R, look at the Rcpp package by Dirk Eddelbuettel and Romain Francois. Dirk has also written the RcppArmadillo package as an inter...
4,736,877
4,739,745
How to link Boost in a dependent static library
In MS Visual C++ 2010 I had a single C++ project in my solution which used boost and worked perfectly. I then decided to convert this project into a static library and create a new project which depends on this static library. Now, my converted static library builds without errors and warnings (compiler and linker) b...
Apparently you don't need the .libs, as your exe also links without them. You seem to be using boost header-only methods and classes. So just tell boost to disable auto linking by defining the preprocessor symbol BOOST_ALL_NO_LIB in your project. If you want to make your .lib unnecessary big by including all of boost, ...
4,736,929
4,737,009
Comparison : C++ template specialization approaches
Which is more correct? And Why. On work I recently run in a discussion how to do a specific template specialization. This way: template <typename T, bool someBoolVar = is_polymorphic<T>::value> struct SomeTemplate { // with empty definition }; template <typename T> struct SomeTemplate<T, true> { ... }; template <ty...
Neither. Because both will not compile! Wrong syntax for partial specialization! This is how partial specialization is done: //correct syntax template <typename T> struct SomeTemplate<T,false> { ... }; Not this: //wrong syntax template <typename T, false> struct SomeTemplate { ... }; Now answer to your question...
4,737,018
7,109,669
How to call .NET (C#) code from a native C(++) DLL?
I have a C# app.exe and one C# my.dll. The my.dll .NET project links to a native C++ DLL (mynat.dll) (extern C DLL interface) and calling from C# into the C++ DLL works without problems. ( By using the [DllImport("mynat.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] attribute. ) What I n...
While the link provided by SLaks to the Unmanaged Exportsutility might or might not work, we used a similar tool (from a different source) here and due to problems with signed executables have abandoned this approach. We have concluded the following and will do this in the future: The correct way to make .NET callbacks...
4,737,082
5,296,027
Statically linked, correctly working readline library under Windows?
We're developing a C++ software package which depends on the GNU readline library and we usually build using gcc (requiring at least version 4). Now we would like to port this to Windows, obtaining a statically linked version which we can redistribute without requiring compilation by users. I've tried several approache...
After similar frustrations, I have just now compiled both a 32bit and 64bit version of libreadline 6.2 using MinGW-w64. Here's my how I did it: Layout of my dev directory: c:\dev\msys c:\dev\mingw32 c:\dev\local32 c:\dev\mingw64 c:\dev\local64 Set some environment variables for the 32 bit build: export CPPFLAGS=-I/c/d...
4,737,169
4,737,214
PInvoke in 64bit .net app through c++ 64 bit dll
I'm having an issue calling a function in a c++ dll inside of a c# app. I'm calling the function inside of c# like so: [DllImport("cryptopp.dll")] public static extern IntPtr RSAEncryptString(string filename, string seed, string message); It is being exported in the c++ dll as shown below. extern "C" __declspec(dllexp...
I think you need to change the first line to: [DllImport("cryptopp.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] If you want to get very descriptive, you can also add these: public static extern IntPtr RSAEncryptString( [In, MarshalAs(UnmanagedType.LPStr)] string filename, [In...
4,737,226
4,737,261
Regrow memory allocated by operator new()?
Is it possible to regrow memory allocated by operator new(), when allocated this way: char* buf = new char[60]; The C++ FAQ states that memory allocated by new cannot be resized by realloc, so what's the correct way to regrow memory allocated by new?
The correct way is to use std::vector or std::string depending on your particular usage of the array--let C++ handle allocation for you. If you must use new, you'll have to reallocate and copy the memory. This simple templated function shows you the basics: template <typename T> T *GrowArray(T *oldArray, size_t oldCoun...
4,737,344
4,737,379
Order of function call
for the expression (func1() * func2()) + func3() will func1() * func2() be evaluated first as it has brackets or can the functions be called in any order like first func3() and then (func1() * func2())
The functions can be called in any order.
4,737,403
4,737,459
Operator new/delete & destructors
So I'm a beginner trying to get to grips with operator new. What's wrong with my destructor? class arr{ public: arr(){ pool=::operator new(100*sizeof(double)); } ~arr(){ ::operator delete(pool); } void* pool; }; int main() { arr a; a.~arr(); //If I comment this out it's ok....
Well, at a glance, you should not be explicitly calling the destructor. Instead use scoping to force a out of scope and call the destructor. int main() { { arr a; } //This calls destructor of a //Rest of code } Otherwise the destructor of a gets called twice: once when you call it and again when ...
4,738,045
4,921,699
OpenMP: Huge performance differences between Visual C++ 2008 and 2010
I'm running a camera acquisition program that performs processing on acquired images, and I'm using simple OpenMP directives for this processing. So basically I wait for an image from the camera, and then process it. When migrating to VC2010, I see very strange performance hog : under VC2010 my app is taking nearly 100...
In 2010 OpenMP, each worker thread does a spin-wait of about 200 ms after task completion. In my case of a I/O wait and repetitive OpenMP task it is massively loading the CPU. The solution is to change this behaviour; Intel C++ has an extension routine for this, kmp_set_blocktime(). However Visual 2010 doesn't have su...
4,738,272
4,738,305
Default templated parameters in function templates
I was answering this question. And I realized that I ran my mouth off when I didn't know what I was talking about. So my question is this. Is it possible to merge these functions in to one? (don't worry that this is an exact duplicate of a function that already exists, I'm just using it as an example) template <class...
Is it possible to merge these functions in to one? Sadly, no. You can't have a default template argument for a function template parameter and default function arguments cannot be used to deduce template arguments. Is re-using the code from the first in the second even possible without using C++0x features? Ye...
4,738,295
5,004,924
Irrlicht is looking for files in the wrong path
I'm writing a game using Irrlicht. And I have problem. I have game in /home/m4tx/Projects/Discoverer/Discoverer/bin/Debug/, and models in /home/m4tx/Projects/Discoverer/Discoverer/bin/Debug/media/. I have modified code from first Irrlicht example: #include <irrlicht/irrlicht.h> using namespace irr; using namespace cor...
You need to get the working directory right. A good debug line in your code is to print the current path, or log it. I normally put it was the first line in main. #include <unisdt.h> #include <stdlib.h> char cwd[1024] = ""; getcwd( cwd, 1024 ); printf( "Current path: %s\n", cwd ); Also check in your code blocks proje...
4,738,315
4,738,394
C++ Overriding... overwriting?
I know what overriding is in C++. But, is there overwriting? If so, what does it mean? Thanks.
In C++ terminology, you have overriding (relating to virtual methods in a class hierarchy) and overloading (related to a function having the same name but taking different parameters). You also have hiding of names (via explicit declaration of the same name in a nested declarative region or scope). The C++ standard doe...
4,738,405
4,738,459
How can I store objects of differing types in a C++ container?
Is there a C++ container that I could use or build that can contain, say, int and string and double types? The problem I'm facing is that whenever I try to populate, say, a map, vector or list with, say, the following: int x; string y; double z; I'm restricted with the format: list<int> mycountainer; vector<string> my...
You could use (or re-implement) boost::any and store instances of boost::any in a container. That would be the safest, since boost::any has probably dealt with much of the edge cases and complexity involved in solving this kind of problem in the general case. If you want to do something quick and dirty, create a struct...
4,738,425
4,739,057
Remove an element from the middle of an std::heap
I'm using a priority queue as a scheduler with one extra requirement. I need to be able to cancel scheduled items. This equates to removing an item from the middle of the priority queue. I can't use std::priority_queue as access to any element other than top is protected. I'm trying to use the algorithm's heap functi...
Unfortunately, the standard is missing this (fairly important) function. With g++, you can use the non-standard function std::__adjust_heap to do this, but there's no easy portable way of doing it -- and __adjust_heap is slightly different in different versions of g++, so you can't even do it portably over g++ version...
4,738,598
4,738,732
Error declaring hash_map in lex file
I'm working on writing a simple preprocessor for a compiler. Below is an edited snippet of my code: %{ #include <string.h> #include <hash_map> #include "scanner.h" #include "errors.h" struct eqstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) == 0; } }; std::hash_map...
You need std::hash rather than just hash, since you have no using statement that will pull it into scope. Also, the default std::hash<const char *> will hash the pointer directly, which won't work for this use -- you need a hash function that hashes the c-string pointed at. You need to define your own specialization ...
4,738,768
4,740,044
Printing double without losing precision
How do you print a double to a stream so that when it is read in you don't lose precision? I tried: std::stringstream ss; double v = 0.1 * 0.1; ss << std::setprecision(std::numeric_limits<T>::digits10) << v << " "; double u; ss >> u; std::cout << "precision " << ((u == v) ? "retained" : "lost") << std::endl; This di...
Don't print floating-point values in decimal if you don't want to lose precision. Even if you print enough digits to represent the number exactly, not all implementations have correctly-rounded conversions to/from decimal strings over the entire floating-point range, so you may still lose precision. Use hexadecimal flo...
4,738,987
4,739,353
_ITERATOR_DEBUG_LEVEL error in visual studio
I am trying to compile JRTPLIB in Visual Studio 2010 on windows 7. It's been a true nightmare... but I'm atleast narrowing down the problems. This is left. Error 3 error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in client.obj C:\Users\Johan-bar\Documents\Visual Stud...
Compile everything you use with -D_ITERATOR_DEBUG_LEVEL=0 option. It is so by default in VS 2010 Release mode, but some things are still built with other options and so are not binary compatible. In older visual studios there was _SECURE_SCL and i am not sure if some of code may still use it. Put somewhere (say into st...
4,739,140
4,739,164
g++ -lcurl says its not found, but I can see it in ldconfig -p
I am trying to build some software on a brand new install of CentOS 5.5 My compile line is : g++ -I ../common/ -I ../readers/ -I ../writers/ -I /home/dcole/software/xerces-c-3.1.1/src -O3 -Wall -fopenmp -fPIC -o chipper chipper.cpp -L/usr/lib64/ ../../lib/IDT.a ../../lib/Linux/libxerces-c.a -lcurl -lidn -ldl -lssl .....
At link time, -lcurl tells the linker to look for libcurl.so. From there, the SONAME within the library (libcurl.so.3) is embedded into the executable, and that's the filename that is searched for when executing. You have libcurl.so.3 but may be lacking libcurl.so, which is needed for development. What is your distribu...
4,739,388
4,739,474
make an integer even
Sometimes I need to be sure that some integer is even. As such I could use the following code: int number = /* magic initialization here */; // make sure the number is even if ( number % 2 != 0 ) { number--; } but that does not seem to be very efficient the most efficient way to do it, so I could do the following...
int even_number = (number / 2) * 2; This should work regardless architecture as long as optimizer is not going in the way (it shouldn't but who knows).
4,739,709
5,187,957
Looking for numerical/multimedia/signal_processing benchmarks in C (maybe c++)
I am working on custom instruction selection algorithms for fgpas softcore, and I need some C code to test my system. My requirement are: Oriented toward heavy number crunching : numerical/multimedia/signal_processing Written in C (prefered) or C++ (or anything llvm can compile) Platform agnostic (no inline assembly e...
Maybe you could adapt something from CPU2006's FP components. From http://www.spec.org/cpu2006/Docs/: 410.bwaves Fortran Fluid Dynamics 416.gamess Fortran Quantum Chemistry 433.milc C Physics: Quantum Chromodynamics 434.zeusmp Fortran Physics / CFD 435.gromacs C/Fortran Biochemistry/Molecular Dynamics 436.ca...
4,739,904
4,740,125
How to selectively build Qt for VS2010?
I have been building Qt library for VS2010 for 4 hours now, and it seems that it will go on for a while. (At the moment it is building something related to javascript.) Is there an option to just build the stuff I want? It would be much much easier if I had installed VS 2008 and the prebuilt library of QT for VS 2008....
configure.exe -platform win32-msvc2010 -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-multimedia -no-qt3support -fast Is my fast build setting for Qt - takes about 20mins on a decent single CPU desktop. Webkit is particularly slow to build, it uses lots of complex templated code.
4,739,917
4,739,941
loading library on cluster
I successfully compiled a program in c++, with boost, on a cluster we have here. I need to run an SGE script to run the simulation. The error I get is this ./main: error while loading shared libraries: libboost_thread.so.1.45.0: cannot open shared object file: No such file or directory Do I need to specify the ...
The easiest option is to compile a static binary. (With gcc, use -static. For other compilers, RTFM.) Another option is to set the LD_LIBRARY_PATH environment variable to the directory containing the Boost libraries, inside the job script: LD_LIBRARY_PATH=/where/ever/you/installed/boost If you didn't install Boost you...
4,740,295
4,740,626
Non-Blocking File Reads
Is there a non-blocking file read API in java? If not would it be wise to build one in C++ and call it from a java app via JNI?
No, FileChannel does not extend SelectableChannel. Probably because not all OSes support it. Windows does, and in theory you could write a windows-specific C++ library and call it via JNI, but it is a lot of work to integrate this with java.nio. I would rather have a worker thread copy the file contents to a pipe and...
4,740,298
4,740,310
Why is it trying to send a char array instead of a string?
My function declaration is siteObject(std::string& url, std::string& get, std::string& post); So why is this site("String 1", "String 2", "String 3"); creating a mismatch type error. It says it wants a string reference and it's receiving a char array. If you need more detail just ask in the comments.
Because there's an implicit call to the std::string constructor, which creates a temporary object. You cannot take a non-const reference to a temporary (because it's meaningless to modify a temporary). So, either modify your function to take const references, or by-value, or pass it non-temporary objects.
4,740,413
4,744,716
Compiling my C++ code for ARM Architecture
I am a java developer. I have some C++ code to make some system realted calls. This code is compiled on Intel 32-bit platform using GCC (I have make files) and it works fine on regular Intel based 32-bit linux machine. Now I need to run this on a linux OS running on Marvell ARM processor. When I load the shared objects...
You need more than just a switch, you need a cross-compiler. You can make your own, but probably the easiest way is : Find the development tools for your board. It probably comes with a development kit that includes a cross-compilation toolchain If you don't have these, you can try to install a precompiled cross-compi...
4,740,492
4,740,545
Changing an m x 3 array into an stl container?
I have an array: const string ARRAY[][3] = { {"Kolkata","Mumbai","218"}, {"Kolkata","New Delhi","316"}, ... {"Mumbai","Chennai","715"}, {"Chennai","Bangalore","516"}, }; This was a convenient way to store the entire table because I knew how many rows I had. However, in the future, the data needs to...
The most straightforward conversion would be to use an array in the struct: struct row { std::string data[3]; }; std::vector<row> v; Or you can use the std::/std::tr1::/boost:: array class template: std::vector<std::array<std::string, 3> > v; If you are going to use separate data members for each of the elements...
4,740,670
4,740,827
DLL dependency question / SetDLLDirectory
I have the following situation and can't come up with any good solution. I have a C++ application (app.exe) installed in C:\ProgFiles\MyApp. It needs a bunch of DLLs, which I install in C:\ProgFiles\MyApp\bin. I'd like to put them in a subfolder because there are so many of them. Now when I start app.exe, something n...
See this article from Microsoft which discusses the DLL search path and related issues. In particular, notice that if you do not put them in your app’s directory the current directory takes precedence, which is a security hole. One solution would be to use LoadLibrary (with a fully-qualified path), then GetProcAddress....
4,740,737
4,741,020
Look for alternative solution for generating a sequence of data
I have a problem, let's say: Generate a new string from the previous one following by one rule. 1, 11, 21, 1211, 111221, 312211, 13112221,... "1" : means one number 1 so the next string will be "11" "11" : means two numbers 1 so the next string will be "21" "21" : means one number 2 and one number 1 so the ...
To the best of my knowledge there isn't an STL "one-liner" that can generate this sequence. You could use a combination of algorithms to try to delineate all the ranges of adjacent consecutive values, perhaps using std::adjacent_difference, but I honestly think the hand-written loop will be more elegant. On an unrelat...
4,740,760
4,740,794
Permutations with some fixed numbers
How to effectively generate permutations of a number (or chars in word), if i need some char/digit on specified place? e.g. Generate all numbers with digit 3 at second place from the beginning and digit 1 at second place from the end of the number. Each digit in number has to be unique and you can choose only from digi...
Generate all permutations of 2 4 5 and insert 3 and 1 in your output routine. Just remember the positions were they have to be: int perm[3] = {2, 4, 5}; const int N = sizeof(perm) / sizeof(int); std::map<int,int> fixed; // note: zero-indexed fixed[1] = 3; fixed[3] = 1; do { for (int i=0, j=0; i<5; i++) i...
4,740,927
4,740,991
HTTP GET request problem
I am writing a simple downloader. I am trying to download jpg picture. void accel::download(int threads){ char msg[] = "HEAD /logos/2011/cezanne11-hp.jpg HTTP/1.0\r\nConnection: close\r\n\r\n"; int back = send(socketC, (const char *)&msg, strlen(msg), 0); char *buff = new char[500]; back = recv(socketC,...
You don't recieve anything because you told the server that you didn't want to make a second request when you specified Connection: close In your HEAD request. This tells the server that you're only going to make ONE request and not to bother waiting for a second. Try changing your first request to a persistant 'keep...
4,741,035
4,741,241
How do I DllExport a C++ Class for use in a C# Application
I have created a C++ Dll project which contains a class "myCppClass" and tried to Dll export it using the following code as described by: http://msdn.microsoft.com/en-us/library/a90k134d(v=vs.80).aspx class __declspec(dllexport) CExampleExport : //public CObject { ... class definition ... }; I have omitted the "public...
C# cannot directly import C++ classes (which are effectively name-mangled C interfaces). Your options are exposing the class via COM, creating a managed wrapper using C++/CLI or exposing a C-style interface. I would recommend the managed wrapper, since this is easiest and will give the best type safety. A C-style inter...
4,741,061
4,741,217
Is it logical to return a pointer to a char * you take as function argument?
So how such thing can be used to create such silly nesting functions: Z.reset(...C.reset(B.reset(A.get()))...) so a function would loock like char * reset(char * buffer) { ... return buffer; } so... my question is - such thing is acceptable in C++ simple API you would show to...
Technically, this is allowed. Strictly, it is acceptable. But I still wouldn't do it. The only reason I can think of to engineer a function like this is to support Method Chaining, which I think is an abomination. Opinions on this differ. You may love them, think they are nice & expressive, good for IntelliSense,...
4,741,271
4,741,401
Ways to detect whether a C++ virtual function has been redefined in a derived class
In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual function (with an implementation in the base class) has been re-implemented in the derived class? The context: I am writing a C++ library to solve certain classes of math...
You can't check for override of virtual function portably. You need to bring the knowledge to the Solver, preferably via type as opposed to run-time flag. One (type-based) way is to check for presence or absence of a interface, via dynamic_cast. A probably better way is to provide overloads of solve function, in your c...
4,741,406
4,746,359
How do I remove the library paths that qmake automatically adds to the linker options
Wanted to try using qt creator (coming from eclipse cdt) and I'm trying to get my project to build. Unfortunately, qmake is adding -L/usr/lib to the linker options by itself, making it link to the wrong version of a library, and I can't figure out how to remove it. I've tried doing "LIBS = " in the project file, as we...
It comes from qmake itself. It puts qt_libspath into link flags. It can be changed by either configuring and compiling Qt with a different directory prefix, or by modifying the qmake binary itself. An easy solution for you could be to create a filesystem-level link to the correct library version with a different name. ...
4,741,425
4,741,463
Virtual Interface Dtor && Dynamic_Cast
I'm trying to downcast from an interface to a derived class but my virtual dtor kills it? class IFOO { public: virtual ~IFOO(){}; virtual size_t index() PURE; }; class FOO : public IFOO { public: FOO() : size(5){}; ~FOO(){}; virtual size_t index(){ return index; }; size_t index; }; int main() { IFOO* A =...
You are taking the address of a temporary in the line IFOO* A = &FOO(); It should be IFOO* A = new FOO(); I guess the code works if you remove the dtor from your interface, because in that case it will not be called, and you enter the realm of undefined behavior, in which anything is possible, even bad code working a...
4,741,628
4,742,079
Most performant way to inherit structs in C++?
Let's say I have the following: #pragma pack(push,1) struct HDR { unsigned short msgType; unsigned short msgLen; }; struct Msg1 { unsigned short msgType; unsigned short msgLen; char text[20]; }; struct Msg2 { unsigned short msgType; unsigned short msgLen; uint32_t c1; uint32_t c2; }; . ...
A common pattern to deal with binary network protocols is define a struct that contains an union: struct Message { Header hdr; union { Body1 msg1; Body2 msg2; Body3 msg3; }; }; Semantically you are stating that a Message is composed of a Header and a body that can be one-of Body1, Body2... N...
4,741,715
4,741,816
How to check memory leak when dealing with linked-list naked pointer style?
When dealing with naked pointer, what is the best way to make sure that memory get released? For example, implemented linked-list using C style. #include <iostream> using namespace std; struct node { int value; node* next; node( int value ) : value( value ), next( NULL ) { } }; void put( node* root...
An alternative to a heap checker if you know which object may be a culprit is to manually instrument your code: unsigned nodes = 0; struct node { ~node() { --nodes; } int value; node* next; node( int value ) : value( value ), next( NULL ) { ++nodes; } }; Then: int main() { ...
4,741,857
4,741,921
Cannot find baseclass function if baseclass has two functions of same name
I have a baseclass that has two functions of same name but with different signatures in a 2-level inheritance. struct A { virtual void f(int) { } virtual void f(int, int) { }; virtual void f1(int) { } }; struct B: public A { }; struct C: public B { void f(int, int) { } void f1(int) { } }; int main() ...
Write using A::f inside the definition of C. You are a victim of name hiding! void C::f(int, int) hides void A::f(int), just because.
4,741,864
4,741,895
Design Pattern advice
I was wondering if someone could help me. Suppose I have some classes as follows: class A { ... }; class B : public A { ... } class C : public A { ... }; class D { ... }; class E : public D { ... }; class F : public D { ... }; Now I want class B to have an object of type E as a member and class C to have a object...
What's wrong with just doing exactly as you say? class A { A(D* p) : ptr(p) {} D* ptr; }; class B : public A { B() : A(new E) {} }; class C : public A { C() : A(new F) {} }; If you want to automate it a bit better, you can use an intermediate template class. class A { virtual D* getD(); }; templ...
4,741,905
4,741,981
Code Crashes Immediately After Running
Even at the bare minimum of 10 numbers to input, I get no errors but my code crashes immediately on running. I was also wondering, what should I do if I have a question similar to another question that I've already asked, but on another new problem? #include <iostream> #include <cmath> #include <fstream> #include <cstd...
vector<int> a; a[1]=2; You can't access a[1] until you've reserved space for it. You should probably use a.push_back(2) to append 2 to the end of a. You have declared primer to return int, yet it returns nothing. Either make it void or return the number of primes. i/a[ii]==floor(i/a[ii]) isn't going to do what you exp...
4,741,973
4,742,226
basic instructions on how to create a .sln with simple C++ library (no .net use) and C++ project using that library?
I am C++ beginner. I have a simple console project. with class files inside that use boost (.libs) and openCV (dlls). I want to put all my existing classes into some namespace and into seperate projects. So I need a tutorial on how to separate my application project and code library in visual studio enviroment inside o...
First you create a new W32 Project (and solution) for your new executable (exe or dll). Choose save all (or else if something goes wrong, you'll lose everything). After this you go to the solution explorer (in the right margin) and right-click on the solution-name (not the project). In the popup-menu choose Add->new P...
4,742,003
4,742,034
Shared objects and inclusion without installation in C++ under linux
I'm writing a program that has two libraries that I need to use: v8, and v8-juice. Unfortunately, v8-juice can't be compiled as a static library due to some stuff it does with templates. There's some other quirks with it that require v8 to be compiled as a shared object as well. So, when I compile my program, I end up ...
Shared libraries can be in the same folder as your executable. man ld.so: $ORIGIN and rpath ld.so understands the string $ORIGIN (or equivalently ${ORIGIN}) in an rpath specification (DT_RPATH or DT_RUNPATH) to mean the directory con- taining the application executable. Thus, an application located in...