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,078,515 | 2,078,987 | Why aren't there compiler-generated swap() methods in C++0x? | C++ compilers automatically generate copy constructors and copy-assignment operators. Why not swap too?
These days the preferred method for implementing the copy-assignment operator is the copy-and-swap idiom:
T& operator=(const T& other)
{
T copy(other);
swap(copy);
return *this;
}
(ignoring the copy-elis... | This is in addition to Terry's answer.
The reason we had to make swap functions in C++ prior to 0x is because the general free-function std::swap was less efficient (and less versatile) than it could be. It made a copy of a parameter, then had two re-assignments, then released the essentially wasted copy. Making a copy... |
2,078,544 | 2,078,591 | question about throwing an object | #include <iostream>
using namespace std;
class A{
public:
A() {std::cout<<"A() ";}
A(const A& a){cout<<"A(const A&) ";}
~A(){cout<<"~A() ";}
virtual void Foo(){cout<<"A::Foo() ";}
};
class B: public A
{
public:
B(){std::cout<<"B() ";}
B(const B& a){cout<<"B(const B&) ";}
~B(){cout<<"~B() ... | Because in the first sample the local variable b is first being copied at the throw line, and then sliced at the catch ( A ex ) line, while in the second sample only the second copy is performed.
I think I have to mention the throw by value, catch by reference mantra here :)
|
2,078,567 | 2,078,582 | very basic c question | as we use pointers in the argument list of functions like
void f(int *);
this means that this function will receive a pointer to an integer
but what does this means
void f(int ***);
and
void f(int **=0)
| void f(int ***);
means that the function receives a pointer to a pointer to a pointer to an int. This would work with it:
int x=42;
int *px=&x;
int **ppx=&px;
int ***pppx=&ppx;
f(pppx);
Now about the 2nd one, its a function that receives a pointer to a pointer to an int, and if you give it nothing, it defaults to 0.... |
2,078,844 | 2,078,922 | Odd Memory Error -- Bad Alloc | Working on a WinPCap project. Trying to do some basic pointer and memory operations and having lots of errors.
I've included the two lines I'm trying to run along with the includes.
The same lines in another VSC++ project work just fine. This is the error I am getting
Unhandled exception at 0x75a79617 in
pktdump_ex.... | My guess is the freestore is corrupted by one the previous statements (perhaps by an incorrect use of the pcap interface), and you only learn of the error on the next memory allocation or release, when the manager detects it and throws a bad alloc.
|
2,079,103 | 2,080,711 | OpenCV's clustering function cvKMeans2() - what is a type of cluster center in array? | I'm using function cvKMeans2() from OpenCV library for clustering. It has optional parametr:
centers - The optional output array of the cluster centers
The same parametr is also in function kmeans().
I want to know informations about clusters. But I haven't found what is a type of that cluster center in array, so I can... | In OpenCV 2.0, the equivalent kmeans function takes a CV_32FC1 matrix, but OpenCV 2.0 is quite a substantial upgrade to the old kmeans2 function, so I cannot be sure if the cluster centers datatype would still be the same for the OpenCV 1.1 version.
|
2,079,118 | 2,079,134 | Cannot Modify Non Const Member in Class | I try to modify one specific method in OpenCV. In the class definition;
class CV_EXPORTS CvANN_MLP : public CvStatModel
...
protected
...
int activ_func;
when I try to modify activ_func field, I get:
error: assignment of data-member in read-only structure
error, however it is not defined as const, how is that possi... | Unfortunately, you didn't give the context of the assignment statement itself. But I'm guessing that you're trying to assign to activ_func from a const member function.
|
2,079,296 | 2,079,314 | C++ Templates - LinkedList | EDIT -- Answered below, missed the angled braces. Thanks all.
I have been attempting to write a rudimentary singly linked list, which I can use in other programs. I wish it to be able to work with built-in and user defined types, meaning it must be templated.
Due to this my node must also be templated, as I do not know... | Might wanna try
Node<T>* temp = new Node<T>;
Also, to get hints on how to design the list, you can of course look at std::list, although it can be a bit daunting at times.
|
2,079,366 | 2,079,377 | How to secure communication between two c++ programs over ssh | This might be a non-programming question.
Exposition:
1) I am using Linux.
2) I have two C++ programs, "client" and "server"; they run on different machines, they currently talk over tcpip. I have the source code to both programs.
3) Neither program does buffer over flow checking / defense against man in the middle ata... | As far as programming solutions go, you'd need OpenSSL or GNU TLS. Out of those two the latter is a lot more cleanly written (OpenSSL has many pitfalls).
For a really elegant solution one would use OpenSSL via boost::asio, but that solution is probably suitable only if you're starting a new project.
In terms of user-s... |
2,079,386 | 2,079,394 | 2D vector modelling for game development | Making my Asteroids clone (in C) I've rather fallen in love with vector-based entities, but I've simply coded them in as x,y-point arrays. That's been fine for something like Asteroids, but what should I do if I want to make more complex 2D models?
I note that there is an awful lot of 3D modelling software out there, a... | As far as 2D vector game programming goes, it usually is the domain of Flash and Flex.
Still SVG and loading it via Cairo seems to be a viable solution. Although I'd take care to make sure that you have hardware acceleration enabled (OpenGL backend preferably).
As far as 2D formats go, you won't get as good support as ... |
2,079,600 | 2,079,624 | Initializiation confusion | Not sure of the appropriate title, but it stems from this discussion:
Do the parentheses after the type name make a difference with new?
On Visual Studio 2008, when I run the following code:
struct Stan
{
float man;
};
int main()
{
Stan *s1 = new Stan;
Stan *s2 = new Stan();
}
Examining the locals, s1 ha... | Adding a string stops the struct from being a POD class because a POD class must be an aggregate class with no members of type non-POD-struct and std::string has (amongst other things) user-declared constructors which makes it a non-POD-struct.
This is a known bug/feature of Visual Studio 2008. It doesn't support C++03... |
2,079,632 | 2,079,681 | Having a class with no data members good option for file manipulation? | I have a file with saved data that sometimes needs to be accessed, written to, erased, etc. when the program is running. I decided to write a SavedDataHandler class to accomplish this. I'm currently using the fstream class.
I considered having one data member be the fstream itself, opening it in the constructor, and c... | Well in some projects, wrapping is essential. Just stop to think if later you'll need for example, to change the file I/O libs (dunno why you'd want to do that, since C++ libs are optimized and ISO). What would you do then? Change all the calls from fstream to YourNewSuperMegaLib::SuperFileSystem::MegaFileStream?
If yo... |
2,079,638 | 2,083,653 | How to print the return type of a function in Visual Studio 2008 (C++)? | Imagine you have a function, if you hover over it with the mouse in visual studio you'll get the function prototype. Is it possible to print to the screen the return type of this function ?
This is a practical question, not a programming one. Does the functionality exist in VS ?
| I don't know a direct way, but here's a workaround that is relatively easy.
Right click on the function name.
Choose either "Go to definition" or "Go to declaration".
Select/copy the return type using standard copy/paste features.
|
2,079,653 | 2,079,667 | In a C++ template function can I return a dereferenced argument type? | What I mean is the following. I want a template function that takes two vector iterators (or two pointers to array of double) and returns a double that is somehow related to the vector iterators or array pointers that I pass. However, I want this to work for double or int, or any arithmetic type.
I think I'm not allowe... | If you want to return a double (i.e the type that you would get when dereferencing), you can use the iterator traits:
template<typename RandomAccessIterator>
typename std::iterator_traits<RandomAccessIterator>::value_type
func(RandomAccessIterator a, RandomAccessIterator b) {
typedef typename std::iterator_traits<... |
2,079,684 | 2,079,695 | Converting a Char to Its Int Representation | I don't see this an option in things like sprintf().
How would I convert the letter F to 255? Basically the reverse operation of conversion using the %x format in sprintf?
I am assuming this is something simple I'm missing.
| char const* data = "F";
int num = int(strtol(data, 0, 16));
Look up strtol and boost::lexical_cast for more details and options.
|
2,079,828 | 2,079,840 | Why does my simple C++ GUI application show a message box in Chinese? |
Oh as for the whole (LPCWSTR) casting thing: It wouldn't compile unless I put those in. It gave me this error message:
Error 1 error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [22]' to 'LPCWSTR'
| Put an L infront of your string to make it a wide string. L"Goodbye cruel World"
Then you won't need the cast.
You can also use the TEXT("") macro that will create an unicode string or ascii string depending on your configuration settings.
The reason you were seeing chinese is that MessageBox was interpreting an ascii ... |
2,079,851 | 2,079,855 | Invoke function within class method from outside the class with name the same like one method in class has | Is there a simple way to invoke the function within some class method from outside the class with name the same like one method in class has.
I have 3 different examples.
void a () { // outside the class
}
class A {
// example 1, the same names
void a() {
a (); // but the outside one,
}
// ex... | To reference a name outside the current class, use an empty namespace operator ::.
void A::a()
{
::a (); // calls the outside one
}
|
2,079,890 | 2,079,928 | What does this compiler build statement mean? | I am a programming student in my second OOP class, which is taught in C++, and I am using Visual Studio 2008.
I keep encountering this weird statement when I build my project in VS, my project builds fine, I would just like to know what it means. It appears every time I build my project, doesn't matter if I click rebui... | You can safely ignore it.
Incremental linking speeds things up. What happens is that rather then do a link from scratch, it uses the results of the last link to speed things up.
If it can't do an incremental link, it issues you that warning and does a full link. All it means is that it will take longer to link.
|
2,079,912 | 2,080,057 | Simpler way to create a C++ memorystream from (char*, size_t), without copying the data? | I couldn't find anything ready-made, so I came up with:
class membuf : public basic_streambuf<char>
{
public:
membuf(char* p, size_t n) {
setg(p, p, p + n);
setp(p, p + n);
}
}
Usage:
char *mybuffer;
size_t length;
// ... allocate "mybuffer", put data into it, set "length"
membuf mb(mybuffer, length);
ist... | I'm assuming that your input data is binary (not text), and that you want to extract chunks of binary data from it. All without making a copy of your input data.
You can combine boost::iostreams::basic_array_source and boost::iostreams::stream_buffer (from Boost.Iostreams) with boost::archive::binary_iarchive (from Boo... |
2,079,937 | 2,080,134 | How do I use chi square distribution with C++ Boost library? | I've checked the examples in the Boost website, but they are not what I'm looking for.
To put it simple, I want to see if a number on a die is favored, using 600 rolls, so the average appearances of every number (1 through 6) should be 100.
And I want to use the chi square distribution to check if the die is fair.
Help... | Suppose e[i] and o[i] are arrays holding the expected and observed count of rolls for each of the 6 possibilities. In your case, e[i] is 100 for each bin, and o[i] is the number of times i was rolled in your 600 trials.
You then calculate the chi-squared statistic by summing (e[i]-o[i])2/e[i] over
the 6 bins. Lets sa... |
2,080,233 | 2,080,238 | Is it good programming to have lots of singleton classes in a project? | I have a few classes in a project that should be created only once.
What is the best way to do that?,
They can be created as static object.
Can be created as singleton
Can be created as global.
What is the best design pattern to implement this?
I am thinking of creating all classes as singleton, but that would create... | Take a look at Steve Yegge's blog post about this - Singleton Considered Stupid
|
2,080,277 | 2,080,319 | Is there a language with RAII + Ref counting that does not have unsafe pointer arithmetric? | RAII = Resource Acquisition is Initialization
Ref Counting = "poor man's GC"
Together, they are quite powerful (like a ref-counted 3D object holding a VBO, which it throws frees when it's destructor is called).
Now, question is -- does RAII exist in any langauge besides C++? In particular, a language that does not allo... | Perl 5 has ref counting and destructors that are guaranteed to be called when all references fall out of scope, so RAII is available in the language, although most Perl programmers don't use the term.
And Perl 5 does not expose raw pointers to Perl code.
Perl 6, however, has a real garbage collector, and in fact allows... |
2,080,281 | 2,080,333 | How do I mmap a _particular_ region in memory? | I have a program. I want it to be able to mmap a particular region of memory over different runs.
I have the source code of the program. C/C++
I control how the program is compiled. gcc
I control how the program is linked. gcc
I control how the program is run (Linux).
I just want to have this particular region of mem... | You cannot make sure that nothing else takes that area of memory - first come, first served. However, as you need a particular part of the memory, I'm guessing that you have a pretty specialized environment, so you simply need to make sure that you are first (using start scripts)
|
2,080,328 | 2,081,691 | Test framework for component testing | I am looking for a test framework that suit my requirements. Following are the steps that I need to perform during automated testing:
SetUp (There are some input files, that needs to be read or copied into some specific folders.)
Execute (Run the stand alone)
Tear Down (Clean up to bring the system in its old state)
... | After reading this article http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle some time ago I went for CxxTest.
Once you have the thing set up (you need to install python for instance) it's pretty easy to write tests (I was completely new to unit tests)
I use it at work, integrated as a visual stu... |
2,080,405 | 2,080,426 | Newbie QT question about connect | I just tried to set up a small QT example and the connect statement fails to compile.
the error message from the compiler is: "no matching function for call to 'MainWindow::connect(...'"
what am I doing wrong her?
Thank you for your help.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNetw... | QObject::connect expects pointers to QObject's, you are passing networkManager as a normal variable. Just changing connect(networkManager...) to connect(&networkManager...) should do the trick.
|
2,080,610 | 2,080,616 | What's the best way to program c++ on a Mac? | What is the best software ( open source ) for programming on c++ a Mac ?
any suggestions?
| Xcode, same as C and ObjC.
|
2,080,679 | 2,080,696 | mysqlclient library linkage problem | I am linking an application with mysqlclient library on 64-bit CentOS 5.4 and get a linkage error (cannot find -lmysqlclient).
The library is in /usr/lib64/mysql/:
una@localhost$ ll /usr/lib64/mysql/
total 9072
...
lrwxrwxrwx 1 root root 26 Jan 3 15:54 libmysqlclient_r.so -> libmysqlclient_r.so.15.0.0
lrwxrwx... | -L/usr/lib64/mysql
The ld.so.conf stuff is only used at runtime, not compile time.
|
2,080,681 | 2,080,693 | Difference of Enum between java and C++? | I am learning Enums in java I like to know what are the major differences of Enum in java and C++.
Thanks
| In C++, an enumeration is just a set of named, integral constants. In Java, an enumeration is more like a named instance of a class. You have the ability to customize the members available on the enumeration.
Also, C++ will implicitly convert enum values to their integral equivalent, whereas the conversion must be expl... |
2,080,862 | 2,081,359 | QScintilla, example project doesn't work | I wanted to try QScintilla out. So i downloaded and installed it, no problems.
When i ran the example project it said I was missing QtCored4.dll, so i copied it into the directory, then it said it needed other dll's aswell so copied them too.
At the end it gives me a Visual C++ Runtime error. It just says it terminated... | I have no problems with QScintilla. I have Qt 4.6 compiled from sources with VC++ 2008. After downloading QScintilla-gpl-2.4.1 and unpacking I compiled it with:
cd Qt4
qmake qscintilla.pro
nmake
and finally installed with
nmake install
copy %QTDIR%\lib\qscintilla2.dll %QTDIR%\bin
And while compiling and running exam... |
2,080,892 | 2,096,771 | How to create a virtual file? | I'd like to simulate a file without writing it on disk. I have a file at the end of my executable and I would like to give its path to a dll. Of course since it doesn't have a real path, I have to fake it.
I first tried using named pipes under Windows to do it. That would allow for a path like \\.\pipe\mymemoryfile but... | You can store the data in an NTFS stream. That way you can get a real path pointing to your data that you can give to your dll in the form of
x:\myfile.exe:mystreamname
This works precisely like a normal file, however it only works if the file system used is NTFS. This is standard under Windows nowadays, but is of cou... |
2,080,912 | 2,080,921 | What to do with private member functions when turning static class to namespace in C++? | I have a class that has 5 static public functions and 1 static private function (called from one of the public functions). The class doesn't have any member variables. It seems to me that it should be a namespace and not a class. But what to do with the private function? I prefer it not to be accessible by every namesp... | There are two ways i know of
Don't declare them in the header
One way is to not declare those functions inside the header. They can be placed into unnamed namespaces within the implementation file, only.
Indeed, you will then have to implement any function that accesses this private function in the implementation file... |
2,081,175 | 2,081,962 | Template parameters dilemma | I have a dilemma. Suppose I have a template class:
template <typename ValueT>
class Array
{
public:
typedef ValueT ValueType;
ValueType& GetValue()
{
...
}
};
Now I want to define a function that receives a reference to the class and calls the function GetValue(). I usually consider the followi... | If your function is very specific to ArrayType, and no other template will satisfy its interface requirements, use #1 as it's both shorter and more specific: the casual reader is informed that it operates on an ArrayType.
If there's a possibility that other templates will be compatible with DoGetValue, use #2 as it's m... |
2,081,431 | 2,081,497 | Best way to slow down a thread? Is using Sleep() OK? | I've written a C++ library that does some seriously heavy CPU work (all of it math and calculations) and if left to its own devices, will easily consume 100% of all available CPU resources (it's also multithreaded to the number of available logical cores on the machine).
As such, I have a callback inside the main calcu... | Sleep should be fine for throttling an app, which from your comments is what you're after. Perhaps you just need to be more precise how long you sleep for.
The only software in which I use a feature like this is the BOINC client. I don't know what mechanism it uses, but it's open-source and multi-platform, so help your... |
2,081,690 | 2,081,701 | C#: Can i write "private:" or "protected:" regions like in C++ | In C++ you can write:
private:
int w;
string x;
protected:
int y;
string z;
is there something similar in C# ?
| No, there are no regions with a specific access type in C#. Every member of a class or struct must have an explicit access modifier or accept the default access modifier private.
Also, on the topic of access modifiers in C# compared to C++, C# has two additional modifiers internal and protected internal. The modifier i... |
2,081,710 | 2,082,472 | What is the best way to do 2D animation? | I'm writing a 2D animation class, and I've got TGA pictures in which the player animation is stored. These pictures are 8x8 tiles (so on each row there are 8 frames of a moving character)
However, I don't have a clue on how to animate this in code.
I was thinking about updating it by moving the u-v coordinates each fra... | Sup dawg.
Seeing as you're using the UV coordinates of the texture that contains all your animation states, you'll need to convert from pixel coordinates to UV coordinates.
If your sprite is 32 pixels wide and your texture is 256 pixels wide (thus containing 8 frames), you'll want to divide the width of the sprite by t... |
2,081,738 | 2,081,769 | Can I use the C++ Boost shared_ptr to program as if I was coding in Java, as in, not care about memory management? | It's been a while I coded in C/C++, and now I need its efficiency for a project I'm doing.
What I understand from this shared_ptr is that it basically deletes the object when I need it to. So, if, for example, my object has a vector of shared_ptr, I wouldn't have to worry about iterating through the vector and deleting... | You have to understand that shared pointers are implemented using a reference count, that means that if you have cycles in your pointer graph then the objects will not be released. That is, if a points to b and b points to a but nothing points to a or b, then neither a nor b will be released because they both have a re... |
2,081,905 | 2,081,988 | Undefined reference to non-member function - C++ | I have the following in header file.
namespace silc{
class pattern_token_map
{
/* Contents */
};
pattern_token_map* load_from_file(const char*);
}
In the CPP file (this has got proper includes)
pattern_token_map* load_from_file(const char* filename)
{
// Implementation goes here
}
In another CPP... | When you implement it, you have to make sure you implement the right function:
namespace silc {
pattern_token_map* load_from_file(const char* filename) {
// Implementation goes here
}
}
If you instead did this:
using namespace silc; // to get pattern_token_map
pattern_token_map* load_from_file(const char* filename)... |
2,082,099 | 2,082,274 | Difference between operator new and operator new[]? | I've overloaded the global operator new/delete/new[]/delete[] but simple tests show that while my versions of new and delete are being called correctly, doing simple array allocations and deletes with new[] and delete[] causes the implementations in newaop.cpp and delete2.cpp to be called.
For example, this code
int* ... | Ok, I managed to crack this so am posting in case anyone else stumbles upon this.
The reason for the operator not being called was because my implementation was located in a library, not in the project which called the operators. In fact, since technically you only need to include an implementation of the operators, th... |
2,082,156 | 2,082,178 | Hiding private constants in an inline namespace header | I have some inline functions contained within a namespace in a header file and am not currently in a position to move them into a cpp file. Some of these inline functions use magic constants, for example:
// Foo.h
namespace Foo
{
const int BAR = 1234;
inline void someFunc()
{
// Do something with ... | You can't, anonymous namespaces work for the translation unit they are defined in (or included into in your case).
You could consider moving them into a detail namespace to signal to the user that they are internal details:
namespace foo {
namespace detail {
int magic = 42;
}
// ... use detail::mag... |
2,082,339 | 2,083,011 | Virtual tables on anonymous classes | I have something similar to this in my code:
#include <iostream>
#include <cstdlib>
struct Base
{
virtual int Virtual() = 0;
};
struct Child
{
struct : public Base
{
virtual int Virtual() { return 1; }
} First;
struct : public Base
{
virtual int Virtual() { return 2; }
} Second;
};
int main()
... | It is visible how MSVC is getting it wrong from the debugging symbols. It generates temporary names for the anonymous structs, respectively Child::<unnamed-type-First> and Child::<unnamed-type-Second>. There is however only one vtable, it is named Child::<unnamed-tag>::'vftable' and both constructors use it. The dif... |
2,082,453 | 2,082,492 | Object oriented programming , inheritance , copy constructors | Suppose I have a base class Person and I publicly inherit a class Teacher from base class Person.
Now in the main function I write something like this
// name will be passed to the base class constructor and 17
// is for derived class constructor.
Teacher object(“name”,17) ;
Teacher object1=object; //call to copy ... | You have to call the base copy constructor explicitly:
Teacher(const Teacher& other)
: Person(other) // <--- call Person's copy constructor.
, num_(other.num_)
{
}
Otherwise Person's default constructor will be called.
I seem to not fully understand the question so I'll just say everything I think is relevan... |
2,082,664 | 2,082,677 | Ofstream writing the wrong thing into a file | Hey guys, I couldn't really think of what to call this error in the title, so here goes.
I'm starting an assignment where I have to read the contents of a file, perform some calculations and write the contents + the new calculations to a file.
I wrote the code to read in the file, and to right away write it into an o... | The correct way to read a file line by line is:
string line;
while( getline( file, line ) ) {
// do something with line
}
For why this is so, you might want to take a look at this blog post of mine.
|
2,082,739 | 2,082,814 | Optimizing for space instead of speed in C++ | When you say "optimization", people tend to think "speed". But what about embedded systems where speed isn't all that critical, but memory is a major constraint? What are some guidelines, techniques, and tricks that can be used for shaving off those extra kilobytes in ROM and RAM? How does one "profile" code to see whe... | My experience from an extremely constrained embedded memory environment:
Use fixed size buffers. Don't use pointers or dynamic allocation because they have too much overhead.
Use the smallest int data type that works.
Don't ever use recursion. Always use looping.
Don't pass lots of function parameters. Use globals ins... |
2,082,972 | 2,083,002 | Array as private member of class | I am trying to create a class which has a private member that is an array. I do not know the size of the array and will not until the value is passed into the constructor. What is the best way to go about defining the class constructor as well as the definition in the .h file to allow for this variable size of the arra... | If you want a "real" C-style array, you have to add a pointer private member to your class, and allocate dynamically the memory for it in the constructor (with new). Obviously you must not forget to free it in the destructor.
class YourClass
{
private:
int * array;
size_t size;
// Private copy constructo... |
2,083,060 | 2,083,068 | What could C/C++ "lose" if they defined a standard ABI? | The title says everything. I am talking about C/C++ specifically, because both consider this as "implementation issue". I think, defining a standard interface can ease building a module system on top of it, and many other good things.
What could C/C++ "lose" if they defined a standard ABI?
| The freedom to implement things in the most natural way on each processor.
I imagine that c in particular has conforming implementations on more different architectures than any other language. Abiding by a ABI optimized for the currently common, high-end, general-purpose CPUs would require unnatural contortions on som... |
2,083,096 | 2,083,115 | What will this construction do? | std::vector<int> a;
int p;
int N;
// ...
p = a[ N>>1 ];
What is the N>>1 part?
| Divides N by 2 (by bit shifting right 1) and using that as the index into the vector a to assign p.
|
2,083,135 | 2,083,150 | visual studio 2008 isn't creating an .exe file when i build my project. any ideas why? | i'm new to visual studio and couldn't find anything on google about this. i know this is an extremely noobish question, but i can't seem to find any info for it.
the debug shows me whatever i write, and the build has no errors, so i know the code i'm writing is fine.
the release folder doesn't contain the .exe, even af... | Some possible reasons:
Did you accidentally create a class library project? In that case the output would be a DLL and not an EXE.
Does the output window or the error list display any build errors? In that case you should first fix these, then build again.
Did you change the configuration of the project, so that the o... |
2,083,163 | 2,083,217 | Why doesn't std::istream assume ownership over its streambuf? | I am writing some sort of virtual file system library for video-games in the likes of CRI Middleware's ROFS (see Wikipedia). My intention with the library is to provide natural means of accessing the resources of the games I develop, which store some data embedded in the executable, some on the media and some on the lo... | You could just derive your own stream classes from istreamresp. ostream, set the buffer
in the constructor and destroy it in the destructor.
Something like:
class config_istream : public std::istream {
public:
config_istream(std::string name) :
std::istream(fslib.InputStream(name.c_str()))
{
}
... |
2,083,200 | 2,083,208 | Optimal method to create a large string containing several variables? | I want to create a string that contains many variables:
std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";
std::string sentence;
sentence = name1 + " and " + name2 + " sat down with " + name3;
sentence += " to play cards, while " + name4 + " played t... | Yes, std::stringstream, e.g.:
#include <sstream>
...
std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";
std::ostringstream stream;
stream << name1 << " and " << name2 << " sat down with " << name3;
stream << " to play cards, while " << name4 << " playe... |
2,083,603 | 2,083,629 | STL containers element destruction order | Does ISO C++ standard mandate any sort of destruction order of objects inside STL containers?
Are std::list/std::vector/std::map elements destroyed starting from the beginning or the end of the container?
Can I rely on std::map storing its elements in std::pairs internally so a key in a pair is destroyed before its va... |
Unspecified in the standard.
Yes, but this means that the key is destroyed after its associated value.
|
2,083,721 | 2,083,736 | Should I use a class of functions or a namespace of functions? | Say I want some functions to deal with some file, and I was considering 2 options.
1) Create a class like SavedDataHandler that a user could use like this....
// Note that SavedDataHandler has no members. It just has functions that operate on a
// resource ( the file)
SavedDataHandler gameSave;
gameSave.SaveData( arg1,... | I tend to the following simplified pattern:
if its only used by one class and likely to stay that way, put it in the implementation file in an anonymous namespace.
if it is of use for more then one class and doesn't need access to a class' internal state, put it in a namespace.
if it needs access to the class inte... |
2,083,771 | 2,085,502 | A method to calculate the centre of mass from a .stl (stereo lithography) file? | I am trying to calculate the centre of mass (x,y,z) coordinates of an object defined in an STL file (stereo lithography, not to be confused with the standard template library). The STL file contains a closed object (or objects) defined by a boundary made of triangles. The triangles themselves are not necessarily in any... | After a lot of thinking and experimentation I have the answer!
First we add a 4th point to each triangle in to make them into tetrahedrons with a volume centroid. We calculate the volumes and centres of masses and multiply them by each other to get our moments. We sum the moments and divide by total volume to get our o... |
2,083,941 | 2,084,230 | How do I get OpenGL/GLUT working with Eclipse IDE (cocoa 64 bit) using C++ and on Snow Leopard | This seems like it should be strait forward, but a lot of the information I'm finding it pre-snow leopard, deals with cocoa and carbon, or the XCode IDE. None of which helps me with my problem at hand.
I simply want to compile, and run openGL using C++ without becoming dependent on the Mac environment since I will mos... | Please see my answer at OpenGL and GLUT in Eclipse on OS X
|
2,083,969 | 2,084,003 | 'hash_map' was not declared in this scope with g++ 4.2.1 | I am trying to use sgi hash_map.
#include <list>
#include <iostream>
#include <string>
#include <map>
#include <cstring>
#include <tr1/unordered_map>
#include <ext/hash_map>
using namespace std;
struct eqstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};
int ma... | The include file <ext/hash_map> refers to the GNU extension hash map class and this is declared in namespace __gnu_cxx. You can either explicitly qualify the template name or add:
using namespace __gnu_cxx;
|
2,084,098 | 2,084,339 | Two C++ apps sharing a read-only region of memory on Linux | I have two processes P1 and P2.
I have this large read-only resource, called "R" that I want both P1 and P2 to have access to.
R is not just a "flat" group of bytes; it's a bunch of C++ objects that point to each other.
I would prefer that P1 and P2 only share one copy of R -- somehow have P1 load R into a region in me... | Actually something similar has been asked and solved before:
And the best answer will probably work for you:
Use boost interprocess library. While you still can't use objects with virtual functions (nasty vtable pointer outside shared memory issue), they do have tools to let you use smart pointers to other objects ins... |
2,084,265 | 2,084,337 | Reading integers from a text file with words | I'm trying to read just the integers from a text file structured like this....
ALS 46000
BZK 39850
CAR 38000
//....
using ifstream.
I've considered 2 options.
1) Regex using Boost
2) Creating a throwaway string ( i.e. I read in a word, don't do anything with it, then read in the score ). However, this is a last resort... | why to make simple things complicated?
whats wrong in this :
ifstream ss("C:\\test.txt");
int score;
string name;
while( ss >> name >> score )
{
// do something with score
}
|
2,084,503 | 2,084,518 | What's a fluent interface? | I recently came across this expression - but reading up on Wikipedia did not clarify it much for me - I still don't get it:
What's the point of it
How is it used in practice (i.e. how does it benefit a coder in their day to day work/building systems)?
[Edit]
The Wikipedia article C++ example is overly long, and confl... | It benefits the coder by reducing the amount he has to type (and read).
To use the C++ example on Wikipedia:
Before:
int main(int argc, char **argv) {
GlutApp app(argc, argv);
app.setDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_ALPHA|GLUT_DEPTH); // Set framebuffer params
app.setWindowSize(500, 500); // Set wi... |
2,084,575 | 2,084,597 | Best Practices For Creating a Log Writer for errors | I have recently been doing some work that has been quite in depth,
i was wondering what you think is better for logging.
Is it better to.
A. Every time i want to write to my log, open the file, write to it
then close it straight away so it there is no real chance of losing
information in the case of a critical fa... | To my knowledge, it's fairly common (mandated?) for a stream flush to be the equivalent to saving.
That is, when you say:
file.flush();
Everything waiting to be written is written. Note that std::endl; also calls flush. So, leave it open and just flush after a dump of information.
|
2,084,801 | 2,084,990 | c++ using declaration, scope and access control | Typically the 'using' declaration is used to bring into scope some member functions of base classes that would otherwise be hidden. From that point of view it is only a mechanism for making accessible information more convenient to use.
However: the 'using' declaration can also be used to change access constraints (not... | With regard to your declaration without using: These are called "access declarations", and are deprecated. Here is the text from the Standard, from 11.3/1:
The access of a member of a base class can be changed in the derived class by mentioning its qualified-id in
the derived class declaration. Such mention is call... |
2,084,871 | 2,084,942 | Which C++ cross platform GUI framework has good skinning ability? | What is a cross-platform C++ GUI framework that has good skinning ability?
So I could (and give the users) the ability to customise the GUI.
| EDIT: As you're looking for something like wxSkin, first why not use it in the first place?
Then, if you don't want to use wxSkin, have a look at Juce. Qt's goal is definitely not themeable GUIs although windows masks and stylesheets are a way to implement them. There is the QSkingObject project on Qt-Apps.org but last... |
2,084,935 | 2,084,973 | WIN API User Privilege C++ | I'm trying to see if the user has the SeLoadDriver privilege. I've got the PLUID :
PLUID pld;
LookupPrivilegeValue(NULL, SE_LOAD_DRIVER_NAME, pld);
But now i'm not sure how to get a bool from the PLUID stating that the user has, or not, the privilege. I've read the related methods but it think that it might be... | It's a little more involved than that.
First you need to obtain the process token's privilege set (by calling GetTokenInformation()) then you scan the buffer that you've got from that (which is an array of LUID_AND_ATTRIBUTES structures) for the LUID that you get from LookupPrivilegeValue(). You can then use the LUID_A... |
2,085,211 | 2,094,616 | Finding memory allocation error | I'm getting memory allocation errors (and a subsequent crash) on the following simplified code:
std::wstring myKey = L"str_not_actually_constant";
MyType obj;
Read( obj );
std::map<std::wstring, MyType> myMap;
myMap[myKey] = obj; // Sometimes allocation error (1)
...
Read( MyType& obj )
{
obj.member1 = ReadFromFunc... | Finally tracked down the error.
We are using the above functionality as part of a larger socket communication using OpenSSL (hence above reference). The socket was writing data and reading data as per above code simplification.
The way the socket was read was that we were re-allocating memory from one buffer to anoth... |
2,085,239 | 2,085,246 | Can I ungarble GCC's RTTI names? | Using gcc, when I ask for an object/variable's type using typeid, I get a different result from the type_info::name method from what I'd expect to get on Windows. I Googled around a bit, and found out that RTTI names are implementation-specific.
Problem is, I want to get a type's name as it would be returned on Windows... | If it's what you're asking, there is no compiler switch that would make gcc behave like msvc regarding the name returned by type_info::name().
However, in your code you can rely on the gcc specific __cxa_demangle function.
There is in fact an answer on SO that addresses your problem.
Reference: libstdc++ manual, Chapte... |
2,085,302 | 2,085,385 | Printing all environment variables in C / C++ | How do I get the list of all environment variables in C and/or C++?
I know that getenv can be used to read an environment variable, but how do I list them all?
| The environment variables are made available to main() as the envp argument - a null terminated array of strings:
int main(int argc, char **argv, char **envp)
{
for (char **env = envp; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s\n", thisEnv);
}
return 0;
}
|
2,085,304 | 2,085,654 | Export c++ functions inside a C# Application | Greetings,
I am sorry for bothering, I'll show the question:
I am trying to export some functions written in c++ in a DLL in order to import them in a C# Application running on Visual Studio.
I make the export as reported in the following code,
tobeexported.h:
namespace SOMENAMESPACE
{
class __declspec(... | What about using managed C++ to compile your DLL? Then you just have to add a ref to the class like this:
namespace SOMENAMESPACE
{
public ref class SOMECLASS
{
public:
SOMETYPE func(param A,char b[tot]);
};
... |
2,085,427 | 2,325,933 | Link with an older version of libstdc++ | After installing a new build machine, I found out it came with 6.0.10 of the standard C++ library
-rw-r--r-- 1 root root 1019216 2009-01-02 12:15 libstdc++.so.6.0.10
Many of our target machines, however, still use an older version of libstdc++, for example:
-rwxr-xr-x 1 root root 985888 Aug 19 21:14 libstdc++.so.6.0... | You don't need to link to a different library, you need to use an older version of the compiler.
Have a look at the GNU ABI policy. The libstdc++ shared library is designed to be forward compatible. I.e. version 6.0.10 can be used if you need 6.0.8. In the policy you can read that from gcc-4.2.0 on, 6.0.9 is needed,... |
2,085,449 | 19,582,155 | .NET rounding error in ToString("f2") | Hello I have this code in C#:
float n = 2.99499989f;
MessageBox.Show("n = " + n.ToString("f2", CultureInfo.InvariantCulture));
And this code in C++:
float n = 2.99499989f;
printf("n = %.2f", n);
First one outputs 3.00.
Second one outputs 2.99.
I have no clue why this is happening.
Update:
I also tried Objective-C NSL... | (I realize this is an old question, but I'm answering this as I am understanding some things myself...)
My suggestion is that "printf" is converting the float to a double before applying the formatting.
I tried converting the float to a double, and then looking at the double's ToString("f2") result, which it did round ... |
2,085,501 | 2,087,203 | How to access private class fields from a test using UnitTest++? | I'm facing a nuisance when coding my unit tests using UnitTest++. I'm wondering how to access private member class fields in a clean way (or maybe any way...)
By now, I have a solution to access protected members using a class fixture deriving from the class under test. The following code shows the idea:
struct MyFixtu... | Unit testing is all about testing your objects through their public interface. The fact that it might be hard is why writing testable code is sometimes referred to as art. Not everyone can write testable code right away, that's why people invented XP approach of writing tests first. Sounds unrealistic, works in reality... |
2,085,511 | 2,087,046 | wait and notify in C/C++ shared memory | How to wait and notify like in Java In C/C++ for shared memory between two or more thread?I use pthread library.
| Instead of the Java object that you would use to wait/notify, you need two objects: a mutex and a condition variable. These are initialized with pthread_mutex_init and pthread_cond_init.
Where you would have synchronized on the Java object, use pthread_mutex_lock and pthread_mutex_unlock (note that in C you have to pai... |
2,085,639 | 2,085,777 | Faster way to create tab deliminated text files? | Many of my programs output huge volumes of data for me to review on Excel. The best way to view all these files is to use a tab deliminated text format. Currently i use this chunk of code to get it done:
ofstream output (fileName.c_str());
for (int j = 0; j < dim; j++)
{
for (int i = 0; i < dim; i++)
output... | Use C IO, it's a lot faster than C++ IO. I've heard of people in programming contests timing out purely because they used C++ IO and not C IO.
#include <cstdio>
FILE* fout = fopen(fileName.c_str(), "w");
for (int j = 0; j < dim; j++)
{
for (int i = 0; i < dim; i++)
fprintf(fout, "%d\t", arrayPointer[j ... |
2,085,845 | 2,085,865 | How to make C++ wrapper of C# DLL COM InterOp method? | I have a C# COM DLL and I want to call its methods throught c++ methods.
How do I make this?
| Ask VisualStudio to generate the typelib or use regasm.exe /tlb to generate the typelib, then import it into the C++ project with #import directive.
|
2,085,956 | 2,085,976 | C++ 'this' and operator overloading | I was wondering how can you use operators along with 'this'. To put an example:
class grd : clm
{
inline int &operator()(int x, int y) { return g[x][y]; }
/* blah blah blah */
};
grd grd::crop(int cx1, int cy1, int cx2, int cy2)
{
grd ngrd(abs(cx1-cx2), abs(cy1-cy2));
int i, j;
//
for (i = cx... | Either:
this->operator()(i,j) or (*this)(i,j)
|
2,085,998 | 2,086,093 | Portability of std::mem_fun expression | Assuming a correct instantiation in the indicated comment, is the following expression legal and portable C++? Why or why not?
std::mem_fun</*…*/>(&(std::vector<int>::clear))
| As it's written, with an empty set of template parameters, no. You need to either give the correct parameters, or leave them out altogether so they're inferred from the argument.
So this is legal:
std::mem_fun(&std::vector<int>::clear)
and so is this:
std::mem_fun<void,std::vector<int> >(&std::vector<int>::clear)
Bot... |
2,086,195 | 2,086,292 | OpenGL: the ultimate coordinate system confusion solution? | I'm tired of thinking how the hell my coodinates are working at each case.
I heard that I could flip the Y-axis by this code:
glScalef(1, -1, 1);
But should I? Doesnt this break some other external functions and lighting etc?
| There's no correct yes/no answer to this question. Calling glScalef(1, -1, 1) means using a left-handed instead of a right handed coordinate system, this has historically been the choice of for instance Direct3D and the RenderMan Interface. Some people feel it's more intuitive to have the positive z-axis pointing in to... |
2,086,296 | 2,086,964 | replacement project for existing school assignment | I have a school assignment which consists of programming a scanner/lexical analyzer for a specified simple language. The scanner has to be programmed in C++.
This type of assignment has been used since the 90's and, although still a valid excersise, I consider it to be a little antiquated and a little boring.
I have go... |
This type of assignment... is considered to be a little antiquated and a little boring.
I'm curious: who considers this antiquated? Your professor? Somebody notable in the parsing community? Or you?
Scanners and parsers are still relevant to professional software development and, more importantly, relevant to the sci... |
2,086,538 | 2,086,943 | Force template parameter to be a structure | I'm trying to do a base template class which parameter T must be a structure.
When I use a variable declared as being of type T (both in the template class as in a class that extends it defining T) GCC fails to compile it:
GCC error: invalid use of incomplete
type ‘struct x'
Despite it working on VC I understand th... | Most (if not all) times the compiler complains about using an 'incomplete' type the problem resides in trying to use a forward declared class that has not been completely defined.
There are just so many things you can do with an incomplete type: define functions that take or return the type or references to it, define ... |
2,087,015 | 2,138,675 | Best encryption library for mobile devices? | Hello I have been using LibTomCrypt to use SHA1 encryption ( for data integrity checking ) on mobile devices (iPhone OS and Android for the moment ). I was wondering if anyone is using anything else, things to consider are Portability ( C preferred but C++ is also an option ), and libraries size ( small == better for m... | I've looked a lot of libraries, and in the end I ended up going with "TomCrypt", for the following reasons:
1) Excellent portability. You can customize the library in a very very easy way in order to almost assure portability between lot's of devices.
2) Very modular, I could (in a very easy way) pick up and compile on... |
2,087,026 | 2,087,073 | Effect of using a comma instead of a semi-colon in C and C++ | I've noticed on a number of occasions when refactoring various pieces of C and C++ code that a comma is used rather than a semi-colon to seperate statements. Something like this;
int a = 0, b = 0;
a = 5, b = 5;
Where I would have expected
int a = 0, b = 0;
a = 5; b = 5;
I know that C and C++ allow use of commas to ... | It doesn't make a difference in the code you posted. In general, the comma separates expressions just like a semicolon, however, if you take the whole as an expression, then the comma operator means that the expression evaluates to the last argument.
Here's an example:
b = (3, 5);
Will evaluate 3, then 5 and assign th... |
2,087,379 | 2,087,431 | A Wrapper to hardware functions | I'm developing a project and I have to make a wrapper to some hardware functions.
We have to write and read data to and from a non-volatile memory. I have a library with the read and write functions from the seller company. The problem is that these functions should be called with a delay between each call due to hardw... | Adding a mediator in this context is a pretty typical solution so you aren't out in the weeds here. I would say you would need to implement this because the original functions are not reentrant. Assuming, of course, that you own the access to the hardware. (i.e. You are the driver.) If other people can get access t... |
2,087,582 | 2,087,624 | Converting std::list to C friendly type | What's the most elegant way to return a std::list object from a shared lib function (implemented by C++ code) to a C consumer? I know for std::vector, we can return the address of the 1st element of the vector and have the consumer treat it as an array, but std::list is implemented as a linked lis.
| Copy the std::list to a std::vector and return the address of the first element, as you already mentioned.
(Of course, this may mean that you don't want to be using a std::list in the first place.)
(This solution assumes that the object being accessed is owned by the C++ library -- If this isn't the case, you may need ... |
2,087,593 | 2,087,731 | Does the Boost unordered_map only work to associate items with integers? | I had a
HashMap<Node, Double>
in Java which I'd use later on to retrieve the double associated with a node. I've tried to do
boost::unordered_map<Node*, double>
but I get a "error C2108: subscript is not of integral type" when I try to put something in it, like:
map[some_node] = some_double;
If I interpreted the... | Unlike Java, C++ does not provide hashing functions for classes. If the type of the hashmap key is an integer or a pointer, then C++ can use the fact that an integer is its own hash, but it can't fo this for types you define yourself - in that case you have to provide a hash function explicitly. This can be hard to d... |
2,087,600 | 2,087,621 | Is a C++ destructor guaranteed not to be called until the end of the block? | In the C++ code below, am I guaranteed that the ~obj() destructor will be called after the // More code executes? Or is the compiler allowed to destruct the obj object earlier if it detects that it's not used?
{
SomeObject obj;
... // More code
}
I'd like to use this technique to save me having to remember to rese... | You are OK with this - it's a very commonly used pattern in C++ programming. From the C++ Standard section 12.4/10, referring to when a destructor is called:
for a constructed object with
automatic storage duration
when the block in which the object is
created exits
|
2,087,827 | 2,088,464 | keeping Eclipse-generated makefiles in the version control - any issues to expect? | we work under Linux/Eclipse/C++ using Eclipse's "native" C++ projects (.cproject). the system comprises from several C++ projects all kept under svn version control, using integrated subclipse plugin.
we want to have a script that would checkout, compile and package the system, without us needing to drive this process... | I know that this is a big problem (I had exactly the same; in addition: maintaining a build-workspace in svn is a real pain!)
Problems I see:
You will get into problems as soon as somebody adds or changes project settings files but doesn't trigger a new build for all possible platforms! (makefiles aren't updated).
The... |
2,087,840 | 2,087,942 | Add a Reference from a C# App to a DLL compiled without /clr? | I'm using Visual Studio 2008 to build a Solution with two Projects: a C# Console App and a C++ DLL. I want the app to call a function from the dll using P/Invoke. Therefore I'm trying to add the dll as a Reference to the C# app. But when I try the Add Reference command, Visual Studio won't let me do it unless I set the... | Why not just add a post-build step to copy your unmanaged DLL to your project directory? You don't need a "reference" to be able to refer to an unmanaged DLL, and it sounds like the only problem you're experiencing is due to the file not being automatically copied into the search path.
|
2,088,120 | 2,088,168 | How to read a REG_MULTI_SZ type value from the registry using RegQueryValueEx(..) in c++ | In our vc++ win32 application we are reading a registry value of type reg_multi_sz, its working fine on 32-bit but giving empty buffer when i ran on 64- bit. How can I read values of 64 bit registry from my 32-bit application ?
| Could you be more specific? Usually when your try to read 64-bit registry hive in 32-bit code you must open HKLM\Software using KEY_WOW64_64KEY. Hope that helps.
|
2,088,259 | 2,088,287 | Literal initialization for const references | How does the following code work in C++? Is it logical?
const int &ref = 9;
const int &another_ref = ref + 6;
Why does C++ allow literal initialization for const references when the same is not permitted for non-const references? E.g.:
const int days_of_week = 7;
int &dof = days_of_week; //error: non const reference ... | So you can write code like this:
void f( const string & s ) {
}
f( "foobar" );
Although strictly speaking what is actually happening here is not the literal being bound to a const reference - instead a temprary string object is created:
string( "foobar" );
and this nameless string is bound to the reference.
Note th... |
2,088,293 | 2,088,311 | How to write comparator function for qsort? | class for example:
class classname{
public:
int N,M;
};
classname a > classname b if a.N>B.N
| class classname{
public:
int N,M;
bool operator< (const classname& other) const { return N < other.N; }
};
...
std::vector<classname> arr;
...
std::sort(arr.begin(), arr.end());
Or do you want to use C's qsort?
static int compare_classname (const void* a, const void* b) {
const classname* _a = reinterpr... |
2,088,455 | 2,088,662 | How do I find the cause of this linker error? | After going through a lengthy process to rename a project, my DLL project will not build in Debug mode (Release builds work):
MSVCRTD.lib(msvcr90d.dll) : error LNK2005: _CrtDbgReportW already defined in LIBCMTD.lib(dbgrpt.obj)
This project, and the five static libraries it depends on, are set to use "Multi-threaded De... | LIBCMT is what you need for /MT, MSVCRT is what you need for /MD. You are linking .obj and .lib files that were mixed, some compiled with /MT some with /MD. That's not good.
Usually it is the .lib files that cause the problem. Review their build settings and make sure their /M option is the same as your DLL project.... |
2,088,477 | 2,088,496 | C++ checking the type of reference | Is it bad design to check if an object is of a particular type by having some sort of ID data member in it?
class A
{
private:
bool isStub;
public:
A(bool isStubVal):isStub(isStubVal){}
bool isStub(){return isStub;}
};
class A1:public A
{
public:
A1():A(false){}
};
class AStub:public A
{
public:
AStub():A(... | Generally, yes. You're half OO, half procedural.
What are you going to do once you determine the object type? You probably should put that behavior in the object itself (perhaps in a virtual function), and have different derived classes implement that behavior differently. Then you have no reason to check the object ty... |
2,088,495 | 2,088,542 | how to remove all even integers from set<int> in c++ | I'm new to C++. I'd like to know how experienced coders do this.
what I have:
set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
s.insert(5);
for(set<int>::iterator itr = s.begin(); itr != s.end(); ++itr){
if (!(*itr % 2))
s.erase(itr);
}
and of course, it doesn't work. because itr is incremented aft... | for(set<int>::iterator itr = s.begin(); itr != s.end(); ){
if (!(*itr % 2))
s.erase(itr++);
else ++itr;
}
effective STL by Scott Myers
|
2,088,930 | 2,088,941 | Using USB port from c++ | i was just wondering if somebody could give me any pointers about how to use USB ports on Ubuntu(and other unix systems) &&/|| (and/or :]) windows. I was trying to googling some stuff up but i failed horribly. Even names of libraries to be used etc would be appriciated.
Thanks, Tomas Herman
| You can use libusb for direct access to USB. http://www.libusb.org/
If you instead wish to use a USB serial port or other device for which the OS already has drivers, look for other means. E.g. /dev/input/event* or /dev/ttyUSB* devices on Linux.
|
2,088,944 | 2,088,955 | How do you use the non-default constructor for a member? | I have two classes
class a {
public:
a(int i);
};
class b {
public:
b(); //Gives me an error here, because it tries to find constructor a::a()
a aInstance;
}
How can I get it so that aInstance is instantiated with a(int i) instead of trying to search for a default constructor? Basical... | You need to call a(int) explicitly in the constructor initializer list:
b() : aInstance(3) {}
Where 3 is the initial value you'd like to use. Though it could be any int. See comments for important notes on order and other caveats.
|
2,089,021 | 2,089,068 | What is correct way to initialize a static member of type 'T &' in a templated class? | I'm playing around with an eager-initializing generic singleton class. The idea is that you inherit publicly from the class like so:
class foo : public singleton<foo> { };
I've learned a lot in the process but I'm stuck right now because it's breaking my Visual Studio 2008 linker. The problem is with the static instan... | You can't, since you don't have a concrete instance. You can need to create an actual instance that you can refer to:
template <class T>
class singleton {
...
private:
static T instance_;
public:
static T& instance;
};
template <class T> T singleton<T>::instance_;
template <class T> T& singleton<T>::instan... |
2,089,056 | 2,089,087 | Cyclic dependency between header files | I'm trying to implement a tree-like structure with two classes: Tree and Node. The problem is that from each class I want to call a function of the other class, so simple forward declarations are not enough.
Let's see an example:
Tree.h:
#ifndef TREE_20100118
#define TREE_20100118
#include <vector>
#include "Node.h"
... | In the headers, forward declare the member functions:
class Node
{
Tree * tree_;
int id_;
public:
Node(Tree * tree, int id);
~Node();
void hi();
};
In a separate .cpp file that includes all the required headers, define them:
#include "Tree.h"
#include "Node.h"
Node::Node(Tree * tree, int id) : tr... |
2,089,083 | 2,089,176 | Pure virtual function with implementation | My basic understanding is that there is no implementation for a pure virtual function, however, I was told there might be implementation for pure virtual function.
class A {
public:
virtual void f() = 0;
};
void A::f() {
cout<<"Test"<<endl;
}
Is code above OK?
What's the purpose to make it a pure virtual fun... | A pure virtual function must be implemented in a derived type that will be directly instantiated, however the base type can still define an implementation. A derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name (by calling A::f() in your example -... |
2,089,107 | 2,089,141 | Guides, Tutorials or Books about building MacOSX GUI apps with C++ in Xcode? | with GUI apps I mean not just a Unix command line application, but the whole .app bundle and a full Cocoa or Carbon application.
Thanks!
PS: I wasn't totally accurate with GUI application.
I meant an application with a window and a menu, as opposed to a Unix command line application.
Actually I got to a tutorial about ... | My recommendation is to work your way through the docs at http://developer.apple.com . There is a ton of useful material there from guides to sample code.
As for building GUI apps, I would recommend building the GUI parts with Cocoa (Objective-C). You can still implement your logic and rest of the app with C++ (C++... |
2,089,340 | 2,089,570 | Identifying a C# or C++ function start in a line count program | I have a program, written in C#, that when given a C++ or C# file, counts the lines in the file, counts how many are in comments and in designer-generated code blocks. I want to add the ability to count how many functions are in the file and how many lines are in those functions. I can't quite figure out how to determi... | Start by scanning scopes. You need to count open braces { and close braces } as you work your way through the file, so that you know which scope you are in. You also need to parse // and /* ... */ as you scan the file, so you can tell when something is in a comment rather than being real code. There's also #if, but you... |
2,089,362 | 2,089,393 | How to get TRUE hardware MAC address | I know, that this question was created many times, but it is stil open
The problem is following:
My application need to generate some UID for computer, it working on.
I need it to implement the genuine protection.
MAC address is a good candidate, because it is unique for each ethernet card.
Many articles uses either Ge... | The only means that Windows has to access the MAC address is asking the driver.
That's what the driver is for - to talk to the hardware so that Windows doesn't have to include code for every single device anyone might come up with ever.
If the driver is telling Windows that the MAC address is something, then that's wha... |
2,089,418 | 2,089,458 | Using operator+ without leaking memory? | So the code in question is this:
const String String::operator+ (const String& rhs)
{
String tmp;
tmp.Set(this->mString);
tmp.Append(rhs.mString);
return tmp;
}
This of course places the String on the stack and it gets removed and returns garbage.
And placing it on the heap would leak mem... | Your solution doesn't return garbage if you have a working copy constructor - the String object tmp is copied into the result object before it is destroyed at the end of the block.
You could do this better by replacing
String tmp;
tmp.Set(this->mString);
with
String tmp(*this);
(you need a correctly working copy cons... |
2,089,429 | 2,089,469 | Magic Numbers In Arrays? - C++ | I'm a fairly new programmer, and I apologize if this information is easily available out there, I just haven't been able to find it yet.
Here's my question:
Is is considered magic numbers when you use a literal number to access a specific element of an array?
For example:
arrayOfNumbers[6] // Is six a magic number in ... | That really depends on the context. If you have code like this:
arr[0] = "Long";
arr[1] = "sentence";
arr[2] = "as";
arr[3] = "array.";
...then 0..3 are not considered magic numbers. However, if you have:
int doStuff()
{
return my_global_array[6];
}
...then 6 is definitively a magic number.
|
2,089,514 | 2,089,642 | How to know and load all images in a specific folder? | I have an application (C++ Builder 6.0) that needs to know the total of images there are in a specific folder, and then I have to load them: in an ImageList or in a ComboBoxEx... or any other control...
How can I do that?
I know how to load an image in a control, or to save in a TList, or in an ImageList... but How to ... | I did something like this yesterday with C++ using the boost::filesystem library. However, if you are not using boost already, I would strongly recommend you just use the windows libraries instead. This was my code though in case you're interested:
#include <algorithm>
#include <boost/filesystem.hpp>
#include <set>
na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.