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 |
|---|---|---|---|---|
1,122,268 | 1,122,593 | How to construct a static global variable in C++ | I'm having some trouble compiling/linking a set of classes, several of them dealing with a common global variable.
Basically, I declare and define a extern variable foo in class A and access/update it in classes B and C.
The relevant code looks like this:
A.h
extern string foo; // declare it <=== compiler error "s... | In A.h have you actually got the extern declaration within the actual class A? Your question currently says this in words but then your code snippet suggests it is at file level. The only way I can get the error you are talking about i.e. "storage class specified for foo" is for the following in A.h:
class A
{
public:
... |
1,122,749 | 1,123,265 | Implementing drag and drop with QT 4.5 using QT Creator environment | We're about to commit to Qt and C++ (sigh) to do some cross-platform development. The latest version of Qt 4.5 seems very nice as does the QT Creator IDE, which although simple compared to other IDEs, is a good way to get started.
I'm trying to understand how to do drag and drop into QT widgets from the "outside" world... | Someone on my team figured it out ---- turns out there is an option to "Promote" a widget, meaning you can subclass it to something else and then override the needed methods with no pain.
Seems to me it would have been more obvious if it said "Subclass widget..." rather than "Promote" but that's OK.
This QT Creator is ... |
1,122,785 | 1,122,794 | How to force Visual Studio preprocessor case sensitivity with #includes? | If you have a header file named ThisIsAHeaderFile.h, the following will still locate the file in Visual Studio:
#include <ThisIsAheaderFile.h>
Is there a way to enforce case sensitivity so that the #include will result in an error?
| You can't, because the Windows file system is itself case-insensitive.
If you could get into a situation where you had both RICHIE.h and richie.h, it might make sense to control case sensitivity, but you can't.
|
1,122,938 | 1,123,048 | Undefined reference - C++ linker error | I'm getting an Undefined reference error message, on this statement:
GlobalClass *GlobalClass::s_instance = 0;
Any ideas? Code is shown below:
================================================
#ifndef GLOBALCLASS_H_
#define GLOBALCLASS_H_
#include <string>
class GlobalClass {
public:
std::string get_value();
... | Are you trying to implement a Singleton class? Ie. You want only a single instance of of the class, and you want that instance available to anyone who includes the class. I think its commonly known as a Singleton, the following example works as expected:
Singleton.h:
#include <string>
class Singleton
{
public:
stat... |
1,123,013 | 1,124,020 | Undefined reference error message - C++ |
Possible Duplicate:
Undefined reference - C++ linker error
Now, I'm getting an "Undefined reference error message to 'GlobalClass::s_instance', and 'GlobalClass::instance()', respectively on these statements:
GlobalClass *GlobalClass::s_instance = 0;
GlobalClass::instance()->set_value(myAddress); \\ <== undefined ... | Further to Alex Black's response, its complaining that the GlobalClass::instance() function does not have an implementation. Which it doesn't:
static GlobalClass *instance() {
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
That really ought to be:
GlobalClass *... |
1,123,044 | 1,123,159 | When should your destructor be virtual? |
Possible Duplicate:
When to use virtual destructors?
When should your C++ object's destructor be virtual?
|
You need virtual destructor when at
least one of class methods is
virtual.
This is because the reason for virtual method is that you want to use polymorphism. Meaning you will call a method on the base class pointer and you want the most derived implementation - this is the whole point of polymorphism.
Now if you did... |
1,123,080 | 1,123,116 | Why do we need typename here? | template<class T>
class Set
{
public:
void insert(const T& item);
void remove(const T& item);
private:
std::list<T> rep;
}
template<typename T>
void Set<T>::remove(const T& item)
{
typename std::list<T>::iterator it = // question here
std::find(rep.begin(),rep.end(),itme);
if(it!=rep.end()) rep.er... | In general, C++ needs typename because of the unfortunate syntax [*] it inherits from C, that makes it impossible without non-local information to say -- for example -- in A * B; whether A names a type (in which case this is a declaration of B as a pointer to it) or not (in which case this is a multiplication expressio... |
1,123,115 | 1,125,750 | Boost Graph Library and Visitors | I'm writing a library for manipulating bond graphs, and I'm using the Boost Graph Library to store the data for me. Unfortunately, I can't seem to figure out how to implement a proper visitor pattern using it, as you can't subclass out vertices - you must rely on 'properties' instead. The visitor framework provided i... | What do you mean, you can't subclass out vertices? You can use your own vertex class, it's just a matter of specifying it in the Graph typedef. You can even use members as properties when working with BGL algorithms.
As for the other way around (which is harder IMO), you need to create a vertex property list and access... |
1,123,455 | 1,123,493 | Should every C++ programmer read the ISO standard to become professional? | Should every C++ programmer read the ISO standard to become professional?
| No. C++ standard is more like a dictionary - something where you look up specific things that concern you at any given moment. It doesn't make a good (or useful) reading if you treat it as a simple book to read from beginning to end.
If the question were whether every professional C++ programmer should have an ISO stan... |
1,123,587 | 1,123,646 | c++ std::fstream behaviour on MacOS | On MacOS with gcc4.2 should the following code create a new file if none exists?
#include <fstream>
void test () {
std::fstream file ("myfile.txt", std::ios::in | std::ios::out);
}
By my logic it should, either open up an existing file for read/writing or create a new empty file for read/writing. But the behaviou... | First of all, I have no idea why you think that fopen("r+") creates a file if it doesn't exist - according to ISO C & C++, it does not, it just opens an existing file for read/write. If you want to create a file with fopen, you use "w+".
For streams, you just specify trunc:
std::ofstream file ("myfile.txt",
std::io... |
1,123,700 | 1,123,730 | Projects for C++ Beginner/Intermediate? | I really want to learn more about C++. I know the basics, and I know the concepts, and I have even been able to create C++ projects myself, but my problem is being able to view, fix, and add to code I haven't written myself. I have looked at some open source projects on sourceforge, etc, but many of them are so big or ... | If you are already able to create own projects, I think the best way to learn how to read&change someone's code is to get job in software company. They even will pay for it :)
|
1,123,725 | 1,123,759 | Why should default parameters be added last in C++ functions? | Why should default parameters be added last in C++ functions?
| To simplify the language definition and keep code readable.
void foo(int x = 2, int y);
To call that and take advantage of the default value, you'd need syntax like this:
foo(, 3);
Which was probably felt to be too weird. Another alternative is specifying names in the argument list:
foo(y : 3);
A new symbol would ha... |
1,123,880 | 1,123,886 | Am I using new operator correctly? | I have the following pointer.
char **x = NULL;
x is will point to an array of pointers. So is the following code correct?
x = new (nothrow) (*char)[20];
and we will dealocate it using
delete[] x;
Is
x = (char **) malloc(sizeof(char **) * 20);
and
x = new (nothrow) (*char)[20];
equivalent?
| No, that code has syntax errors. The asterisk goes after the type name, to form a pointer to that type. So it's:
char*
not:
*char
It's weird that you have this right in the "C-style" example using malloc(), but not in C++.
As many commenters have kindly enough pointed out, there are other issues with the malloc() and... |
1,123,975 | 1,124,046 | How to override member of base class after inheritance in C++ | i have this :
class A {
public :
A(int i ) : m_S(i)
{
m_Pa = new Foo(*this) ;
}
private :
int m_S ;
Foo* m_Pa;
}
and derived class
class B : public A {
public :
B() : A (242)
{
// here i like to override the A class m_Pa me... | your m_Pa should be protected than you can call like:
B() : A (242), m_Pa(12)
{
}
or
B() : A (242)
{
m_PA = 55
}
or you should make a public or protected function which changes m_Pa
class A {
public :
A(int i ) : m_S(i)
{
m_Pa = new Foo(*this) ;
}
v... |
1,124,129 | 1,124,166 | High-level HTTP client library for native C/C++ in Win32 | Are there no "high-level" HTTP libraries for native C/C++ in Win32 or am I just looking in the wrong places?
By "high-level" I mean an API that lets me do HTTP web requests/responses in C++ with "about the same" abstraction level as the .NET framework (but note that using C++/CLI is not an option for me).
How to do som... | Win32 provides the Internet* functions.
http://msdn.microsoft.com/en-us/library/aa385473(VS.85).aspx
You'll need to do an (IIRC, I haven't touched these APIs in over 10 years) InternetOpenURL and InternetReadFile.
|
1,124,223 | 1,153,840 | simple rtsp broadcast example source | I want to broadcast the screen (not a static screen) of my program using rtsp/rtp since this way a mobile phone (at least the more recent ones) can view the stream.
I'm looking for a simple example program which takes the frames I offer, encodes it with a codec and then sends this (using rtsp) to any clients attached.
... | this seems to be pretty much what I was looking for: live555.com
Useful libraries and code examples of how to stream stuff from your own app
R
|
1,124,232 | 1,124,362 | Getting started guide for Boost.Spirit? | I've been looking recently at Boost.Spirit (the version included in Boost 1.39), however I'm quite confused from the docs alone. What I'm looking for is for an example of a toy language implemented with Boost.Spirit -- something along the lines of a tiny Javascript or Lua or so, where you basically create an AST and pr... | An introductory article from CP
A JSON parser implemented using Boost.Spirit from CodeProject
Spirit Application Repository
|
1,124,340 | 1,129,672 | Any ideas why QHash and QMap return const T instead of const T&? | Unlike std::map and std::hash_map, corresponding versions in Qt do not bother to return a reference. Isn't it quite inefficient, if I build a hash for quite bulky class?
EDIT
especially since there is a separate method value(), which could then return it by value.
| const subscript operators of STL containers can return a reference-to-const because they flat out deny calls to it with indexes that do not exist in the container. Behaviour in this case is undefined. Consequently, as a wise design choice, std::map doesn't even provide a const subscript operator overload.
QMap tries to... |
1,124,466 | 1,124,549 | hash_map and map which is faster? less than 10000 items | vs2005 support
::stdext::hash_map
::std::map.
however it seems ::stdext::hash_map's insert and remove OP is slower then ::std::map in my test.
( less then 10000 items)
Interesting....
Can anyone offored a comparision article about them?
| It is not just about insertion and removal. You must consider that memory is allocated differently in a hash_map vs map and you every time have to calculate the hash of the value being searched.
I think this Dr.Dobbs article will answer your question best:
C++ STL Hash Containers and Performance
|
1,124,534 | 1,124,539 | Computing length of array | I have a C++ array declared as mentioned below:
CString carray[] =
{
"A",
"B",
"C",
"D",
"E"
}
I want to determine the length of carray at runtime. I am doing:
int iLength = sizeof(carray)/sizeof(CString);
Is this correct?
| Yes. In case the declared element type ever changes, you could also write
int iLength = sizeof(carray)/sizeof(carray[0]);
|
1,124,571 | 1,124,588 | Get list of static libraries used in an executable | Since ldd lists only the dynamic libraries, is there a way to extract the information about the static libraries used to create the executable?
| ldd <exe filename> shows dynamically linked libraries
nm <exe filename> shows the symbols in the file.
To see which symbols come from static libraries requires running nm against those libraries to get a list of the symbols (functions, etc.) in them, then comparing them to what your list of symbols from nm <exe filenam... |
1,124,634 | 1,124,759 | Call destructor and then constructor (resetting an object) | I want to reset an object. Can I do it in the following way?
anObject->~AnObject();
anObject = new(anObject) AnObject();
// edit: this is not allowed: anObject->AnObject();
This code is obviously a subset of typical life cycle of an object allocated by in placement new:
AnObject* anObject = malloc(sizeof(AnObject));
a... | Don't get sucked in by the FQA troll. As usual he gets the facts wrong.
You can certainly call the destructor directly, for all objects whether they are created with placement new or not. Ugly is in the eye of the beholder, it is indeed rarely needed, but the only hard fact is that both memory allocation and object cre... |
1,124,726 | 1,124,733 | Visual Studio 2008 build errors | I'm trying to compile an old project that was originally designed for Visual Studio 2008 SP0 (I'm using SP1 now). I'm getting these errors.
Error 51 error LNK2019: unresolved external symbol "unsigned long __cdecl GetDeviceState(enum DEVICES_ENUM,enum DEVICE_STATE_ENUM &,int &)" (?GetDeviceState@@YAKW4DEVICES_EN... | I would suggest to check the files mentioned in the last row.
|
1,125,349 | 1,125,553 | How do I set the executable attributes with qmake for a c++ project? | I use buildbot to compile my Qt/C++/nmake project.
I would like to add the version number to the executable and the company details (on the properties of the file).
Does anybody know where I can set this information?
Note: I am using buildbot not Visual Studio so I need a command line way of doing this.
| Unless your version will remain static (i.e. you are only reporting a major build versions or you don't incorporate the version control revision into your version number) you will likely want the version to be generated as part of the build. This could be done in the pro file as another answer indicated but this would ... |
1,125,412 | 1,125,699 | How to do an active sleep? | I am running some profiling tests, and usleep is an useful function. But while my program is sleeping, this time does not appear in the profile.
eg. if I have a function as :
void f1() {
for (i = 0; i < 1000; i++)
usleep(1000);
}
With profile tools as gprof, f1 does not seems to consume any time.
What I a... | What kind of a system are you on? In UNIX-like systems you can use setitimer() to send a signal to a process after a specified period of time. This is the facility you would need to implement the type of "active sleep" you're looking for.
Set the timer, then loop until you receive the signal.
|
1,126,071 | 1,126,079 | Accessing members of an array of structures in C++ | Working through C++ Primer Plus and am trying to cin data to a dynamically allocated array of structures. One of the items is a char array. How do I write to these struct members? Posting code of my wrong attempt so you can see what I'm trying to do.
#include <iostream>
using namespace std;
struct contributions
{
... | Try using std::string instead of char[20] for name and the sample should work just fine.
struct contributions
{
std::string name;
double dollars;
};
also change the access to
ptr[i].name
|
1,126,118 | 1,126,146 | where can I find a good boost reference? | I'd like to have a good up-to-date reference for boost by my side, and the only books I found are the following:
Beyond the C++ Standard Library: An Introduction to Boost
The C++ Standard Library Extensions: A Tutorial and Reference
Both books are somewhat dated, and I am sure boost has been evolving.
Obviously I ... | Try this one out:
http://man.leftworld.net/develop/asio/reference/index.html
http://alexott.blogspot.com/search/label/boost
http://www.boost.org/doc/
http://torjo.com/tobias/
http://docs.huihoo.com/boost/1-33-1/libs/multi_index/doc/reference/index.html
|
1,126,445 | 1,126,455 | Why does strlen() return a 64-bit integer? Am i missing something? | When compiling a 64bit application, why does strlen() return a 64-bit integer? Am i missing somthing?
I understand that strlen() returns a size_t type, and by definition this shouldn’t change, but... Why would strlen need to return a 64-bit integer?
The function is designed to be used with strings. With that said:
Do p... | It looks like, when compiling for a 64-bit target, size_t is defined as 64-bit. This makes sense, since size_t is used for sizes of all kinds of objects, not just strings.
|
1,126,730 | 1,126,742 | How to find the width of a String (in pixels) in WIN32 | Can you measure the width of a string more exactly in WIN32 than using the GetTextMetrics function and using tmAveCharWidth*strSize?
| Try using GetTextExtentPoint32. That uses the current font for the given device context to measure the width and height of the rendered string in logical units. For the default mapping mode, MM_TEXT, 1 logical unit is 1 pixel.
However, if you've changed the mapping mode for the current device context, a logical unit ... |
1,126,812 | 1,126,837 | Class issue, adding a day | I'm trying to make the add_day function work, but I'm having some trouble. Note that I can't make any changes to the struct (it's very simplistic) because the point of the exercise is to make the program work with what's given. The code is
#include "std_lib_facilities.h"
struct Date{
int y, m, d;
Date(in... | The linker error is because you are not defining the constructor.
Date::Date( int yr, int mo, int day ) : y(year), m(month), d(day)
{
}
For the add_day question: you are correct that you need to change the return type. It should return a Date object. You can construct a new Date object and return it with the day value... |
1,126,877 | 1,126,990 | Edit the frame rate of an avi file | Is it possible to change the frame rate of an avi file using the Video for windows library? I tried the following steps but did not succeed.
AviFileInit
AviFileOpen(OF_READWRITE)
pavi1 = AviFileGetStream
avi_info = AviStreamInfo
avi_info.dwrate = 15
EditStreamSetInfo(dwrate) returns -2147467262.
| I'm pretty sure the AVIFile* APIs don't support this. (Disclaimer: I was the one who defined those APIs, but it was over 15 years ago...)
You can't just call EditStreamSetInfo on an plain AVIStream, only one returned from CreateEditableStream.
You could use AVISave, then, but that would obviously re-copy the whole fil... |
1,127,326 | 1,134,243 | Advise HTMLElementEvents2 sink (MSDN website) | From the msdn website
void CMyClass::ConnectEvents(IHTMLElement* pElem)
{
HRESULT hr;
IConnectionPointContainer* pCPC = NULL;
IConnectionPoint* pCP = NULL;
DWORD dwCookie;
// Check that this is a connectable object.
hr = pElem->QueryInterface(IID_IConnectionPointContainer, (void**)&pCPC);
... | ATLEventHandling Sample
Edit:
void CMyClass::ConnectEvents(IHTMLElement* pElem)
{
typedef IDispEventImpl<2, CMyClass, DIID_HTMLElementEvents2, LIBID_MSHTML, 4, 0> IMyClassHTMLElementEvents2Sink;
IMyClassHTMLElementEvents2Sink::DispEventAdvise(pElem);
}
Because you have multiple functions DispEventAdvise on the... |
1,127,328 | 1,127,344 | source code of c/c++ functions | I wanted to have a look at the implementation of different C/C++ functions (like strcpy, stcmp, strstr). This will help me in knowing good coding practices in c/c++. Could you let me know where can I find it?
Thanks.
| You could check out a copy of glibc, which will have the source code for all C functions in the C standard library. That should be a good starting place.
|
1,127,350 | 1,127,392 | difference of variable in placement of private keyword in a MFC class | Using the following code snippet as an illustration to my question:
// #includes and other macros
class MyClass : public CFormView
{
private:
DECLARE_DYNCREATE(MyClass)
bool privateContent;
...
public:
bool publicContent;
...
};
class MusicPlayer
{
public:
AppClass *the... | If you look at the definition of DECLARE_DYNCREATE, you will see that it uses another macro:
// not serializable, but dynamically constructable
#define DECLARE_DYNCREATE(class_name) \
DECLARE_DYNAMIC(class_name) \
static CObject* PASCAL CreateObject();
And if you look at that macro, DECLARE_DYNAMIC, you'll see... |
1,127,443 | 1,127,473 | What is going on with 'function pointer' or 'reference to function' as argument to function in C++? | In Numerical Recipes they use something I've never seen done before, and couldn't easily find info on:
void fun( std::vector<double> derivatives(const double, const std::vector<double> &) ) { ...; derivatives(...); ...; }
Which I'm guessing is passing the function by reference (is this correct)? Why would this be favo... | This is equivalent to
void fun( std::vector (*derivatives)(const double, const std::vector &) ) {
...; derivatives(...); ...;
}
And similar to how
void f(int derivatives[]) { ... }
is equivalent to the following
void f(int *derivatives) { ... }
So the parameter is a function pointer. Functions as parameters ar... |
1,127,460 | 1,127,503 | How to "add reference" in C++ | I'm new to C++ and there's something I just completely don't get. In C#, if I want to use an external library, log4net for example, I just add a reference to the log4net DLL and its members are automatically available to me (and in IntelliSense). How do I do that in non-managed C++?
| Often, the library comes with 1) a header file (.h) and 2) a .lib file in addition to the .dll.
The header file is #include'ed in your code, to give you access to the type and function declarations in the library.
The .lib is linked into your application (project properties -> linker -> input, additional dependencies).... |
1,127,496 | 1,127,512 | Namespace loop or code leak in boost::function? | I'm really baffled by this. Have I managed to do something to cause this, or is it an unclosed namespace block in boost, or some bug in VS c++ 2008? I'm definitely sure I've closed all my own namespaces properly, all includes are outside of and above them, and all my header files got include guards.
alt text http://low... | Visual C++'s intellisense is a bit quirky. Sometimes it screws up. That doesn't mean there is a problem in your code. Always take C++ intellisense with a grain of salt.
|
1,127,616 | 1,128,702 | How do I unit test a protected method in C++? | How do I unit test a protected method in C++?
In Java, I'd either create the test class in the same package as the class under test or create an anonymous subclass that exposes the method I need in my test class, but neither of those methods are available to me in C++.
I am testing an unmanaged C++ class using NUnit... | Assuming you mean a protected method of a publicly-accessible class:
In the test code, define a derived class of the class under test (either directly, or from one of its derived classes). Add accessors for the protected members, or perform tests within your derived class . "protected" access control really isn't very ... |
1,127,617 | 1,127,671 | What's wrong with this algorithm implementation [Sieve of Erathosthene] | I'm trying to implement the Sieve of Eratosthene in C++. However after several attempts at this I always get runtime errors. I'm thinking this has to do with the state of iterators being used get corrupted somewhere. I can't put my finger on it though. Here is my code:
//Sieves all multiples of the current sequenc... | This line:
num_list.erase(elements_iter);
Is going to cause you problems since you are modifying the list while iterating it. You could do this to avoid that problem:
elements_iter = num_list.erase(elements_iter);
ETA: Removed stuff about erase() invalidating other iterators (looks like they are safe in this case) -... |
1,127,738 | 1,127,766 | cannot call member function without object | This program has the user input name/age pairs and then outputs them, using a class.
Here is the code.
#include "std_lib_facilities.h"
class Name_pairs
{
public:
bool test();
void read_names();
void read_ages();
void print();
private:
vector<string>names;
vector<double>ages;... | You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:
int main()
{
Name_pairs np;
cout << "Enter names and ages. Use 0 to cancel.\n";
while(np.test... |
1,127,918 | 1,128,152 | Interfaces vs Templates for dependency injection in C++ | To be able to unit test my C++ code I usually pass the constructor of the class under test one or several objects that can be either "production code" or fake/mock objects (let's call these injection objects). I have done this either by
Creating an interface that both the "production code" class and the fake/mock clas... | I think interface option is better, but one doesn't have to create common base class just for test. You can inherit your mock class from production class and override necessary methods. You'll have to make the methods virtual though, but that's how tools like mockpp work and they also allow automate this process a litt... |
1,127,936 | 1,128,006 | understanding String^ in C++ .Net | I remember seeing somewhere there "^" operator is used as a pointer operator in Managed C++ code. Hence "^" should be equivalent to "*" operator right??
Assuming my understanding is right, when I started understanding .Net and coded a few example programs, I came across some code like this:
String ^username; //my unde... | String^ is a pointer to the managed heap, aka handle. Pointers and handles are not interchangable.
Calling new will allocate an object on an unmanaged heap and return a pointer. On the other hand, calling gcnew will allocate an object on a managed heap and return a handle.
The line username = "XYZ" is merely a compiler... |
1,128,096 | 1,128,259 | C++ string comparison in one clock cycle | Is it possible to compare whole memory regions in a single processor cycle? More precisely is it possible to compare two strings in one processor cycle using some sort of MMX assembler instruction? Or is strcmp-implementation already based on that optimization?
EDIT:
Or is it possible to instruct C++ compiler to remove... | Not really. Your typical 1-byte compare instruction takes 1 cycle.
Your best bet would be to use the MMX 64-bit compare instructions( see this page for an example). However, those operate on registers, which have to be loaded from memory. The memory loads will significantly damage your time, because you'll be going out... |
1,128,150 | 1,128,453 | Win32 API to enumerate dll export functions? | I found similar questions but no answer to what I am looking for. So here goes:
For a native Win32 dll, is there a Win32 API to enumerate its export function names?
| dumpbin /exports is pretty much what you want, but that's a developer tool, not a Win32 API.
LoadLibraryEx with DONT_RESOLVE_DLL_REFERENCES is heavily cautioned against, but happens to be useful for this particular case – it does the heavy lifting of mapping the DLL into memory (but you don't actually need or want to u... |
1,128,188 | 1,128,208 | How do I convert a LPWSTR to a GUID? | I'm working with the Windows 7 audio APIs, and I've hit a wall.
Basically, I need to take an IAudioSessionControl2* and get an ISimpleAudioVolume* out of it.
Now, it looks like I can call on IAudioSessionManager->GetSimpleAudioVolume() using the value of IAudioSessionControl2->GetSessionInstanceIdentifier(...). Note t... | Try CLSIDFromString. A CLSID is actually defined as:
typedef GUID CLSID;
therefore you can use CLSIDFromString to generate a GUID. Here's some sample code:
LPWSTR guidstr;
GUID guid;
...
HRESULT hr = CLSIDFromString(guidstr, (LPCLSID)&guid);
if (hr != S_OK) {
// bad GUID string...
...
}
Warning
Things that ... |
1,128,212 | 1,128,243 | How do you pass information from an 8 byte array into variable bit size data containers? | I have an 8 byte message where the differing chunks of the message are mapped to datums of different types (int, bool, etc.), and they vary in bit sizes (an int value is 12 bits in the message, etc.). I want to pass only the bits a datum is concerned with, but I am not sure if there is a better way. My current though... | Are the messages alway of the same format/order? Ie. 12bitsInt|8bitsChar|etc. If so a simple solution would be to set up appropriate bitmasks to grab each particular value. Ie. if the first 12 bits (low order) corresponded to an integer we could do:
__uint64 Message; // Obviously has data in it.
int IntPortion = Messag... |
1,128,458 | 1,128,527 | Memory Leak Detecting and overriding new? | I am attempting to get Memory leak detection working with the help of these two articles:
http://msdn.microsoft.com/en-us/library/e5ewb1h3%28VS.80%29.aspx
http://support.microsoft.com/kb/q140858/
So in my stdafx.h I now have:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define new new(_NORMAL_BLO... | You can use pragma directives to save and restore the new macro when undefing for overloads. See [MSDN](http://msdn.microsoft.com/en-us/library/hsttss76(VS.71).aspx) for the exact syntax.
E.g.
#pragma push_macro("new")
#undef new
void FAR* operator new(size_t cb);
#pragma pop_macro("new")
You can put these in heade... |
1,128,501 | 1,128,542 | Why do implicit conversion member functions overloading work by return type, while it is not allowed for normal functions? | C++ does not allow polymorphism for methods based on their return type. However, when overloading an implicit conversion member function this seems possible.
Does anyone know why? I thought operators are handled like methods internally.
Edit: Here's an example:
struct func {
operator string() { return "1";}
ope... | Conversion operators are not really considered different overloads and they are not called based on their return type. The compiler will only use them when it has to (when the type is incompatible and should be converted) or when explicitly asked to use one of them with a cast operator.
Semantically, what your code is ... |
1,128,535 | 1,128,598 | STL vector reserve() and copy() | Greetings,
I am trying to perform a copy from one vector (vec1) to another vector (vec2) using the following 2 abbreviated lines of code (full test app follows):
vec2.reserve( vec1.size() );
copy(vec1.begin(), vec1.end(), vec2.begin());
While the call to vec2 sets the capacity of vector vec2, the copying of data to ve... | As noted in other answers and comments, you should just use vector's built-in functionality for this. But:
When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up ... |
1,128,875 | 1,131,234 | How do I overload the << operator? | I intend to call a function whenever m_logger<<"hello"<<"world" is called. m_logger is of type ofstream.
So i decide to overload << with following signature
friend ofstream& operator<<(ofstream &stream,char *str);
However the vc compiler gives following error:
error C2666: 'operator <<' : 6 overloads have similar con... | The problem is that ofstream is already overloaded this way. If you make mlogger of a new type holding an ofstream, then you can do this:
class mlogger_t {
public:
ofstream stream;
...
}
mlogger_t& operator<<(mlogger_t& stream, const string& str) {
stream.stream << str;
...
}
//EDIT: here is how to ma... |
1,128,929 | 1,129,005 | Possible to break a loop when outside of it? | After trying to make a while(bool) loop and it failing because I couldn't see the contents of the vectors because there was nothing in them, I made a while(true) loop with the intention of breaking out if the user inputs a 0. Here are the important portions of the code.
Edit: Working code, but what does|= mean?
#includ... | If you change the problem and view it upside down it becomes quite simple.
Change your setter methods to actually return the value that was just entered. I also made age a local variable of the method to prevent side effects from creeping :
Double Name_pairs::read_ages()
{
Double age;
cout << "Enter correspo... |
1,128,937 | 1,129,964 | C++ WxWidgets: Single log window for messages from Multiple Threads | What's the best/proper method to collect log messages from multiple threads and have them all be displayed using a window? (while the threads are running).
I am currently trying to redirect stdout (cout) in to a wxTextCtrl but failing miserably when attempting to do so over multiple threads. Any help would be apprecia... | Logging has had a few major updates recently in the wxWidgets trunk, you can read about them here. One of them is to add support for logging from threads other than the main thread.
|
1,128,945 | 1,147,980 | Get an audio session's volume level | Does anyone know how to get the current volume level of an audio session* in Vista or 7?
I've got the IAudioSessionControl2 and IAudioSessionManager2 instances you need to listen for volume changes, but actually getting the current volume is proving elusive.
*by audio session I mean (roughly) the per-application audio ... | Actually IAudioSessionManager::GetSimpleAudioVolume IS what you're looking for.
An audio session is identified by two (or three) things: The session guid, the process ID and the cross process flag (if the cross process flag is specified when the stream is created, the process ID is ignored).
The simple audio volume c... |
1,129,012 | 1,129,077 | How do I get IP address from socket In Windows | I have the DWORD socket in windows. I need to know if it is a connection that goes out to the internet or if it is a local connection, to some form of localhost. Is there a good way to get the address that the socket is connected to in windows from just the socket? Or is there a better way to tell if the connection ... | You probably want to call getpeername(). Using it is pretty basic, you pass a sockaddr pointer and a length and it fills in the data for you.
As far as determining if the connection is local, getaddrinfo() can give you a list of all available local addresses. You would compare the result of getpeername() to the local ... |
1,129,176 | 1,129,192 | Sorting with two vectors | I'm wondering if it's possible if you have, for example, a vector<string> and a vector<double> with corresponding pairs, to sort the vector<string> alphabetically while keeping the pairs matched up.
I know this can be done by creating a class that holds both values and just sorting that, but I'd rather keep two separat... | If you intend to use std::sort, you will need to use a datastructure like a pair.
You can, of course, manually sort the vectors, and essentially reimplement std::sort.
This question really depends on a great number of other questions, such as:
How many items will be in the vectors?
How critical is performance?
Do you ... |
1,129,183 | 1,129,186 | Question about inheritance | class B{
private:
void DoSomething();
}
class W{
private:
class D: public B{
}
D d;
}
Can I call private member function in base class of D in the scope of class W?
| Nope. You can never call a private member function from anywhere except the class that owns it. If you want derived classes to be able to access it, declare it protected instead.
You can also declare D to be a 'friend' of class B; that would allow D to access B.DoSomething(). However, this approach is usually frowne... |
1,129,191 | 1,129,236 | variable allocation in a nested loop question | because obj, the playingCard object is created inside a nested for loop does that mean after the second for loop completes, obj gets deallocated from the stack each time?
and a small side question,
does a compiler use the stack (similar to recursion) to keep track of loops and nested loops?
for(int c = 0;c<nElem... | It gets constructed and deconstructed every iteration.
However, on the stack, the concept of allocation is (for at least VS and GCC) more hazy. Since the stack is a contiguous block of memory, premanaged by the compiler, there's no real concept of allocating and deallocating in the way that there is for heap allocation... |
1,129,194 | 1,129,200 | Download a URL in C++ | I want to be able to download a URL in C++. Something as simple as:
std::string s;
s=download("http://www.example.com/myfile.html");
Ideally, this would include URLs like:
ftp://example.com/myfile.dat
file:///usr/home/myfile.dat
https://example.com/myfile.html
I was using asio in Boost, but it didn't really seem ... | Not a direct answer, but you might like to consider libCURL, which is almost exactly what you describe.
There are sample applications here, and in particular this demonstrates how simple usage can be.
|
1,129,519 | 1,129,712 | Fixed Length Float in C/C++? | I was wondering whether it is possible to limit the number of characters we enter in a float.
I couldn't seem to find any method. I have to read in data from an external interface which sends float data of the form xx.xx. As of now I am using conversion to char and vice-versa, which is a messy work-around. Can someone ... | Rounding a float (that is, binary floating-point number) to 2 decimal digits doesn't make much sense because you won't be able to round it exactly in some cases anyway, so you'll still get a small delta which will affect subsequent calculations. If you really need it to be precisely 2 places, then you need to use decim... |
1,129,710 | 1,129,724 | User-defined cast to string in C++ (like __repr__ in Python) | How do I make something like user-defined __repr__ in Python?
Let's say I have an object1 of SomeClass, let's say I have a function void function1(std::string). Is there a way to define something (function, method, ...) to make compiler cast class SomeClass to std::string upon call of function1(object1)?
(I know that ... | Define a conversion operator:
class SomeClass {
public:
operator std::string () const {
return "SomeClassStringRepresentation";
}
};
Note that this will work not only in function calls, but in any context the compiler would try to match the type with std::string - in initializations and assignments, op... |
1,129,894 | 1,130,035 | Why can't you use offsetof on non-POD structures in C++? | I was researching how to get the memory offset of a member to a class in C++ and came across this on wikipedia:
In C++ code, you can not use offsetof to access members of structures or classes that are not Plain Old Data Structures.
I tried it out and it seems to work fine.
class Foo
{
private:
int z;
int fu... | Short answer: offsetof is a feature that is only in the C++ standard for legacy C compatibility. Therefore it is basically restricted to the stuff than can be done in C. C++ supports only what it must for C compatibility.
As offsetof is basically a hack (implemented as macro) that relies on the simple memory-model supp... |
1,130,106 | 1,130,112 | Linking with a debug/release lib with qmake/Qt Creator | I am using Qt Creator and have a Qt GUI project that depends on a C++ static library project. I want to link the release version of the GUI app with the release build of the .lib and the debug release of the GUI app with the debug .lib. I have found out how to add additional libraries to the project by including a li... | In your project file you can do something like this
debug {
LIBS += -L./libfolder -lmydebuglib.lib
}
release {
LIBS += -L./libfolder -lmyreleaselib.lib
}
The bit inside the debug braces is used if DEBUG has been added to the CONFIG qmake variable, similarly stuff inside the release brackets is included if REL... |
1,130,360 | 1,130,408 | Checking digital signature programmatically | I have the exe for the project im working on signed by a digital signature which means when it asks for admin rights it shows the company name. This works very well but if you modify the exe it will still work and show unknown there instead.
Is there a way to check the digital signature to see if it is valid when you ... | Here is a sample program(it uses WinVerifyTrust function) that verifies signature, but I'm not sure that it will work under Windows 7. You should try it.
|
1,130,440 | 1,130,452 | Is it possible to assign object to int? | I have a CCounter class which holds and integer value protected by mutex. I've defined several operators like post/pre inc/dec returning an integer so I can do:
CCounter c(10);
int i = c++;
but what do I do with a simple assignment like i = c ? I tried to define friend operator= but it gives me
operator=(int&, const C... | You need to define a casting operator that casts from CCounter to int. Add this member to your class:
operator int() const {
return ...;
}
|
1,130,761 | 14,085,970 | compile cdrtools with mingw | I need to compile cdrtools with mingw (to avoid cygwin dependancy).
It was done somehow long time ago but sources are not available anymore:
http://web.archive.org/web/20040707140819/http://cdrtools.bootcd.ru/
Does anyone know how to compile cdrtools with mingw?
Thanks.
| These so called "forks" both have less functionality than the original software but they are full of bugs and dead since many years.
dvdrtools started with a cdrtools version from 2001 (now 12 years old), removed the original DVD support code and replaced that by something that may work with a Pioneer A03. It did not d... |
1,130,906 | 1,130,918 | Can I add breakpoint on CreateProcess in VS | Can I add breakpoint on windows CreateProcess API in Visual studio like I can do in Windbg?
| Yes - Go "Debug / New breakpoint / Break at function..." and paste this:
{,,kernel32.dll}_CreateProcessW@40
into the Function box.
That assumes a Unicode build - replace W with A for ANSI builds.
A bit of explanation: the @40 piece is part of the stdcall calling convention, and gives the number of bytes of parameters ... |
1,131,064 | 1,131,250 | Transfer a boost::ptr_list from a library to a client | I dynamically load a library in C++ like described here.
My abstract base class looks like this:
#include <boost/ptr_container/ptr_list.hpp>
class Base {
public:
virtual void get_list(boost::ptr_list<AnotherObject>& list) const = 0;
};
And my library now provides a derived class Derived
class Derived : public Base... |
Use a std::list<shared_ptr<AnotherObject> >.
Pass a custom deleter to the shared_ptr that calls the proper delete.
|
1,131,221 | 1,131,247 | Link Checker With ShellExecute? | I've been tasked with going through a database and checking all of the links, on a weekly schedule. I normally work in PHP, but doing this in PHP would be very slow (it actually would timeout the page after about 100 URLs), so I decided to make a quick C++ app.
Admitidly, I haven't used C++ since college, so I'm a bit ... | I think you answered your own question. ShellExecute is really not appropriate for this task, and something like CURL would be better.
|
1,131,582 | 1,131,597 | Error while using Boost with Visual Studio 2008 | I am using Boost with Visual Studio 2008 and I have put the path to boost directory in configuration for the project in C++/General/"Additional Include Directories" and in Linker/General/"Additional Library Directories". (as it says here: http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#build-from... | Where is the file located, and which include path did you specify? (And how is the file #include'd)
There's a mismatch between some of these But it's impossible to say what's wrong when you haven't shown what you actually did.
Edit:
Given the paths you mentioned in comments, the problem is that they don't add up.
If th... |
1,131,639 | 1,132,514 | How are float and doubles represented in C++ (gcc)? | How are floating points represented and interpreted by a compiler. I am trying to understand that so I can easily interpret what byte array would mean for floats and doubles.
Thanks
| To actually interpret it you would probably not want to treat it as bytes anyway because mantisa boundries don't align to an 8bit boundry.
Something along the lines of:
mantisa = (*(unsigned int *)&floatVal) | MANTISA_MASK;
exp = ((*(unsigned int *)&floatVal) | EXP_MASK ) >> EXP_SHIFT;
sign = ((*(unsigned in... |
1,132,175 | 1,132,396 | Custom sorting, always force 0 to back of ascending order? | Premise
This problem has a known solution (shown below actually), I'm just wondering if anyone has a more elegant algorithm or any other ideas/suggestions on how to make this more readable, efficient, or robust.
Background
I have a list of sports competitions that I need to sort in an array. Due to the nature of this ... | Isn't it just this?
if (a==b) return other_data_compare(a, b);
if (a==0) return 1;
if (b==0) return -1;
return a - b;
|
1,132,453 | 1,132,965 | Is there a way to prevent a "keyword" from being syntax highlited in MS Visual Studio | MS Visual Studio editor highlights some non-keyword identifiers as keywords
in C++ files. Particularly "event" and "array" are treated as keywords.
That's very annoying to me, because they are not C++ keywords.
I know how to add my own keywords to the list of syntax-highlighted identifiers,
but how to remove existing b... | It doesn't look like a disable-syntax-coloring feature is exposed in a user-friendly way.
The only way I can think of selectively disabling syntax coloring is to create a new syntax coloring plugin for the IDE, and list all of the keywords you want colored. Microsoft gives information in this article on how to accompl... |
1,132,924 | 1,132,962 | What aspect oriented language is a good place to start for a c++ programmer | The only one I know of is called "e" which is used for test bench design in hardware design and verification but I want something for general purpose programming.
| Aspect oriented programming isn't so much a defining feature of a language, it's a paradigm that can be applied to many existing programming languages. You'd be hard-pressed to find a specific language that's aspect oriented in nature, though one could exist that makes adding cross-cutting concerns easy out of the box... |
1,132,951 | 1,132,994 | Specialize member function template of a class template | I have the following code:
#include <stdio.h>
template<int A>
class Thing
{ // 5
public:
Thing() :
data(A) {
}
template<int B>
Thing &operator=(const Thing<B> &other) {
printf("operator=: A = %d; B = %d\n", A, B);
printf("this->data = %d\n", data... | I don't think you need to specialize it, can't you just provide an overload for operator=?
template<int A>
class Thing
{ // 5
public:
Thing() :
data(A) {
}
template<int B>
Thing &operator=(const Thing<B> &other) {
printf("operator=: A = %d; B = %d\n", A, B);
... |
1,132,987 | 1,133,258 | C++ interacting with a dynamic webpage? | I was thinking recently about what projects I could start that would be of use to me and this came up. I post on various forums a daily updated journal entry that is the same for each forum. I also keep a log of the journal entries as individual docx files on my hard drive. I figured it would be great if I could cre... | That problem can be approached as simply as using cURL (or a similar library) to GET pages and POST form data, or it could be as complicated as writing a Firefox XPCOM extension.
|
1,133,170 | 1,133,223 | array of integers vs. pointer to integer in c++ | If I have int x[10] and int *y, how can I tell the difference between the two?
I have two ideas:
sizeof() is different.
&x has different type --- int (*p)[10] = &x works but not int **q
= &x.
Any others?
In some template library code, I need to determine whether a pointer is a "real" pointer or degenerated from a... | The sizeof idea is not very good, because if the array happens to have a single element, and the element type happens to be the same size as a pointer, then it will be the same size as the size of a pointer.
The type matching approach looks more promising, and could presumably be used to pick a template specialization ... |
1,133,534 | 1,133,921 | #import'ing msado15.dll, is there another way? | In all ADO C++ code I can find, there is a line
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename("EOF", "EndOfFile")
I understand that this line "incorporate information from a type library", and that "The content of the type library is converted into C++ classes". What?
I'm also lo... | It's been a while since I played with that stuff, so what follows is a bit vague and may even be slightly inaccurate, but I hope it still helps:
The DLL implements COM interfaces, and contains a type library describing those interfaces. Among other things, a type library contains the IDL of those interfaces, which shou... |
1,133,598 | 1,133,646 | Qt and C++ - undefined reference to slot | I have a build error with a slot in Qt. I have an class which has a public slot:
void doSomething();
In constructor of this class i do:
this->connect( ui->textFrom, SIGNAL(returnPressed()),
this, SLOT(doSomething()) );
I have QLineEdit - textFrom object. The build error is
../moc_mainwindow.cpp:66: un... | void doSomething(); looks like a snip from the header file, did you implement the slot itself?
|
1,133,722 | 1,134,095 | Things to keep in mind when migrating from VS2008 to VS2010 | So, I'll be soon working on porting two APIs (C++ and C++/CLI) to use the VS2010 compiler. I think it'd be a good idea to have a head start on this. Any tips?
| Breaking changes to C++/STL projects are outlined here.
vs2010 will also use a different build mechanism in the for of MSBuild.
Unfortunately, the revamped Intellisense in vs2010 won't extend to C++/CLI which some people aren't too happy about, however native code developer can look forward to a more responsive environ... |
1,133,739 | 1,134,501 | how does ofstream or ostream type cast all types to string? | any system defined user type past to ostream object is converted to a string or char* ?
like cout<<4<<"Hello World";
works perfectly fine, how is this achieved? is the << operator overloaded for each and every type? is there a way to achieve it through just one generic overloaded function? what i mean is can i have ju... | After re-reading your question (as a result of a comment in this answer) I have realized that what you want is not only conversions into string (my assumptions in the other answer here), but rather forwarding into the internal ofstream.
Now, what you want to achieve is not simple, and may be overkill in most cases. In ... |
1,133,902 | 1,133,917 | How can/should C++ static member variable and function be hidden? | m_MAX and ask() are used by run() but should otherwise not be public. How can/should this be done?
#include <vector>
class Q {
public:
static int const m_MAX=17;
int ask(){return 4;}
};
class UI {
private:
std::vector<Q*> m_list;
public:
void add(Q* a_q){m_list.push_back(a_q);}
int run(){return Q::m... | You could define both m_MAX and ask() within the private section of class Q. Then in Q add: "friend class UI". This will allow UI to access the private members of Q, but no one else. Also note that UI must be defined before the "friend class UI" statement. A forward declaration will work.
|
1,133,955 | 1,134,007 | Why would a virtual function be private? | I just spotted this in some code:
class Foo {
[...]
private:
virtual void Bar() = 0;
[...]
}
Does this have any purpose?
(I am trying to port some code from VS to G++, and this caught my attention)
| See this Herb Sutter article as to why you'd want to do such a thing.
|
1,134,006 | 1,134,061 | real use cases of casting operators | I want to know more about the casting (like static cast, dynamic cast, const cast and reinterpret cast) and when do we REALLY need that (real life scenario)? Any references/links/books will be appreciated.
Thanks.
| This article will do.
|
1,134,050 | 1,480,101 | Is there a way to preserve the BITMAPFILEHEADER when loading a Bitmap as a Windows resource? | I've been working on testing a few things out using SFML 1.4 (Simple and Fast Multimedia Library) with C++ and Visual C++ 2008 Express Edition. To avoid having external images with my graphical programs, I was testing out the sf::Image::LoadFromMemory(const char * Data, std::size_t SizeInBytes) function with Bitmap re... | Using a custom resource type will preserve the entire file. Change the resource script to utilize the RCDATA type as opposed to the BITMAP type:
IDB_SPRITE RCDATA "sprite1.bmp"
In the FindResource function call, use RT_RCDATA instead of RT_BITMAP:
HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(IDB_SPRITE), RT_RC... |
1,134,237 | 1,134,271 | Pedantic gcc warning: type qualifiers on function return type | When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the -Wall -Wextra options) I suddenly got a bunch of errors of the form warning: type qualifiers ignored on function return type.
Consider temp.cpp:
class Something
{
public:
co... | It doesn't violate the standard. That's why they're warnings and not errors.
And indeed you're right — the leading const is superfluous. The compiler warns you because you've added code that in other circumstances might mean something, but in this circumstance means nothing, and it wants to make sure you won't be disap... |
1,134,388 | 1,134,467 | std::endl is of unknown type when overloading operator<< | I overloaded operator <<
template <Typename T>
UIStream& operator<<(const T);
UIStream my_stream;
my_stream << 10 << " heads";
Works but:
my_stream << endl;
Gives compilation error:
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'UIStream' (or there is no acceptable conversion... | std::endl is a function and std::cout utilizes it by implementing operator<< to take a function pointer with the same signature as std::endl.
In there, it calls the function, and forwards the return value.
Here is a code example:
#include <iostream>
struct MyStream
{
template <typename T>
MyStream& operator<... |
1,134,658 | 1,134,765 | Sockets: How to send data to the client without 'waiting' on them as they receive/parse it | I have a socket server, written in C++ using boost::asio, and I'm sending data to a client.
The server sends the data out in chunks, and the client parses each chunk as it receives it. Both are pretty much single threaded right now.
What design should I use on the server to ensure that the server is just writing out... | If you set your socket to non-blocking, then writes should fail if they would otherwise block. You can then queue up the data however you like, and arrange for another attempt to be made later to write it. I don't know how to set socket options in the boost socket API, but that's what you're looking for.
But this is pr... |
1,134,931 | 1,134,949 | Reading/Understanding third-party code | When you get a third-party library (c, c++), open-source (LGPL say), that does not have good documentation, what is the best way to go about understanding it to be able to integrate into your application?
The library usually has some example programs and I end up walking through the code using gdb. Any other suggestion... | I frequently use a couple of tools to help me with this:
GNU Global. It generates cross-referencing databases and can produce hyperlinked HTML from source code. Clicking function calls will take you to their definitions, and you can see lists of all references to a function. Only works for C and perhaps C++.
Doxyge... |
1,135,018 | 1,135,039 | Achieving Interface functionality in C++ | A big reason why I use OOP is to create code that is easily reusable. For that purpose Java style interfaces are perfect. However, when dealing with C++ I really can't achieve any sort of functionality like interfaces... at least not with ease.
I know about pure virtual base classes, but what really ticks me off is tha... | Template MetaProgramming is a pretty cool thing. The basic idea? "Compile time polymorphism and implicit interfaces", Effective C++. Basically you can get the interfaces you want via templated classes. A VERY simple example:
template <class T>
bool foo( const T& _object )
{
if ( _object != _someStupidObject && _obj... |
1,135,187 | 1,135,217 | Porting to Solaris SPARC using Sun Studio 12 | I am trying to compile an object file using the code below.
//--Begin test.cpp
class A;
void (A::* f_ptr) ();
void test() {
A *a;
(a->*f_ptr)();
}
//-- End test.cpp
For GNU g++ compiler, it is able to compile the object file.
$ g++ -c test.cpp
But for Sun Studio 12 on a Solaris 10 (SPARC), it outputs an erro... | Try to #include <A.h> in that file. The compiler needs to know what class A looks like.
|
1,135,392 | 1,141,445 | serial communication anomaly in Linux? | I am using select call to communicate with an external subsystem (protocol for the same has been provided and implemented as a Qt thread) using serial port RS232. We do not have the hardware for the external systems and thus we have developed in house simulators using .Net 2.0 and C# to mimic the behavior of the underl... | I have solved the problem. My apologies if I couldn't get across my point. Earlier we were using signal handling for serial interfacing with each system connected to a dedicated serial port, this design was flawed from start as signal handler in our case was way too complex. Ideally a signal handler should just set som... |
1,135,560 | 1,135,582 | Pointer to Value in a std::map | I have a std::map that is used by multiple threads to store data. The map is declared like this:
std::map<int, Call> calls;
From each thread, I have to acquire a mutex lock, obtain a pointer or reference to the object belonging to that thread, then release the mutex lock. I can modify the object after that because eac... | You should use iterators:
mutex.lock();
std::map<int, Call>::iterator callptr = calls.find(id);
callptr->second.foo();
...
mutex.unlock();
Your first solution with pointers is problematic, because the lifetime of the object in the map is uncertain - it may be moved when the tree is rebalanced when elements are inser... |
1,135,822 | 1,135,834 | Escaping a # symbol in a #define macro? | Without going into the gory details I want to use a #define macro that will expand to a #include but the '#' sign is confusing the preprocessor (as it thinks I want to quote an argument.)
For example, I want to do something like this:
#define MACRO(name) #include "name##foo"
And use it thus:
MACRO(Test)
Which will ex... | As far as I remember you cannot use another preprocessor directive in define.
|
1,135,841 | 1,135,862 | C++ multiline string literal | Is there any way to have multi-line plain-text, constant literals in C++, à la Perl? Maybe some parsing trick with #includeing a file? I can't think of one, but boy, that would be nice. I know it'll be in C++0x.
| Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:
const char *text =
"This text is pretty long, but will be "
"concatenated into just a single string. "
"The disadvantage is that you have to quote "
"each part, and newlines must be literal as "... |
1,135,901 | 1,135,967 | Windows message loop | Theres some reason for this code not reach the first else?
I got it exactly the same from vairous sources. Than I did my own encapsulation. Everything goes fine. Window is created, messages are treated, events are generated to keyborad input in the client area, the gl canvas works fine (when I force it to draw).
The on... | In your case the message queue must never be empty - why? Well it depends on what the rest of your program is doing. Some possibilities:
Your code is posting new messages to the queue in a manner such that the queue doesn't get empty. I'd suggest logging out the message ids as they are handled.
You aren't handling p... |
1,136,115 | 1,136,129 | creating a vector of pointers that point to more vectors | I am trying to create a vector that contains pointers, each pointer points to another vector of a type Cell which I have made using a struct.
The for loop below allows me to let the user define how many elements there are in the vector of pointers. Here's my code:
vector< vector<Cell>* > vEstore(selection);
for (int t... | Cell cell = { 10, 12 };
binpocket[1]->push_back(cell);
Alternatively, you can give your struct a constructor.
struct Cell
{
Cell() {}
Cell(unsigned long long lr1, unsigned int cw2)
: lr1(lr1), cw2(cw2)
{
}
unsigned long long lr1;
unsigned int cw2;
};
Then you could do
binpocket[1]->pu... |
1,136,249 | 1,136,255 | How to call Base class method through base class pointer pointing to derived class | class Base
{
public:
virtual void foo()
{}
};
class Derived: public Base
{
public:
virtual void foo()
{}
};
int main()
{
Base *pBase = NULL;
Base objBase;
Derived objDerived;
pBase = &objDerived;
pBase->foo();
/*Here Derived class foo will be called, but i want this to ca... | pBase->Base::foo()
|
1,136,323 | 1,136,971 | Adding generic logging support in C++ shared library | I'm writing a c++ shared library that is intended to be used by other library or executable. What is the best way to add a generic logging in my library? Ideally I'd like to adapt my library to logging functionality chosen by the library's user.
Suppose i have a class in my library
class A {
public:
void method... | You can provide a callback mechanism to allow the library's user to provide your library with an adapter into their logging.
I.e., in your library provide an abstract logging interface class, e.g.:
class Logger
{
public:
virtual ~Logger () {}
virtual void log (const std::string& message) = 0;
};
and a class to... |
1,136,359 | 1,137,153 | How to force std::stringstream operator >> to read an entire string? | How to force std::stringstream operator >> to read an entire string instead of stopping at the first whitespace?
I've got a template class that stores a value read from a text file:
template <typename T>
class ValueContainer
{
protected:
T m_value;
public:
/* ... */
virtual void fromString(std::string & str)
{... | As operator >> is not satisfying our requirement when T=string, we can write a specific function for [T=string] case. This may not be the correct solution. But, as a work around have mentioned.
Please correct me if it won't satisfy your requirement.
I have written a sample code as below:
#include <iostream>
#include <s... |
1,136,900 | 54,747,631 | RTP sequence extract | A RTP packet consists of a 12-byte RTP header and
subsequent RTP payload
The 3rd and 4th byte of the header contain the
Most-Significant-Byte and Least-Significant-Byte of
the sequence number of the RTP packet
Seq Num= (MSB<<8)+LSB
char pszPacket[12];
...
long lSeq = ???? - How to get the sequence number from a packet?... | If you need a proper implementation for that:
typedef struct _RTPHeader
{
//first byte
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
unsigned int CC:4; /* CC field */
unsigned int X:1; /* X field */
unsigned int P:1; /* padding flag */
unsigned int version:2;
#elif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.