question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,712,076 | 2,712,125 | How to use an iterator? | I'm trying to calculate the distance between two points. The two points I stored in a vector in C++: (0,0) and (1,1).
I'm supposed to get results as
0
1.4
1.4
0
But the actual result that I got is
0
1
-1
0
I think there's something wrong with the way I use iterator in vector.
How can I fix this problem?
I posted the ... | That your code compiles at all is probably because you have a using namespace std somewhere. (Otherwise vector would have to be std::vector.) That's something I would advise against and you have just provided a good case why:
By accident, your call picks up std::distance(), which takes two iterators and calculates the ... |
2,712,377 | 2,712,494 | How to 'hide' spurious "declared but never used" warnings? | I'm using the Borland (AKA "Embarcodegearland") C++Builder 2007 compiler which has a minor bug that certain static const items from system header files can cause spurious "xyzzy is declared but never used" warnings.
I'm trying to get my code 100% warning free, so want a way of masking these particular warnings (note - ... | A common way to reference variables is something like this:
#define UNREFERENCED(x) ((void)x)
// ...
void MyFunc()
{
const int x = 5; // never used for whatever reason
UNREFERENCED(x); // stops compiler warning
}
The 'cast to void' effectively means 'do nothing with this expression' so should be equivalent ... |
2,712,398 | 2,712,503 | Boost binding a function taking a reference | I am having problems compiling the following snippet
int temp;
vector<int> origins;
vector<string> originTokens = OTUtils::tokenize(buffer, ","); // buffer is a char[] array
// original loop
BOOST_FOREACH(string s, originTokens)
{
from_string(temp, s);
origins.push_back(temp);
}
// I'd like to use this... | FromString() takes 3 arguments and default arguments are not part of a functions type. So the bind expression should probably be something like:
boost::bind<int>(&FromString<int>, boost::ref(temp), _1, std::dec);
|
2,712,499 | 2,713,674 | Is it possible to create your own custom locale | Since Windows doesnt have a C++ locale with UTF8 support by default, i would like to construct a custom locale object which supports UTF8 (by creating it with a custom ctype facet).
How can i construct a locale object with a my own ctype implementation (i only found functions to construct a locale using an already exis... | It's possible to create custom facets by inheriting from std::locale::facet. Locales can use those custom facets as in following code:
class custom_facet : public std::locale::facet {
public:
static std::locale::id id;
custom_facet(int);
int custom_value() const;
};
std::locale custom_locale ( std:... |
2,712,560 | 2,712,575 | Trivial Q about redefinition | Why this isn't allowed:
int a = 0;
int a = 0;
but this is:
for (int i = 0; i < 2; ++i)
{
int a = 0;
}
As far as I know code inside for loop will be executed twice whitout actually going out of its scope, so it should also be an error to define a twice.
Looking forward to your answers
Thanks.
| There is a single definition within the for loop. The variable gets created, used, then destroyed at the closing curly brace and recreated in the next loop iteration. There is a single variable defined.
This is somehow similar to a variable defined in a function. The function can be called many times, but the variable ... |
2,712,894 | 2,712,947 | How to insert into std::map | In code below:
map<string,vector<int>> create(ifstream& in, const vector<string>& vec)
{
/*holds string and line numbers into which each string appears*/
typedef map<string,vector<int>> myMap;
typedef vector<string>::const_iterator const_iter;
myMap result;
string tmp;
unsigned int lineCounter ... | Seriously, I would not do it.
You are only going to complicate your code unnecessarily. You would need a call to the insert to generate the new element in the map and then modify it.
Just for the sake of it (avoiding the double lookup, but building an unnecessary empty vector):
result.insert( std::make_pair( *beg, std:... |
2,713,043 | 2,713,073 | Access violation of member of pointer object | So I am coding this client/server program. This code is from the client side. The client has an instance of an object
mpqs_sieve *instance_;
The reason I make it as a pointer is, that mpqs_sieve only has a constructor that takes 3 arguments, and I want to instantiate it at a later point in time.
The client first gets ... | You are passing a copy of the instance_ pointer to the function, not a reference to the variable. When you assign to instance_, you're modifying a local variable, not the member variable with the same name.
Change the function parameter to mpqs_sieve *&instance_.
|
2,713,160 | 2,713,282 | Ambiguous access to base class template member function | In Visual Studio 2008, the compiler cannot resolve the call to SetCustomer in _tmain below and make it unambiguous:
template <typename TConsumer>
struct Producer
{
void SetConsumer(TConsumer* consumer) { consumer_ = consumer; }
TConsumer* consumer_;
};
struct AppleConsumer
{
};
struct MeatConsumer
{
};
stru... |
I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer.
This hasn't to do with templates, it comes from using multiple base classes - the name lookup is already ambiguous and overload resolution only takes place after that.
A simplified example would be the followin... |
2,713,289 | 2,713,327 | How to execute Javascript function in C++ | Please tell me, how to include a javascript header file or javascript function in C++ code. The C++ code is written in Linux(UBUNTU)?
Although i need to perform the above action only, but let me tell u my purpose of doing it, as i am intending to implement CTI (Computer Telephony Integration) operation.
(Help will be a... | Calling Scripting functions from C++
http://clipp.sourceforge.net/Tutorial/back_calling.html
JavaScript Calls from C++ - CodeGuru
http://www.codeguru.com/cpp/i-n/ieprogram/article.php/c4399/JavaScript-Calls-from-C.htm
JavaScript call from C++ - CodeProject
http://www.codeproject.com/KB/COM/jscalls.aspx
calling javascri... |
2,713,314 | 2,713,501 | Expose C++ object to Javascript in Qt | Is there any way I can expose a C++ object/function to JavaScript running inside the QtWebKit browser in Qt? It's possible to expose ActionScript objects to JS code running inside the WebKit browser in Adobe AIR - I'm looking for similar functionality in Qt.
| Yes. Take a look at this. It should be a good start.
|
2,713,496 | 2,713,518 | Parsing HTML to find specific links (Without Keywords) | I posted about this sort of earlier, but I am not sure how to post back to my original question as I can only comment or answer my own question.
Anyways, I need to get 4 links from a website, the latest stable build links for windows and linux, and the latest development build links for windows and linux (4 links total... | Maybe you'll find the location of the actual downloads, http://www.sourcemod.net/smdrop/, easier to parse.
|
2,713,509 | 2,713,524 | Auto pointer for unsigned char array? | I'd need a class like std::auto_ptr for an array of unsigned char*, allocated with new[]. But auto_ptr only calls delete and not delete[], so i can't use it.
I also need to have a function which creates and returns the array. I came out with my own implementation within a class ArrayDeleter, which i use like in this ex... | Boost has a variety of auto-pointers, including ones for arrays. Have you considered if std::vector is sufficient? Vectors are guaranteed to be contiguous in memory, and if you know the size and allocate memory ahead of time via reserve() or resize(), the location in memory will not change.
|
2,713,687 | 2,714,156 | Speed of QHash lookups using QStrings as keys | I need to draw a dynamic overlay on a QImage. The component parts of the overlay are defined in XML and parsed out to a QHash<QString, QPicture> where the QString is the name (such as "crosshairs") and the QPicture is the resolution independent drawing. I then draw components of the overlay as they are needed at a posi... | Gareth has the right answer of course. I'd like to extend it a tiny bit.
Go for consistency and reusability
first. Try not introduce huge
performance bottlenecks too; it's
hard to strike the balance
Set realistic performance criteria. I'm guessing you are making something game-like, a reasonable criteria would be "s... |
2,713,698 | 2,713,746 | NCurses-Like System for Windows | Are there any C++ libraries similar to Ncurses, but for Windows? It seems there are no ports of Ncurses and I need a really good display system like it.
Any suggestions? Cross-platform is a plus.
| There is very similar library PDCurses. It uses the same calls as ncurses, but works on Win32. The only thing you'd need to port a program would be to recompile.
http://pdcurses.sourceforge.net/
|
2,713,931 | 2,772,002 | Low Throughput on Windows Named Pipe Over WAN | I'm having problems with low performance using a Windows named pipe. The throughput drops off rapidly as the network latency increases. There is a roughly linear relationship between messages sent per second and round trip time. It seems that the client must ack each message before the server will send the next one. Th... | I've implemented a work around, introducing a small (~1ms) fixed delay to buffer up as much data as possible before writing to the pipe. Over a network link with a RTT of 200ms, I can send ten times as much data in about a third of the time.
I send a message down the pipe when it first connects, so the client can deter... |
2,714,129 | 2,714,146 | How to know if an enumerator has reached the end of the collection in C#? | I am porting a library from C++ to C#. The old library uses vectors from C++ and in the C# I am using generic Dictionaries because they're actually a good data structure for what I'm doing (each element has an ID, then I just use using TypeDictionary = Dictionary<String, Type>;). Now, in the C# code I use a loop like t... | Here's a pretty simple way of accomplishing this.
bool hasNext = tdEnum.MoveNext();
while (hasNext) {
int i = tdEnum.Current;
hasNext = tdEnum.MoveNext();
}
I found an online tutorial that also may help you understand how this works.
http://www.c-sharpcorner.com/UploadFile/prasadh/Enumerators11132005232321PM/E... |
2,714,144 | 2,714,212 | Does the usage of interfaces slow down programs? |
Possible Duplicate:
What is the performance cost of having a virtual method in a C++ class?
Is it true that interfaces slow down programs? I have heard that this is the case because during running time each during each usage of an object implementing this interface the decision has to be made which class implementin... | Although Billy points out that this is a lot like the other post on SO, I think it's not exactly the same... mainly because of the way this question is worded.
Because Olga talks about a "decision", I almost thought that she was getting mixed up between using interfaces vs. using a derived class, and determining if the... |
2,714,154 | 2,714,183 | How to get decimal value of a unicode character in c++ | For one of my opensource projects, i need to compute the decimal equivalent of a given unicode character.
For example if tamil character L'அ' is given, the output should be 2949 .
I am using c++ in Qt environment. I googled and could not find a solution for this. Please help if you know a solution for this.
| Use the unicode() method of the QChar object (which you can get e.g. with the at method of a QString, if a QString is what you have to start with).
|
2,714,285 | 2,714,315 | how to place struct in union | I have an union X. It's size is 64bits. How can I write (if possible) its declaration if I want to access those 64 bits as:
1. 4 int16_t: p,q,r,s;
2. Array of 4 int16_t: a[4]
3. 2 int32_t: n, m;
4. Array of 2 int32_t: b[2]
5. 1 int64_t z;
| something like
union thingie_type {
struct { int16_t p,q,r,s; };
int16_t a[4];
struct { int32_t n,m; };
int32_t b[2];
int64_t z;
};
|
2,714,355 | 2,714,407 | Guidelines for writing flexible software? | I've been developing an interpreter in C++ for my (esoteric, if you want) programming language some time now. One of the main things that I have noticed: I start with a flexible concept, and the further I code (Tokenizer->Parser->Interpreter) the less flexible the whole system gets.
For example: I didn't implement an i... |
Define the structure of the project before you start coding. Outline your main objectives and think about how can you achieve that.
Code the headers.
Look if it's possible to implement every feature using this set of interfaces
If no -> go back to (2)
If yes -> code .cpp files
Enjoy.
Of course, this doesn't apply to ... |
2,714,362 | 2,714,394 | C++: how to declare template array as function parameter | Very similar to this post
How can I declare template array as a parameter in templated function?
Something like this code:
template <unsigned i> void my_func (char (&a)[i]); //yes, I do need that reference
| Just declare an extra template parameter, which contains the type in question.
template <typename T, unsigned i>
void my_func (T (&a)[i]);
|
2,714,424 | 2,714,477 | Figuring out what makes a C++ class abstract in VS2008 | I'm using VS2008 to build a plain old C++ program (not C++/CLI). I have an abstract base class and a non-abstract derived class, and building this:
Base* obj;
obj = new Derived();
fails with the error "'Derived': cannot instantiate abstract class". (It may be worth noting, however, that if I hover over Base with the c... | The compiler should tell you in the error message. The following:
struct base
{
virtual void foo(void) = 0;
virtual void bar(void) = 0;
};
struct derived : base
{
virtual void foo(void){}
};
int main(void)
{
derived d;
}
Produces:
error C2259: 'derived' : cannot instantiate abstract class
due to f... |
2,714,426 | 2,714,561 | How to load/save C++ class instance (using STL containers) to disk | I have a C++ class representing a hierarchically organised data tree which is very large (~Gb, basically as large as I can get away with in memory). It uses an STL list to store information at each node plus iterators to other nodes. Each node has only one parent, but 0-10 children.
Abstracted, it looks something like:... | It seems like you could save the data in the following syntax:
File = Meta-data Node
Node = Node-data ChildCount NodeList
NodeList = sequence (int, Node)
That is to say, when serialized the root node contains all nodes, either directly (children) or indirectly (other descendants). Writing the format is fairly straight... |
2,714,671 | 2,714,825 | number of months between two dates - using boost's date | I've used boost::gregorian::date a bit now.
I can see that there are the related months & years & weeks duration types.
I can see how to use known durations to advance a given date.
Qu: But how can I get the difference between two dates in months (or years or weeks) ?
I was hoping to find a function like:
template<type... | Do you mean difference between dates (09/12 - 08/05 = 01/07 = 19months) or difference in time ((date2_seconds - date1_seconds) / seconds_per_month)?
For the first case it's possible to use accessors
greg_year date::year() const;
greg_month date::month() const;
Then difference between dates in months:
int months = (dat... |
2,714,749 | 2,715,041 | does passing __m128i objects by reference to inline function cause these objects to be moved to stack? | I'm writing transpose function for 8x16bit vectors with SSE2 intrinsics. Since there are 8 arguments for that function (a matrix of 8x8x16bit size), I can't do anything but pass them by reference. Will that be optimized by the compiler (I mean, will these __m128i objects be passed in registers instead of stack)?
Code s... | Chances are that they will not be pushed to the stack. If the function is inline the compiler will actually push the operations (code) from the called function into the callee function instead of passing the data from the caller to the callee.
Now, inline is a hint, so the compiler can decide not to actually inline th... |
2,714,784 | 2,714,823 | Start and run a class member function in background, in QT/C++ | Once a minute I want to run a task, not blocking other GUI functions. I heared somthing about QConcurent::run ...
Or should I use signals and slots?
| Use QConcurrent it sounds like what you need. And you can use QFutureWatcher to get signals when it's done (which uses signals and slots)
|
2,715,045 | 2,715,640 | C++ class is not being included properly | I have a problem which is either something I have completely failed to understand, or very strange. It's probably the first one, but I have spent the whole afternoon googling with no success, so here goes...
I have a class called Schedule, which has as a member a vector of Room. However, when I compile using cmake, or ... | It may not matter, I but I see no include guards in your headers. Shouldn't matter, but just to cover any angle...
|
2,715,063 | 2,715,117 | Problem with reading file line-by-line | I'm trying to complete an exercise to write a program that takes the following command line arguments: an input file, an output file, and an unspecified number of words. The program is to read the contents of the input file line by line, find for each word given which lines contain the word, and print the lines with th... | You are looping through the strings you are looking for, but you have the getline() that reads the file in the loop. You really want:
for each input line
getline
for each string we are looking for
is string in line?
|
2,715,164 | 2,715,214 | How can I decode the boost library naming? | I tried to find out that gd means in boost library name and I only found two other people looking for the same thing.
I suppose it should be a place where this is clearly documented and I would like to find it.
mt - multitheaded, get it with bjam threading=multi
s - bjam runtime-link=static
g - using debug versions of... | See Boost getting started windows section 6.3 naming and section 6.1 on Unix naming
The ones that deal with -mt and d are
-mt Threading tag: indicates that the library was built with multithreading support enabled. Libraries built without multithreading support can be identified by the absence of `-mt`.
-d ABI tag: ... |
2,715,198 | 2,715,248 | C++ Pointer Objects vs. Non Pointer Objects |
Possible Duplicate:
Why would you ever want to allocate memory on the heap rather than the stack?
Test2 *t2 = new Test2();
t2->test();
Test2 t3;
t3.test();
Why would I want to create a pointer object of type Test2? Why not just do non pointer version of Test2? Why would I want to do pointer objects?
Found answer h... | The reasons to use dynamic storage include (but probably not limited to)
Manual control of the objects lifetime - the object will live until you explicitly destroy it
Creating as many objects as necessary, when the final number of objects is only known at run-time (like number of nodes in a tree or number of elements ... |
2,715,273 | 10,994,547 | OpenAL and Vista: Device is always 'Generic Software' | I'm writing the audio part of a game, and I'm using OpenAL. I want to use some extensions, but the tests always fail:
TRACE: AudioManager - Sound device: 'Generic Software'
TRACE: AudioManager - Enabling OpenAL extensions...
TRACE: AudioManager - Compressor support: NO
TRACE: AudioManager - Reverb support: YES
TRACE: A... | OpenAL should always return the default audio device, unless you are using a Creative audio card. The extensions are all Creative-specific. It's the same as expecting to get Intel-specific OpenGL extension on an NVIDIA videocard.
For the record, here's how you set up OpenAL:
// create a default device
ALCdevice* device... |
2,715,340 | 2,715,404 | Automatically converting an A* into a B* | Suppose I'm given a class A. I would like to wrap pointers to it into a small class B, some kind of smart pointer, with the constraint that a B* is automatically converted to an A* so that I don't need to rewrite the code that already uses A*.
I would therefore want to modify B so that the following compiles...
struc... | The type of pointer_to_b is pointer to B, which is a type you cannot modify; it's implemented by the compiler.
You can do (*pointer_to_b)->foo(), which will do the right thing (assuming you have the overridden operator->()). However, that won't let the other code do the right thing, if you pass pointer_to_be into it.
A... |
2,715,386 | 2,715,411 | C++ runtime, display exception message | I am using gcc on linux to compile C++ code.
There are some exceptions which should not be handled and should close program.
However, I would like to be able to display exception string:
For example:
throw std::runtime_error(" message"); does not display message, only type of error.
I would like to display messages as ... | Standard exceptions have a virtual what() method that gives you the message associated with the exception:
int main() {
try {
// your stuff
}
catch( const std::exception & ex ) {
cerr << ex.what() << endl;
}
}
|
2,715,563 | 2,715,584 | how to apply shader to specific object | I have several objects on my scene. I want to apply my shader to one of them only. Environment: OpenGL 2.0, C++, GLUT, GLEW.
| The shader program is only in effect for as long as it is installed. Only the draw calls you make while the program is installed will use the shader. You must install your shader, draw your object, and then uninstall the shader.
Edit: By "install" the shader I mean use glUseProgram with your shader's handle. By "uninst... |
2,715,884 | 2,716,247 | How to get a debug flow of execution in C++ | I work on a global trading system which supports many users. Each user can book,amend,edit,delete trades. The system is regulated by a central deal capture service. The deal capture service informs all the user of any updates that occur.
The problem comes when we have crashes, as the production environment is impossibl... | Your solution sounds pretty reasonable, though perhaps rather than relying on viewing your audit trail in the debugger you can trigger it being printed with atexit() handlers. Something as simple as a stack of strings that have __FILE__,__LINE__,pthread_self() in them migth be good enough
You could possibly use some ex... |
2,715,931 | 2,715,993 | Composite pattern in C++ | I have to work with an application in C++ similar to a phone book: the class Agenda with an STL list of Contacts.Regarding the contacts hierarchy,there is a base-class named Contact(an abstract one),and the derived classes Friend and Acquaintance(the types of contact).
These classes have,for instance, a virtual meth... | Well, one way to do it:
virtual contact* contact::findContact(std::string name)
{
if(m_name == name) {return this;}
return NULL;
}
Then:
contact * Company::findContact(std::string name)
{
if(!contact::findContact(name) )
{
//For each contact in the contact list, findContact(name)
//If w... |
2,716,018 | 2,717,017 | How to synchronize access to many objects | I have a thread pool with some threads (e.g. as many as number of cores) that work on many objects, say thousands of objects. Normally I would give each object a mutex to protect access to its internals, lock it when I'm doing work, then release it. When two threads would try to access the same object, one of the threa... | You could use a mutex pool instead of allocating one mutex per resource or one mutex per thread. As mutexes are requested, first check the object in question. If it already has a mutex tagged to it, block on that mutex. If not, assign a mutex to that object and signal it, taking the mutex out of the pool. Once the mute... |
2,716,028 | 2,716,124 | Add 2 chars without using strncpy? | How would I manually concatenate two char arrays without using the strncpy function?
Can I just say char1 + char2?
Or would I have to write a for loop to get individual elements and add them like this:
addchar[0] = char1[0];
addchar[1] = char1[1];
etc
etc
addchar[n] = char2[0];
addchar[n+1] = char2[1];
etc
etc
To clar... | If you consider two trivial loops to be "manual", then yes, without using the standard library this is the only way.
char *append(const char *a, const char *b) {
int i = 0;
size_t na = strlen(a);
size_t nb = strlen(b);
char *r = (char*)calloc(na + nb + 1, 1);
for (i = 0; i < na; i++) {
r[i] ... |
2,716,041 | 2,716,104 | What would the destructor for this class look like? | class Equipment
{
std::vector<Armor*> vEquip;
Weapon* mainWeapon;
int totalDefense;
int totalAttack;
public:
unsigned int GetWeight();
int * GetDefense();
bool EquipArmor(Armor* armor);
bool UnequipArmor(Armor* armor);
bool EquipWeapon(Weapon* wep);
bool UnequipWeapon(Weapon... | Non-pointer types will take care of themselves. So, ints, floats, objects, etc. will take care of themselves, and you don't have to worry about deleting them.
Any pointers that are managed by the class need to be deleted by that class' destructor. So, if the memory pointed to by the pointer was allocated in the class o... |
2,716,079 | 2,716,140 | C++ beginner question regarding chars | I'm just messing around with some C++ at the moment trying to make a simple tic-tac-toe game and I'm running into a bit of a problem. This is my code:
#include <iostream>
using namespace std;
class Square {
public:
char getState() const;
void setState(char);
Square();
~Square();
private:
char * pSt... |
You don't need to use new for creating instances of variables.
Try changing your state variable to char instead of char * (pointer to char).
In general, the char * type is used to indicate a collection (array) of characters terminated by a nul character.
Also, set is a data type in the std namespace. Just change th... |
2,716,134 | 2,716,141 | pointers to functions | I have two basic Cpp tasks, but still I have problems with them. First is to write functions mul1,div1,sub1,sum1, taking ints as arguments and returning ints. Then I need to create pointers ptrFun1 and ptrFun2 to functions mul1 and sum1, and print results of using them. Problem starts with defining those pointers. I th... | Instead of int *funPtr1(int, int) you need int (*funPtr1)(int, int) to declare a function pointer. Otherwise you are just declaring a function which returns a pointer to an int.
For an array of function pointers it's probably clearest to make a typedef for the function pointer type and then declare the array using that... |
2,716,190 | 2,716,513 | How do I use a shared library (in this case JsonCpp) in my C++ program on Linux? | I'm a new-ish C++ programmer, and I'm doing my first program on my own using C++. I decided I would like to use JSON to store some of the data I'm going to be using, and I've found a library to handle JSON, JsonCpp.
I've installed the library using my Linux system's package manager, and in my C++ code, I've used in my ... | I checked the file list of JsonCPP:
include/json/autolink.h [code]
include/json/config.h [code]
include/json/features.h [code]
include/json/forwards.h [code]
include/json/json.h [code]
include/json/reader.h [code]
include/json/value.h [code]
include/json/writer.h [code]
Try #include <json/json.h> if t... |
2,716,293 | 2,716,432 | Trying to 'Make' CUDA SDK, ld cannot find library, ldconfig says it can | I know there are many other questions similar to this one, but none of the solutions posited there are working for me
Basically, making the SDK sample files, i get /usr/bin/ld: cannot find -lcuda
which would be an easy enough 'find the library and throw it to ldconfig', except ldconfig already says it has it...
$ sudo... | ldconfig deals only with runtime libraries, whereas ld deals with build-time libraries. Depending on how you installed the CUDA libraries, you may need to install an additional package for the symlink used at buildtime, or you may need to pass a -L option to gcc or ld in order to tell it where the build-time symlink is... |
2,716,362 | 2,716,412 | How to call DOS Interrupts within a C/C++ program using Inline Assembly? | I need to call some DOS interrupts (Services) from a C/C++ program, I tried the following inline asm code:
(Read a character)
int main()
{
asm(
"movb $0x01, %ah;"
"int $0x21"
);
system("PAUSE");
}
But it did not work ! I would like to know what have i done wrong here ! Also if there is another way to call dos inte... | You can only use DOS interrupts from DOS programs, so to make this work, you'd need a really ancient C++ compiler like Visual C++ 1.0 or 1.5, or Turbo C++/Borland C++ up through something like 4.5 or possibly 5.0. Then you'd have to fix your assembly code -- what you've written looks like AT&T syntax, but all the DOS c... |
2,716,749 | 2,716,989 | Throwing a new exception while throwing an old exception | If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) Example:
struct Foo
{
~Foo()
{
throw 2; // whoops, already throwing 1 at this point, let's terminate!
}
};
int main()
{
Foo foo;
throw 1... | Think in terms of flow control. Exceptions are fundamentally just fancy setjmp/longjmp or setcc/callcc anyway. The exception object is used to select a particular place to jump to, like an address. The exception handler simply recurses on the current exception, longjmping until it is handled.
Handling two exceptions at... |
2,716,917 | 2,717,108 | Adapting Map Iterators Using STL/Boost/Lambdas | Consider the following non-working code:
typedef map<int, unsigned> mymap;
mymap m;
for( int i = 1; i < 5; ++i )
m[i] = i;
// 'remove' all elements from map where .second < 3
remove_if(m.begin(), m.end(), bind2nd(less<int>(), 3));
I'm trying to remove elements from this map where .second < 3. This obviously isn't... | I'm not sure how to do this using just the STL binders but I think your main problem is that what's being passed into the functor you give to remove isn't just an int but a pair<int, unsigned>.
Using boost::bind you'd do it like this:
remove_if(m.begin(), m.end(), bind(&std::pair<int, unsigned>::second, _1) < 3);
Usin... |
2,716,925 | 2,717,125 | Remove never-run call to templated function, get allocation error on run-time | I have a piece of templated code that is never run, but is compiled. When I remove it, another part of my program breaks.
First off, I'm a bit at a loss as to how to ask this question. So I'm going to try throwing lots of information at the problem.
Ok, so, I went to completely redesign my test project for my experime... | you seem to be returning address of the function as a character? that looks weird. char has much smaller bit count than pointer, so it's highly possible you get same values. that could reason why changing code layout fixes/breaks your program
|
2,716,972 | 2,716,999 | why don't STL ifstream and ofstream classes take std::string as filenames? | This is a complaint about STL. Why do they take filename arguments as (char *) and not as std::string? This seems to make no sense.
There are two other questions on this topic:
How to open unicode filenames with
STL
Windows Codepage interactions with
C++
The issue is that I have a lot of code that looks like this:
... |
why don’t ifstream and ofstream classes take std::string as filenames?
I've seen a few sensible arguments for that (namely that this would create a dependency of the streams on strings), but frankly I believe the actual reason is that the streams are much older than the standard library and its strings.
Are there a... |
2,717,012 | 2,717,104 | Weird behaviour with vector::erase and std::remove_if with end range different from vector.end() | I need to remove elements from the middle of a std::vector.
So I tried:
struct IsEven {
bool operator()(int ele)
{
return ele % 2 == 0;
}
};
int elements[] = {1, 2, 3, 4, 5, 6};
std::vector<int> ints(elements, elements+6);
std::vector<int>::iterator it = std::remove_if(ints.begin() + 2... | Edit: Sorry, the original version of this was incorrect. Fixed.
Here's what's going on. Your input to remove_if is:
1 2 3 4 5 6
^ ^
begin end
And the remove_if algorithm looks at all numbers between begin and end (including begin, but excluding end), and removes all elements between that match your... |
2,717,199 | 2,717,413 | dynamically created arrays | My task consists of two parts. First I have to create globbal char array of 100 elements, and insert some text to it using cin. Afterwards calculate amount of chars, and create dedicated array with the length of the inputted text. I was thinking about following solution :
char[100]inputData;
int main()
{
cin >> ... | Regardless of the rest of your question, you appear to have some incorrect ideas about while loops. Let's look at this code.
for(int i=0; i<100; i++) {
while(inputData[i] == "\0") {
++count;
}
}
First, "\0" is not the NUL character. It is a pointer to a string containing only the terminating NUL byte... |
2,717,318 | 2,718,273 | How can I set the line style of a specific cell in a QTableView? | I am working with a QT GUI. I am implementing a simple hex edit control using a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hex bytes and then an ASCII representation of that data in the seventeenth column. Ideally, I would like to edit/set the style of the s... | I could think about a couple of ways of doing what you need; both would include drawing custom grid as it looks like there is no straight forward way of hooking into the grid painting routine of QTableView class:
1.Switch off the standard grid for your treeview grid by calling setShowGrid(false) and draw grid lines for... |
2,717,341 | 2,717,382 | Extremely CPU Intensive Alarm Clock | EDIT:
I would like to thank you all for the swift replies ^^ Sleep() works as intended and my CPU is not being viciously devoured by this program anymore! I will keep this question as is, but to let everybody know that the CPU problem has been answered expediently and professionally :D
As an aside to the aside, I'll ce... | This:
while( clock() < endwait ) {}
Is not "doing nothing". Certainly nothing is being done inside the while loop, but the test of clock() < endwait is not free. In fact, it is being executed over and over again as fast as your system can possibly handle doing it, which is what is driving up your load (probably 50% b... |
2,717,361 | 2,717,429 | Why isn't the copy constructor elided here? | (I'm using gcc with -O2.)
This seems like a straightforward opportunity to elide the copy constructor, since there are no side-effects to accessing the value of a field in a bar's copy of a foo; but the copy constructor is called, since I get the output meep meep!.
#include <iostream>
struct foo {
foo(): a(5) { }
... | It is neither of the two legal cases of copy ctor elision described in 12.8/15:
Return value optimisation (where an automatic variable is returned from a function, and the copying of that automatic to the return value is elided by constructing the automatic directly in the return value) - nope. f is not an automatic va... |
2,717,513 | 2,717,643 | C++ choose function by return type | I realize standard C++ only picks functions by argument type, not return type. I.e I can do something like:
void func(int);
void func(double);
but not
double func();
int func();
Where in the former, it's clear, in the latter, it's ambigious. Are there any extensions that lets me tell C++ to pick which function to use... | You cannot have two functions in the same scope that have the same name and signature (ie. argument types). Yet you can create a function that will behave differently depending on what variable you assign the result to, as in:
int x=f();
double x=f(); // different behaviour from above
by making f() return a proxy with... |
2,717,533 | 2,717,552 | C++ Vector of vectors | I have a class header file called Grid.h that contains the following 2 private data object:
vector<int> column;
vector<vector<int>> row;
And a public method whose prototype in Grid.h is such:
int getElement (unsigned int& col, unsigned int& row);
The definition of above mentioned function is defined as such in Grid.c... | In the line return row[row][col]; the first row is the int&, not the vector.
The variable declared in the inner scope is shadowing the variable in the outer scope, so the compiler is trying to index an int rather than a vector, which it obviously can't do.
You should fix your variable names so that they don't conflict.... |
2,717,671 | 2,717,762 | static arrays defined with unspecified size, empty brackets? | For the C++ code fragment below:
class Foo {
int a[]; // no error
};
int a[]; // error: storage size of 'a' isn't known
void bar() {
int a[]; // error: storage size of 'a' isn't known
}
why isn't the member variable causing an error too? and what is the meaning of this member variable?
I'm using gcc vers... | C99 supports something called a 'flexible' array member that is allowed to be the last member of a struct. When you dynamically allocate such a struct you can increase the amount requested from malloc() to provide for memory for the array.
Some compilers add this as an extension to C90 and/or C++.
So you can have code... |
2,717,700 | 2,717,709 | Should '#include' and 'using' statements be repeated in both header and implementation files (C++)? | I'm fairly new to C++, but my understanding is that a #include statement will essentially just dump the contents of the #included file into the location of that statement. This means that if I have a number of '#include' and 'using' statements in my header file, my implementation file can just #include the header file,... | A using-directive (using namespace std;) should not reside in a header unless it is contained within a function. It is bad practice. It is unlikely that every user of your header wants unqualified lookup for everything in a given namespace; the inclusion of unrelated headers can lead to unexpected ambiguity and compila... |
2,717,701 | 2,719,986 | How can I make a proccess in an OnLButtonDown() event happen again and again untill I live the button? | What happen until now is this:
Any line happens once, and if I use awhile(1) or while (nFlags == MK_LBUTTON) its working as it should but I get a crash.
The other problem, or maybe the same one is the delay if I will be able to do it, maybe using while() with Timer()?
I was thinking about Timer() to recall the function... | In OnLButtonDown() call SetTimer() to start a timer running, eg. every 100ms. Then add OnLButtonUp() and call KillTimer() to stop the timer running. Then, do your code in the OnTimer() function (add WM_TIMER to the message map) and it will run while the mouse is held down.
Note if the user clicks and drags the mouse ... |
2,717,765 | 2,717,789 | Parse <li> list with C++ | I have webpage I downloaded with C++ to a string, and it is basically a massive <li> list of links. I need to find the last 2 elements of the list. Can anyone help me on how to do this?
| If you are going to do it in a robust way you need an html parser. If the structure of the html is simple enough, and the runtime not an issue, something as stupid as doing string.rfind("<li>") twice might be good enough to find the positions of your elements. Then just do something even more hacky to find the end of... |
2,717,854 | 2,717,872 | How to create a dynamic array of an Abstract class? | Lets say I have an abstract class Cat that has a few concrete subclasses Wildcat, Housecat, etc.
I want my array to be able to store pointers to a type of cat without knowing which kind it really is.
When I try to dynamically allocate an array of Cat, it doesn't seem to be working.
Cat* catArray = new Cat[200];
| By creating an aray of pointers to Cat, as in
Cat** catArray = new Cat*[200];
Now you can put your WildCat, HouseCat etc instances at various locations in the array for example
catArray[0] = new WildCat();
catArray[1] = new HouseCat();
catArray[0]->catchMice();
catArray[1]->catchMice();
Couple of caveats, when... |
2,717,931 | 2,720,168 | What happens in memory when a C++ class is instantiated | I'm interested in the nuts and boltw of C++ and I wondered what actually changes when an object is instantiated. I'm particularly interested if the functions are then added to memory, if they are there from runtime or if they are never stored in memory at all.
If anyone could direct me to a good site on some of the co... | A common case is:
Memory is allocated by calling operator new. This function will most probably be already in memory, it's needed a lot.
The constructor of the class is called. This code could already be in memory. If not, the call to this function page-faults. The OS notes, and loads the appropriate page from your ex... |
2,718,050 | 2,718,111 | pointer reference type | I am trying to write a function that takes a pointer argument, modifies what the pointer points to, and then returns the destination of the pointer as a reference.
I am getting the following error: cannot convert int*** to int* in return
Code:
#include <iostream>
using namespace std;
int* increment(int** i) {
... | If you indeed mean "return the destination of the pointer as a reference", then I think the return type you're after is int& rather than int*.
This can be one of the confusing things about C++, since & and * have different meanings depending on where you use them. & is "Reference type" if you're talking about a variabl... |
2,718,138 | 2,725,575 | Lightweight spinlocks built from GCC atomic operations? | I'd like to minimize synchronization and write lock-free code when possible in a project of mine. When absolutely necessary I'd love to substitute light-weight spinlocks built from atomic operations for pthread and win32 mutex locks. My understanding is that these are system calls underneath and could cause a context s... | You need a volatile qualifier on lock, and I would also make it a sig_atomic_t. Without the volatile qualifier, this code:
u16 savedlock = lock;
while (savedlock == 0xffff || __sync_bool_compare_and_swap(&lock, savedlock, savedlock+1) == false)
savedlock = lock;
may not re-read lock when updating save... |
2,718,253 | 2,718,271 | Only static and const variables can be assign to a class? | I am learning C++. Just curious, can only static and constant varibles be assigned a value from within the class declaration? Is this mainly why when you assign values to normal members, they have a special way doing it
void myClass::Init() : member1(0), member2(1)
{
}
| This looks like it is supposed to be a constructor; if it is, it should have no return type, and it needs to have the same name as the class, e.g.,
myClass::myClass()
: member1(0), member2(1)
{
}
Only a constructor can have an initializer list; you can't delegate that type of initialization to an Init function.
A... |
2,718,284 | 2,718,294 | unresolved external symbol _D3D10CreateDeviceAndSwapChain@32 referenced in function "public: bool | Having trouble creating my swap chain. I receive the following error.
DX3dApp.obj : error LNK2019: unresolved external symbol _D3D10CreateDeviceAndSwapChain@32 referenced in function "public: bool __thiscall DX3dApp::InitDirect3D(void)" (?InitDirect3D@DX3dApp@@QAE_NXZ)
Below is the code ive done so far.
#include "DX3d... | You are not linking against the D3D library (D3D10.lib).
Add that library to your linker options (Project properties -> Linker -> Input -> Additional Dependencies). You will need to make sure the library location is in the "Additional Library Directories" path as well.
|
2,718,358 | 2,718,505 | Simple question about C++ constant syntax | Here is some code copied from Thinking in C++ Vol1 Chapter 10.
#include <iostream>
using namespace std;
int x = 100;
class WithStatic {
static int x;
static int y;
public:
void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "... | I've heard this described previously as “a method that does not logically change the object”. It means that by calling this method the caller can expect the object’s state to remain the same after the method returns. Effectively, the this pointer becomes a constant pointer to a constant instance of that class, so membe... |
2,718,386 | 2,718,391 | Multiple SFINAE rules | After reading the answer to this question, I learned that SFINAE can be used to choose between two functions based on whether the class has a certain member function. It's the equivalent of the following, just that each branch in the if statement is split into an overloaded function:
template<typename T>
void Func(T& ... | This is certainly possible; you just have to be careful to ensure that all of the branches are mutually exclusive, otherwise you'll end up with an ambiguity.
Take a look at Boost Type Traits and Boost Enable If, which are the two best tools for supporting this. Boost ICE (which stands for Integral Constant Expression)... |
2,718,689 | 2,718,694 | C++ Vector of vectors is messing with me | If I put this code in a .cpp file and run it, it runs just fine:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<int> row;
typedef vector<row> myMatrix;
void main()
{
//cout << endl << "test" << endl;
myMatrix mat(2,2);
mat[0][1] = 2;
cout << endl << mat... | You need to qualify vector as std::vector.
It works in the .cpp file because you use using namespace std; (do not use using namespace in a header file).
Furthermore, your declaration of the member variable is incorrect. It should just be:
myMatrix sudoku_;
If you want to set its dimensions, you need to do so in the c... |
2,718,724 | 2,718,729 | Operator overload for [] operator | Why would you need to overload the [] operator? I have never come across a practical scenario where this was necessary. Can somebody tell me a practical use case for this.
| Err.. std::vector<t>, std::basic_string<t>, std::map<k, v>, and std::deque<t> ?
I used this for a class representing a registry key, where operator[] returned an object representing a registry value with the string between []s.
See also, the Spirit Parser Framework, which uses [] for semantic actions.
|
2,718,779 | 2,718,813 | Correct Exceptions in C++ | I am just learning how to handle errors in my C++ code. I wrote this example that looks for a text file called some file, and if its not found will throw an exception.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array[90];
try
{
ifstream file;
file.open("somefile.txt");
if(!f... | "Correctly" is a value judgment, but (unlike other classes) there's a major benefit from exceptions classes being a monolithic hierarchy, so I'd generally advise throwing something derived from std::exception, not simply an int.
Second, it's open to question whether an incorrect file name is sufficiently unexpected to ... |
2,718,815 | 2,718,847 | returning reference to a vector from a method and using its public members | I have a vector t_vec that stores references to instances of class Too. The code is shown below. In the main , I have a vector t_vec_2 which has the same memory address as B::t_vec.
But when I try to access t_vec_2[0].val1 it gives error val1 not declared.
Could you please point out what is wrong? Also, if you know of... | You have 2 errors:
The first was already said, you should write
t_vec_2[0]->val1
instead of
t_vec_2[0].val1
The second is the strange line
b = B();
I think you should delete it.
The error occurs because right part B() is gonna be delete just after it is created.
So you don't get in the object b the 10 value as you wa... |
2,718,836 | 2,719,177 | How to define an extern, C struct returning function in C++ using MSVC? | The following source file will not compile with the MSVC compiler (v15.00.30729.01):
/* stest.c */
#ifdef __cplusplus
extern "C" {
#endif
struct Test;
/* NB: This may be extern when imported by another module. */
struct Test make_Test(int x);
struct Test { int x; };
struct Test make_Test(int x)
{
struct Test r;... | This is an interesting question. As you say, compiling the code as C code rightly produces no error. And only MSVC seems to have trouble with it when compiled as C++ code.
Since other C++ compilers don't have a problem with the code, this might be a bug in MSVC, but I can see how MSVC might have a rationale for this ... |
2,718,918 | 2,718,937 | Char* vs std::string |
Possible Duplicate:
C++ char* vs std::string
Is there any advantage to using char*'s instead of std::string?
I know char*'s are usually defined on the stack, so we know exactly how much memory we'll use, is this actually a good argument for their use? Or is std::string better in every way?
| If you're writing in C++ then std::string will be better in most cases you'll encounter. Instead, a few cases when you might want to use char*'s:
-Compatibility with old C code (although std::string's c_str() method handles most of this)
-To conserve memory (std::string will likely have more overhead)
-Cases where you... |
2,719,136 | 2,719,155 | overloading "<<" with a struct (no class) cout style | I have a struct that I'd like to output using either 'std::cout' or some other output stream.
Is this possible without using classes?
Thanks
#include <iostream>
#include <fstream>
template <typename T>
struct point{
T x;
T y;
};
template <typename T>
std::ostream& dump(std::ostream &o,point<T> p) const{
o<<"x: "... | Perhaps it's a copy-paste error, but there are just a few things wrong. Firstly, free-functions cannot be const, yet you have marked dump as such. The second error is that dump does not return a value, which is also easily remedied. Fix those and it should work:
template <typename T> // note, might as well take p as co... |
2,719,142 | 2,719,236 | Splitting a C++ class into files now won't compile | I am teaching myself to write classes in C++ but can't seem to get the compilation to go through. If you can help me figure out not just how, but why, it would be greatly appreciated. Thank you in advance! Here are my three files:
make_pmt.C
#include <iostream>
#include "pmt.h"
using namespace std;
int main() {
... | First some taxonomy.
This
class CPMT {
public:
double GetGain();
// ...
};
is defining a class without also defining the member functions. This
class CPMT {
public:
double GetGain() {return gain;}
// ...
};
is defining the same class, with also defining its member functions (i... |
2,719,204 | 2,719,617 | Make conversion to a native type explicit in C++ | I'm trying to write a class that implements 64-bit ints for a compiler that doesn't support long long, to be used in existing code. Basically, I should be able to have a typedef somewhere that selects whether I want to use long long or my class, and everything else should compile and work.
So, I obviously need conversi... | To avoid the compiler to be confused, you will help it by defining the combination of your class and the built-in types for all the arithmetic operator. For example for operator+, you will need to define + the unsigned ones
MyClass operator+(char, MyClass const&);
MyClass operator+(MyClass const&, char);
MyClass operat... |
2,719,226 | 2,722,489 | How to generate a VBR video from stream of YUV images? | My hardware (video capture card) gives me the images in YV12 (YUV 420) format and I am trying to generate a video from it. I am using C++ under windows and I would like to generate a mpeg-4 VBR video from that stream but I dont know where I should start... (I need it to be VBR because it is a security camera and there ... | ffmpeg will do this for you. Check out this part of the documentation where they talk about encoding raw YUV 420P frames. You can use ffmpeg's built-in mpeg 4 encoder, or it also allows you to interface with other libraries like xvid and x264.
The easiest way to handle this would be to just use the command line ffmpe... |
2,719,641 | 2,719,660 | Can there be two public section in a class? If yes then why ? And in which circumstances we do so? | There is something bugging me about classes. For example
class A
{
public:
A()
{
.....
.....
}
void cleanup()
{
....
....
....
}
public:
UINT a;
ULONG b;
};
In the above example there are two public section. In the first section I am defining a constructor and a method and in the second sec... | Access qualifiers simply apply to the code that follows until the next qualifier. There is no restriction on the number or order of such qualifiers.
It is generally not necessary to repeat the same access qualifier in a class, and doing so is likely to confuse the reader. They also may have an effect on the layout of a... |
2,719,741 | 2,816,930 | Advice when using COM Object/CComPtr and the STL | I am doing some COM related things with directshow such as:
typedef CComPtr<IBaseFilter> AutoIBaseFilterPtr;
map<CString, AutoIBaseFilterPtr> _filterMap;
To store a list of directShow related com objects and their friendly name.
After finding this article (See:Problem 2) on how changes in VC10 compiler might effect ... | The only slight thing I can think of that hasn't been mentioned is that CAdapt is required for CComBSTR as well as CComPtr, because it overloads operator& too.
In fact, it is overloading operator& that makes CAdapt necessary, as many STL containers require that taking the address of something X returns a pointer to sai... |
2,719,832 | 2,719,880 | Why is overloading operator&() prohibited for classes stored in STL containers? | Suddenly in this article ("problem 2") I see a statement that C++ Standard prohibits using STL containers for storing elemants of class if that class has an overloaded operator&().
Having overloaded operator&() can indeed be problematic, but looks like a default "address-of" operator can be used easily through a set of... | Without having looked at the links, I suppose the tricks in boost::addressof() were invented well after the requirement to not to overload unary prefix & for objects to be held in containers of the std lib.
I vaguely remember Pete Becker (then working for Dinkumware on their standard library implementation) once stati... |
2,719,922 | 2,720,223 | How to install the program depending on libstdc++ library | My program is written in C++, using GCC on Ubuntu 9.10 64 bit. If depends on /usr/lib64/libstdc++.so.6 which actually points to /usr/lib64/libstdc++.so.6.0.13. Now I copy this program to virgin Ubuntu 7.04 system and try to run it. It doesn't run, as expected. Then I add to the program directory the following files:
l... | If you're working on Ubuntu, making a .deb (Debian Package) seems to way to go. Here is a link to get you started.
Your package will state it depends on some other packages (typically the packages that includes libstdc++.so.6.0.13 - i guess the package name is something like libstdc++) and dependencies will be installe... |
2,719,984 | 2,719,996 | vector related memory allocation question | I am encountering the following bug.
I have a class Foo . Instances of this class are stored in a std::vector vec of class B.
in class Foo, I am creating an instance of class A by allocating memory using new and deleting that object in ~Foo().
the code compiles, but I get a crash at the runtime. If I disable delete... | You need to implement a copy constructor and an assignment operator for Foo. Whenever you find you need a destructor, you alnmost certainly need these two as well. They are used in many places, specifically for putting objects into Standard Library containers.
The copy constructor should look like this:
Foo :: Foo( co... |
2,720,018 | 2,720,053 | Using Qt's XML library for simple operation | I basically want to use the XML parser from Qt in my existing project. I have only used Qt once before, and that was with Qt Designer, and I am not having much luck finding anything on Google about how to just use the XML library.
I have downloaded a web page that has one large list, and I want to parse it and add each... | The following code should give you a quick view of what to do with Qt XML features for what you need.
#include <list>
#include <QDomDocument>
#include <QFile>
int main()
{
QString filename("myfile.xml");
std::list<QString> result;
int errorLine, errorColumn;
QString errorMsg;
QFile modelFile(filena... |
2,720,181 | 2,720,593 | How to make some simple GUI controls? | I need to make a DirectX or OpenGL app and i will need a custom GUI for that.
I think a button, a input text box, a list box (that will need a scroll bar as there will be more items that can fit on the screen) and a slider control will be enough.
I know about CeGUI framework but i just don't like it, way too many XML f... | A little bit of googling turns up the following:
libnui
Bram Stein's UI library
GiGi
... and then some.
|
2,720,259 | 2,720,446 | Using MSADO15.DLL and C++ with MinGW/GCC on Windows Vista | INTRODUCTION
Hi,
I am very new to C++, is my 1st statement.
I have started initially with VC++ 2008 Express, I've notice that GCC becomes kind of standard so I am trying to make the right steps event from the beginning.
I have written a piece of code that connects to MSSQL Server via ADO, on VC++ it's working like a ch... | GCC and MSVC use #import for different things.
In GCC, #import is an objective-c variant of #include that only includes the header file once.
In MSVC, #import triggers a Microsoft extension that builds a smart pointer implementation and header files from a COM type library.
In GCC you are going to have to import the CO... |
2,720,495 | 2,720,991 | Static variable not initialized | I've got a strange problem with a static variable that is obviously not initialized as it should be.
I have a huge project that runs with Windows and Linux. As the Linux developer doesn't have this problem I would suggest that this is some kind of wired Visual Studio stuff.
Header file
class MyClass
{
// some other... | I suggest you use static member function with static variable and not static variable itself:
class MyClass
{
// some other stuff here
...
private:
static AnotherClass* const getAnotherClass();
};
AnotherClass *const MyClass::getAnotherClass()
{
static AnotherClass *const p = new AnotherClass("... |
2,720,752 | 2,720,803 | How does large text file viewer work? How to build a large text reader | how does large text file viewer work?
I'm assuming that:
Threading is used to handle the file
The TextBox is updated line by line
Effective memory handling is used
Are these assumptions correct? if someone were to develop their own, what are the mustsand don'ts?
I'm looking to implement one using a DataGrid instead ... | I believe that the trick is not loading the entire file into memory, but using seek and such to just load the part which is viewed (possibly with a block before and after to handle a bit of scrolling). Perhaps even using memory-mapped buffers, though I have no experience with those.
Do realize that modifying a large fi... |
2,720,988 | 2,720,999 | Why this function overloading is not working? | class CConfFile
{
public:
CConfFile(const std::string &FileName);
~CConfFile();
...
std::string GetString(const std::string &Section, const std::string &Key);
void GetString(const std::string &Section, const std::string &Key, char *Buffer, unsigned int BufferSize);
..... | Because the CConFile::GetString() is, as the name suggest, a class member function, that is not accessible the way you call it in the second function.
The other function you're declaring, GetString(), is a global one.
You just forgot to add CConFile:: to the second function...
|
2,720,989 | 2,721,018 | How to set text editable in GtkEntry | Pretty straight forward question, I have a GtkEntry widget that I want to set to be editable. I know the function I should use is:
gtk_editable_set_editable
But I don't know how to make it take a GtkEntry widget as an argument
Here is the code I'm using:
GtkWidget *TextEntry;
TextEntry = gtk_entry_new();
gtk_entry_s... | Do the following:
GtkWidget* entry = gtk_entry_new();
gtk_entry_set_editable(GTK_ENTRY(entry), TRUE);
Welcome to the world of GObject :)
Note that if you were using gtk_editable, you need to do:
gtk_editable_set_editable(GTK_EDITABLE(entry), TRUE);
|
2,721,128 | 2,721,158 | Why do I need to call new? |
Possible Duplicates:
When to use “new” and when not to, in C++?
When should I use the new keyword in C++?
It seems like I could program something without ever using the word new, and I would never have to worry about deleting anything either, so why should I ever call it?
From what I understand, it's because I would... | It's a matter of object lifetime: if you stack-allocate your objects, the objects destructors will be called when these objects go out of scope (say, at the end of the method). This means that if you pass these objects out of the method that created them, you'll find yourself with pointers to memory that could be over... |
2,721,244 | 2,721,836 | What is the fastest way to calculate the number of bits needed to store a number | I'm trying to optimize some bit packing and unpacking routines. In order to do the packing I need to calculate the number of bits needed to store integer values. Here is the current code.
if (n == -1) return 32;
if (n == 0) return 1;
int r = 0;
while (n)
{
++r;
n >>= 1;
}
return r;
| You're looking to determine the integer log base 2 of a number (the l=highest bit set). Sean Anderson's "Bit Twiddling Hacks" page has several methods ranging from the obvious counting bits in a loop to versions that use table lookup. Note that most of the methods demonstrated will need to be modified a bit to work wi... |
2,721,263 | 2,721,471 | Pointer-Safe Objects? | Would it be smart to have a vector in an object with a list of pointers that point to it?
This way when the object is deleted, it could delete all the pointers pointing to it to prevent a null-pointer exception?
| If your ultimate goal is to detect when an object is freed from users of the object the best bet is to use a weak pointer semantic. There an implementation in the Boost Smart Pointer library (see weak_ptr). It solves the problem you describe by reversing the reference graph you describe. It has the pointers reference a... |
2,721,315 | 2,721,357 | Dictionary/HashTable Object in C++? | I'm looking for a HashTable or Dictionary implementation in C++ that has similar functionality to the one in C#? Does the STL contain an object like this and how would I use it?
| Actually, to be exactly the same as .NET's Dictionary/Hashtable, what you want is hash_map or unordered_map (std::map is implemented as a binary tree), hash_map is an extension to the SC++L. Most compilers that I know of come with hash_map, though, and boost obviously has unordered_map until C++0x is available in all ... |
2,721,421 | 2,721,499 | How to add/design callback function | How do I setup/register a callback function, in C++, to call a function when there is data to be read from a queue?
Edit 1:
Using Neil's answer for a complete answer (in header file):
#include <vector.h>
class QueueListener {
public:
virtual void DataReady(class MyQueue *q) = 0;
virtual ~QueueListene... | In outline, create a QueueListener base class:
class QueueListener {
public:
virtual void DataReady( class MyQueue & q ) = 0;
virtual ~QueueListener() {}
};
and a queue class (make this queue of integers as example:
class MyQueue {
public:
void Add( int x ) {
theQueue.push_back( x ... |
2,721,647 | 2,721,923 | How can I make the compiler create the default constructors in C++? | Is there a way to make the compiler create the default constructors even if I provide an explicit constructor of my own?
Sometimes I find them very useful, and find it a waste of time to write e.g. the copy constructor, especially for large classes.
| The copy constructor is provided whether you define any other constructors or not. As long as you don't declare a copy constructor, you get one.
The no-arg constructor is only provided if you declare no constructors. So you don't have a problem unless you want a no-arg constructor, but consider it a waste of time writi... |
2,721,648 | 2,721,698 | C++ Unary - Operator Overload Won't Compile | I am attempting to create an overloaded unary - operator but can't get the code to compile. A cut-down version of the code is as follows:-
class frag
{
public:
frag myfunc (frag oper1,
frag oper2);
frag myfunc2 (frag oper1,
frag oper2);
friend ... | const-correctness
This has to be
frag operator+ (const frag &oper1, const frag &oper2);
or else the operands can't be temporaries, such as the return value of operator-
And unary minus should rather be:
frag operator - () const;
since it shouldn't modify the operand.
|
2,721,762 | 2,721,802 | What are windows IPC methods | Question: I have a dll that I can load in another program.
Now the dll has access to all data/functions in the other program.
Which technology can I use that now an external program can send data/commands to that dll, to steer the other program, or get data from it ?
I mean, in the past that meant DDE, I think that was... | Some common ones are:
Named Pipes. Fairly easy to implement.
Shared Memory. A little more work but may be a little bit faster (at least in my testing).
Sockets. This is fairly simple and very portable but not as high performance. But it is sure nice if you suddenly want to be able to communicate with a process run... |
2,721,846 | 2,722,869 | Alternative to c++ static virtual methods | In C++ is not possible to declare a static virtual function, neither cast a non-static function to a C style function pointer.
Now, I have a plain ol' C SDK that uses function pointers heavily.
I have to fill a structure with several function pointers. I was planning to use an abstract class with a bunch of static pu... | You can make Base be a class template that takes its function pointers from its template argument:
extern "C" {
struct CStruct
{
void (*funA)(int, char const*);
int (*funB)(void);
};
}
template <typename T>
class Base
{
public:
CStruct myStruct;
void FillPointers() {
myStruct.funA = &T::myFunA;
myStruc... |
2,722,184 | 2,722,205 | Problem with default member functions of class in C++ (constructor, destructor, operator=, copy constructor) (default ctor, dtor, copy ctor) | We know that compiler generates some member functions for user-defined class if that member functions are not defined but used, isn't it. So I have this kind of code:
class AA
{
};
void main()
{
AA a;
AA b(a);
a = b;
}
This code works fine. I mean no compiler error. But the following code....
class AA
{
... | The compiler-synthesised default constructor calls the default constructors for all class members that have constructors. But integers don't have constructors, and so are not initialised. However, I find it hard to believe that this will cause a run-time error.
To initialise those variables:
class AA {
public:
A... |
2,722,222 | 2,722,265 | Does it make a difference whether I put 'friend class xxxxx' in the public or private section? | class A1 { public: friend class B; }
class A2 { private: friend class B; }
Any difference?
| No, access specificators have no effect on friend declaration.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.