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-elision-friendly form that uses pass-by-value).
This idiom has the advantage of being transactional in the face of exceptions (assuming that the swap implementation does not throw). In contrast, the default compiler-generated copy-assignment operator recursively does copy-assignment on all base classes and data members, and that doesn't have the same exception-safety guarantees.
Meanwhile, implementing swap methods manually is tedious and error-prone:
To ensure that swap does not throw, it must be implemented for all non-POD members in the class and in base classes, in their non-POD members, etc.
If a maintainer adds a new data member to a class, the maintainer must remember to modify that class's swap method. Failing to do so can introduce subtle bugs. Also, since swap is an ordinary method, compilers (at least none I know of) don't emit warnings if the swap implementation is incomplete.
Wouldn't it be better if the compiler generated swap methods automatically? Then the implicit copy-assignment implementation could leverage it.
The obvious answer probably is: the copy-and-swap idiom didn't exist when C++ was developed, and doing this now might break existing code.
Still, maybe people could opt-in to letting the compiler generate swap using the same syntax that C++0x uses for controlling other implicit functions:
void swap() = default;
and then there could be rules:
If there is a compiler-generated swap method, an implicit copy-assignment operator can be implemented using copy-and-swap.
If there is no compiler-generated swap method, an implicit copy-assignment operator would be implemented as before (invoking copy-assigment on all base classes and on all members).
Does anyone know if such (crazy?) things have been suggested to the C++ standards committee, and if so, what opinions committee members had?
| 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 of a heavy-weight class is a waste of time, when we as programmers know all we really need to do is swap the internal pointers and whatnot.
However, rvalue-references relieve this completely. In C++0x, swap is implemented as:
template <typename T>
void swap(T& x, T& y)
{
T temp(std::move(x));
x = std::move(y);
y = std::move(temp);
}
This makes much more sense. Instead of copying data around, we are merely moving data around. This even allows non-copyable types, like streams, to be swapped. The draft of the C++0x standard states that in order for types to be swapped with std::swap, they must be rvalue constructable, and rvalue assignable (obviously).
This version of swap will essentially do what any custom written swap function would do. Consider a class we'd normally write swap for (such as this "dumb" vector):
struct dumb_vector
{
int* pi; // lots of allocated ints
// constructors, copy-constructors, move-constructors
// copy-assignment, move-assignment
};
Previously, swap would make a redundant copy of all our data, before discarding it later. Our custom swap function would just swap the pointer, but can be clumsy to use in some cases. In C++0x, moving achieves the same end result. Calling std::swap would generate:
dumb_vector temp(std::move(x));
x = std::move(y);
y = std::move(temp);
Which translates to:
dumb_vector temp;
temp.pi = x.pi; x.pi = 0; // temp(std::move(x));
x.pi = y.pi; y.pi = 0; // x = std::move(y);
y.pi = temp.pi; temp.pi = 0; // y = std::move(temp);
The compiler will of course get rid of redundant assignment's, leaving:
int* temp = x.pi;
x.pi = y.pi;
y.pi = temp;
Which is exactly what our custom swap would have made in the first place. So while prior to C++0x I would agree with your suggestion, custom swap's aren't really necessary anymore, with the introduction of rvalue-references. std::swap will work perfectly in any class that implements move functions.
In fact, I'd argue implementing a swap function should become bad practice. Any class that would need a swap function would also need rvalue functions. But in that case, there is simply no need for the clutter of a custom swap. Code size does increase (two ravlue functions versus one swap), but rvalue-references don't just apply for swapping, leaving us with a positive trade off. (Overall faster code, cleaner interface, slightly more code, no more swap ADL hassle.)
As for whether or not we can default rvalue functions, I don't know. I'll look it up later or maybe someone else can chime in, but that would sure be helpful. :)
Even so, it makes sense to allow default rvalue functions instead of swap. So in essence, as long as they allow = default rvalue functions, your request has already been made. :)
EDIT: I did a bit of searching, and the proposal for = default move was proposal n2583. According to this (which I don't know how to read very well), it was "moved back." It is listed under the section titled "Not ready for C++0x, but open to resubmit in future ". So looks like it won't be part of C++0x, but may be added later.
Somewhat disappointing. :(
EDIT 2: Looking around a bit more, I found this: Defining Move Special Member Functions which is much more recent, and does look like we can default move. Yay!
|
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() ";}
virtual void Foo() {cout<<"B::Foo() ";}
};
int main()
{
try{
B b;
throw b; //throw like this
}
catch(A ex){
ex.Foo();
}
catch(B ex){
ex.Foo();
}
catch(A * ex){
ex->Foo();
}
catch(B * ex){
ex->Foo();
}
return 0;
}
The output is
A() B() A() B(const B&) ~B() ~A() A(const A&) A::Foo() ~A() ~B() ~A()
#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() ";}
virtual void Foo() {cout<<"B::Foo() ";}
};
int main()
{
try{
throw B(); //throw it this way
}
catch(A ex){
ex.Foo();
}
catch(B ex){
ex.Foo();
}
catch(A * ex){
ex->Foo();
}
catch(B * ex){
ex->Foo();
}
return 0;
}
The output is
A() B() A(const A&) A::Foo() ~A() ~B() ~A()
Can anybody explain the difference to me?
The difference is
A() B(const B&) ~B() ~A()
Why is the copy constructor of class B invoked?
Thanks so much!
| 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.
int x=42;
int *px=&x;
int **ppx=&px;
f(ppx); // pt to pt to x
f(); // same as f(0)
UPDATE:
A practical application of this kind of double pointers is a memory allocation routine like:
bool alloc(T **mem, int count);
This function returns true/false depending on whether or not it worked and would update the pointer you pass in with the real memory address, like this:
T *mem;
verify(alloc(&mem, 100));
You pass in an uninitialized pointer and the function can overwrite it with a real value because you passed a pointer to the actual pointer. At the end, mem contains a pointer to valid memory.
Another application, more common but a lot less enlightening, is an array of arrays (so-called jagged arrays).
|
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.exe: Microsoft C++
exception: std::bad_alloc at memory
location 0x0012f8e4..
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include "DataTypes.h"
#include <sstream>
#include "EthernetLayer.h"
#include <pcap.h>
int* testPointer = new int[2];
delete[] testPointer;
EDIT:
Found out something useful.
The following code snippet is what is crashing the winpcap library.
EthernetStructPointers* testData;
testData = (EthernetStructPointers*)pkt_data;
EthernetStruct newData;
memcpy(newData.DEST_ADDRESS, testData->DEST_ADDRESS, 6);
These are the definitions of the structs.
struct EthernetStructPointers
{
u_char DEST_ADDRESS[6];
u_char SOURCE_ADDRESS[6];
u_char TYPE[2];
};
struct EthernetStruct
{
u_char DEST_ADDRESS[6];
u_char SOURCE_ADDRESS[6];
u_char TYPE[2];
u_char* dataPointer;
string DestAddress;
string SourceAddress;
string Type;
int length;
};
| 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't get it.
Thanks for any advices!
| 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 possible?
| 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 the information it is going to store. I have written a node class as follows -
template <class T> class Node
{
T data; //the object information
Node* next; //pointer to the next node element
public:
//Methods omitted for brevity
};
My linked list class is implemented in a seperate class, and needs to instantiate a node when adding new nodes to the end of the list. I have implemented this as follows -
#include <iostream>
#include "Node.h"
using namespace std;
template <class T> class CustomLinkedList
{
Node<T> *head, *tail;
public:
CustomLinkedList()
{
head = NULL;
tail = NULL;
}
~CustomLinkedList()
{
}
//Method adds info to the end of the list
void add(T info)
{
if(head == NULL) //if our list is currently empty
{
head = new Node<T>; //Create new node of type T
head->setData(info);
tail = head;
}
else //if not empty add to the end and move the tail
{
Node* temp = new Node<T>;
temp->setData(info);
temp->setNextNull();
tail->setNext(temp);
tail = tail->getNext();
}
}
//print method omitted
};
I have set up a driver/test class as follows -
#include "CustomLinkedList.h"
using namespace std;
int main()
{
CustomLinkedList<int> firstList;
firstList.add(32);
firstList.printlist();
//Pause the program until input is received
int i;
cin >> i;
return 0;
}
I get an error upon compilation however - error C2955: 'Node' : use of class template requires template argument list - which points me to the following line of code in my add method -
Node* temp = new Node<T>;
I do not understand why this has no information about the type, since it was passed to linked list when created in my driver class. What should I be doing to pass the type information to Node?
Should I create a private node struct instead of a seperate class, and combine the methods of both classes in one file? I'm not certain this would overcome the problem, but I think it might. I would rather have seperate classes if possible though.
Thanks, Andrew.
| 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 atacks / mac / encryption.
4) I don't want to add this extra layer of complexity to my programs.
5) I want to have the two programs just talk over a ssh channel (but both client & server are running on machines that are multi-user; so if I just open up ports, other uses may access them too).
Question:
What is the least intrusive way to get client&server to talk to each other over a secure channel?
Thanks!
| 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-space solutions, if you could set up both programs to run as a specified user, you could probably setup an SSL tunnel for them, but that highly depends on how you want connections to be established.
|
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, as well as ample tutorials and help on importing 3D models into one's C/C++ program for use with Open GL.
However I'm rather more interested in creating 2D vector-based models than 3D, as I'm perfectly happy to keep trying 2D games for a while yet. Does such a concept as 2D modelling exist? Are there tools for creating and exporting 2D models and libraries for importing 2D models specifically, or does one just create flat models in 3D software and then import those files (e.g. .3ds, .ms3d) and lay them flat onto the z-axis?
My only thought so far was perhaps using something like Inkscape for modelling, generate SVG files, and then use Cairo to import and render them. Will that work well, or do you have other recommendations?
Note I'm a bit of a newbie to modelling of any kind, so I may be asking a silly question...
| 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 for SVG for any format, so I'd stick with it. Technically things like Collada or X3D do support 2D graphics, but practically they have a lot of useless (for a 2D programmer) bloat.
|
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 has an uninitialized float with a random value. s2 is value initialized to 0.
However, if I add a string data member, the float in both instances is uninitialized.
struct Stan
{
std::string str;
float man;
};
However, the string in both instances is initialized. I tried adding other non-POD classes instead of a string, but the latter case only occurs if I add a string data member. I gather that adding a string still keeps it a POD class? If it wasn't a POD class, then it should have value initialized regardless of the parenthesis, right? Any ideas why floats(and other primitive data types for that matter) aren't initialized when I add a string data member?
| 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 value initialization for non-POD types such as the structure in your second example.
With the struct as in your second example what should happen is the float is not initialized by new Stan but is zero initialized in new Stan().
Types with a user declared default constructor are initialized by calling that constructor in all cases, this happens correctly.
See here and here.
|
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 closing it in the destructor. However, I realized that different functions called on the SavedDataHandler open the stream differently ( setting different flags, etc. ) so I decided not to go that route.
Instead I just have a static const std::string with the file name, with the public member functions handling the opening and closing of the file as they need to. Performance is not an issue.
Is this route a valid option? Since it has no data members, providing a constructor isn't even necessary. It's just a class that contains functions ( and one static constant ), with the functions operating on a resource rather than a data member.
| 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 you want simplicity, I'd just inherit fstream and in the constructor, pass the opening modes you want and invoke the super constructor accodingly.
|
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 allowed to say:
template <class T>
T* func(T Begin, T End)
T new_variable = Begin + 5;
return (*new_variable);
}
because the compiler won't understand what T* means. A solution I thought of is to take what I'm trying to return and make it a third argument:
template <class T>
void func(T Begin, T End, T* new_variable)
new_variable = Begin + 5;
return (*new_variable);
}
Will this work? Even if so, is there another way of doing what I'm trying to do? (Sorry if I haven't been clear enough.)
| 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<RandomAccessIterator>::value_type
value_type;
// use value_type now, when you want to save some temporary
// value into a local variable, for instance
value_type t = value_type();
for(; a != b; ++a) t += *a;
return t;
}
These work for all iterators, including pointers:
int main() {
int d[3] = { 1, 2, 3 };
assert(func(d, d + 3) == 6);
}
|
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 string as unicode.
|
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,
}
// example 2, different list of arguments
void a(int x) {
a (); // but the outside one,
}
// example 1, different names
void b () {
a (); // but the outside one,
}
};
Thanks in advance
| 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 rebuild or what configuration I use.
Thanks!
The statement:
LINK : C:\Users\Alex\Documents\Visual Studio 2008\Projects\Project_2\Debug\Project_2.exe not found or not built by the last incremental link; performing full link
The complete build log is here
| 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);
istream reader(&mb);
// use "reader"
I know of stringstream, but it doesn't seem to be able to work with binary data of given length.
Am I inventing my own wheel here?
EDIT
It must not copy the input data, just create something that will iterate over the data.
It must be portable - at least it should work both under gcc and MSVC.
| 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 Boost.Serialization) to be able to use convenient extraction >> operators to read chunks of binary data.
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_iarchive.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> buffer(dataPtr, sizeof(data));
boost::archive::binary_iarchive archive(buffer, boost::archive::no_header);
uint16_t word1, word2;
archive >> word1 >> word2;
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
With GCC 4.4.1 on AMD64, it outputs:
1234,5678
Boost.Serialization is very powerful and knows how to serialize all basic types, strings, and even STL containers. You can easily make your types serializable. See the documentation. Hidden somewhere in the Boost.Serialization sources is an example of a portable binary archive that knows how to perform the proper swapping for your machine's endianness. This might be useful to you as well.
If you don't need the fanciness of Boost.Serialization and are happy to read the binary data in an fread()-type fashion, you can use basic_array_source in a simpler way:
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream<Device> stream(dataPtr, sizeof(data));
uint16_t word1, word2;
stream.read((char*)&word1, sizeof(word1));
stream.read((char*)&word2, sizeof(word2));
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
I get the same output with this program.
|
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!, how would I do this please ??
| 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 say your o[i] array came out with 105, 95, 102, 98, 98, and 102
counts after doing your 600 trials.
chi2 = 52/100 + 52/100 + 22/100 + 22/100 + 22/100 + 22/100 = .660
You have five degrees of freedom (number of bins minus 1). So you're going to
have a declaration like
boost::math::chi_squared mydist(5);
to create the Boost object representing your chi-square distribution.
At this point you would use the cdf accessor function (cumulative distribution function) from the Boost library to look up the p-value corresponding to a chi-squared score of .660 with five degrees of freedom.
p = boost::math::cdf(mydist,.660);
You should get something close to 0.015, which would be interpreted as a (1 - .015) = 98.5% probability of observing a chi-squared score at least as extreme as 0.660, if one assumes the null hypothesis (that the die is fair) holds. So for this set of data, the null hypothesis cannot be rejected with any reasonable confidence level. (Disclaimer: untested code! But if I understand the Boost documentation correctly, this is how it should work.)
|
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 lot of singletons. Is it good programming practice to have lot of singletons?
What are the pros and cons for using singletons?
| 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 allow pointer arithmetric / buffer overflows?
| 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 the garbage collector to be switched out; so you can't rely on things being collected in any particular order.
I believe Python and Lua use reference counting.
|
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 memory, say 0xabcdabcd to 0xdeadbeef that I mmap to a particular file. Is there anyway to guarantee this? (I have to somehow make sure that other things aren't loaded into this particular region).
EDIT:
How do I make sure that nothing else takes this particular region in memory?
| 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)
Apart from this I also want to have some intelligence to make sure if a .cc file changed, all the tests that can validate the changes should be run.
I am evaluating PyUnit, cppunit with scons for this. Thought of running this question to make sure I am on right direction. Can you suggest any other test framework tools? And what other requirements should be considered to select right test framework?
| 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 studio project in my solution. It produces a clickable output when a test fails, and the tests are built and run each time I build the solution.
|
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 <QNetworkAccessManager>
#include <QNetworkReply>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void changeEvent(QEvent *e);
private:
Ui::MainWindow *ui;
QNetworkAccessManager networkManager;
private slots:
void on_requestButton_clicked();
void on_authenticationRequired(QNetworkReply* reply, QAuthenticator* auth);
void on_finished(QNetworkReply* reply);
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
void MainWindow::on_requestButton_clicked()
{
}
void MainWindow::on_authenticationRequired(QNetworkReply* reply, QAuthenticator* auth)
{
}
void MainWindow::on_finished(QNetworkReply* reply)
{
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow), networkManager(this)
{
ui->setupUi(this);
connect(networkManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(on_finished(QNetworkReply*)));
connect(networkManager,SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
this, SLOT(on_authenticationRequired(QNetworkReply*,QAuthenticator*)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
| 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
lrwxrwxrwx 1 root root 26 Jan 3 15:54 libmysqlclient_r.so.15 -> libmysqlclient_r.so.15.0.0
-rwxr-xr-x 1 root root 1518456 Sep 4 01:28 libmysqlclient_r.so.15.0.0
lrwxrwxrwx 1 root root 24 Jan 3 15:54 libmysqlclient.so -> libmysqlclient.so.15.0.0
lrwxrwxrwx 1 root root 24 Jan 3 15:54 libmysqlclient.so.15 -> libmysqlclient.so.15.0.0
-rwxr-xr-x 1 root root 1514000 Sep 4 01:28 libmysqlclient.so.15.0.0
...
And the directory seems to be properly registered for Linux linker:
una@localhost$ cat /etc/ld.so.conf.d/mysql-x86_64.conf
/usr/lib64/mysql
The only way I can link the application on this machine is by specifying the full path to the library file which is unacceptable in my case.
What could cause the problem here?
Thanks.
| -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 explicit in Java.
More information available on Wikipedia.
|
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 in an unusual way.
I know this is vague, but this is just what is states, no additional error messages. The code is from the website, i didn't modify it.
Anyone has any clues about this?
Now that i have this problem, i thought maybe i should extend the standard Qt text component. And try to make my own component like QScintilla.
How hard can it be, to write a component like QScintilla? (Without looking at its source)
Update: So i loaded the example project under Qt Creator. Set the default config to release mode and let it run. And it worked. (very weird). If i switch to debug mode Qt Creator says:
Invalid parameter passed to C runtime function.
If i go to the directory in the file system ( not in Qt Creator ) and run the program (release mode), i get the strange errors i told you about in the comment. While if i run it from Qt Creator it works.
| 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 example I have no problems.
So, first check you environment variables (My Computer, Right Click, Properties -> Advanced tab -> Environment Variables button). Check Path in System Variables section. I have %QTDIR%\bin (c:\Qt\qt-4.6.0\bin) in this variable.
Secondly I'm wondering about letter "d" in your message:
QtCored4.dll
If you made all steps described in documentation you will get release version of libraries and release version of example application linked against release version of Qt libraries. And not debug.
Finally may be QTextEdit & QSyntaxHighlighter is enough for your tasks. Check out Syntax Highlighter Example.
Response to comments.
It's some sort of well known problem (may be). So, as you can see you have 2 different folders with Qt libs
C:\Qt\2009.05\bin;C:\Qt\2009.05\qt\bin
in your path. Libraries in the first folder (...\bin) compiled with VS2008 and libraries in the second one (...\qt\bin) compiled with MinGW. The items in path variable are looked up when your application starts. Suddenly the folder with "wrong" libraries exists before the folder with correct item in your path variable. What you can do is to copy QtCore4.dll, QtGui4.dll and other libraries that you need to folder with your application executable. Hope this helps.
Some links about this problem:
@qtforum.org
@some blog post (in Russian =))
|
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 I can't make it works, and I'm not sure the dll would support a path like this.
Second, I found CreateFileMapping and GetMappedFileName. Can they be used to simulate a file in a fragment of another ? I'm not sure this is what this API does.
What I'm trying to do seems similar to boxedapp. Any ideas about how they do it ? I suppose it's something like API interception (Like Detour ), but that would be a lot of work. Is there another way to do it ?
Why ? I'm interested in this specific solution because I'd like to hide the data and for the benefit of distributing only one file but also for geeky reasons of making it works that way ;)
I agree that copying data to a temporary file would work and be a much easier solution.
| 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 course not an option if you want to support older systems or would like to be able to run this from a usb-stick or similar. Note that any streams present in a file will be lost if the file is sent as an attachment in mail or simply copied from a NTFS partition to a FAT32 partition.
I'd say that the most compatible way would be to write your data to an actual file, but you can of course do it one way on NTFS systems and another on FAT systems. I do recommend against it because of the added complexity. The appropriate way would be to distribute your files separately of course, but since you've indicated that you don't want this, you should in that case write it to a temporary file and give the dll the path to that file. Make sure you write the temporary file to the users' temp directory (you can find the path using GetTempPath in C/C++).
Your other option would be to write a filesystem filter driver, but that is a road that I strongly advise against. That sort of defeats the purpose of using a single file as well...
Also, in case you want only a single file for distribution, how about using a zip file or an installer?
|
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 namespace user, but there is no access control in namespaces.
| 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 (not inline in the header).
Put them into a detail namespace
Preferably, you put them in a different header, and include them. So the code of them won't disturb your interface header. This is how boost does it, too:
#include "detail/destroy.hpp"
namespace orbit {
void destroy() {
detail::destroy_planets();
detail::destroy_stars();
}
}
|
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 following two ways:
Method 1:
template <typename ValueType>
void DoGetValue(Array<ValueType>& arr)
{
ValueType value = arr.GetValue();
...
}
Method 2:
template <typename ArrayType>
void DoGetValue(ArrayType& arr)
{
typename ArrayType::ValueType value = arr.GetValue();
...
}
There is almost no difference between the two methods. Even calling both functions will look exactly the same:
int main()
{
Array<int> arr;
DoGetValue(arr);
}
Now, which of the two is the best? I can think of some cons and pros:
Method 1 pros:
The parameter is a real class not a template, so it is easier for the user to understand the interface - it is very explicit that the parameter has to be Array. In method 2 you can guess it only from the name. We use ValueType in the function so it is more clear this way than when it is hidden inside Array and must be accessed using the scope operator.
In addition the typename keyword might be confusing for many non template savvy programmers.
Method 2 pros:
This function is more "true" to its purpose. When I think if it, I don't really need the class to be Array. What I really need is a class that has a method GetValue and a type ValueType. That's all. That is, this method is more generic.
This method is also less dependent on the changes in Array class. What if the template parameters of Array are changed? Why should it affect DoGetValue? It doesn't really care how Array is defined.
Evey time I have this situation I'm not sure what to choose. What is your choice?
| 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 more generic.
But no use obsessing, since it's easy enough to convert between them.
|
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 calculation loop that software using the library is supposed to call:
while(true)
{
//do math here
callback(percent_complete);
}
In the callback, the client calls Sleep(x) to slow down the thread.
Originally, the clientside code was a fixed Sleep(100) call, but this led to bad unreliable performance because some machines finish the math faster than others, but the sleep is the same on all machines. So now the client checks the system time, and if more than 1 second has passed (which == several iterations), it will sleep for half a second.
Is this an acceptable way of slowing down a thread? Should I be using a semaphore/mutex instead of Sleep() in order to maximize performance? Is sleeping x milliseconds for each 1 second of processing work fine or is there something wrong that I'm not noticing?
The reason I ask is that the machine still gets heavily bogged down even though taskman shows the process taking up ~10% of the CPU. I've already explored hard disk and memory contention to no avail, so now I'm wondering if the way I'm slowing down the thread is causing this problem.
Thanks!
| 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 yourself.
It has a configuration option ("limit CPU use to X%"). The way I'd expect to implement that is to use platform-dependent APIs like clock() or GetSystemTimes(), and compare processor time against elapsed wall clock time. Do a bit of real work, check whether you're over or under par, and if you're over par sleep for a while to get back under.
The BOINC client plays nicely with priorities, and doesn't cause any performance issues for other apps even at 100% max CPU. The reason I use the throttle it is that otherwise, the client runs the CPU flat-out all the time, and drives up the fan speed and noise. So I run it at the level where the fan stays quiet. With better cooling maybe I wouldn't need it :-)
|
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 internal means that it is visible only within the defining assembly and protected internal means protected or internal (NOT protected and internal).
|
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 frame and returning only the current frame. How can I do this?
| 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 the width of the texture, giving you a number between... 0 and 1! This is your offset. To get a frame from your strip, simply do:
float step_size_x = (float)(width) / (float)(texture_width);
float step_size_y = (float)(height) / (float)(texture_height);
float begin_u = step_size_x * step_current_x;
float begin_v = step_size_y * step_current_y;
float end_u = begin_x + step_size_x; // basically, if you want sprite 0, you go from 0 to the x of sprite 1
float end_v = begin_y + step_size_y;
And that's it! Now if you want to copy the portion of the texture, that would be the following in OpenGL:
glBindTexture(GL_TEXTURE_2D, texture_id);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(begin_u, begin_v); glVertex3f(x - (width / 2), y - (height / 2), 0);
glTexCoord2f(end_u, begin_v); glVertex3f(x + (width / 2), y - (height / 2), 0);
glTexCoord2f(begin_u, end_u); glVertex3f(x - (width / 2), y + (height / 2), 0);
glTexCoord2f(end_u, end_u); glVertex3f(x + (width / 2), y + (height / 2), 0);
glEnd();
Now that I've given you a complete code sample, will you please stop bothering me about your game? :P
|
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 each element in the destructor? In other words, I don't have to worry about memory management as long as I use these? Or am I totally misunderstanding this? It sounds too good to be true.
| 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 reference count of '1'.
Boost provides weak pointers to get around this, which allows you to store a pointer to a shared object without incrementing its reference count. Weak pointers provide a layer of safety in that attempting to dereference the pointer after the shared pointer has been released will raise an exception rather than crashing the program.
Shared pointers are also quite expensive (at least compared to a raw pointer) in performance terms - but it's better to use them and then remove them once a profiler identifies a bottleneck rather than not use them everywhere.
Other than that, yes, they are very useful for managing dynamically allocated objects.
Edit: Another gotcha (that's mentioned on the boost pages) is to avoid "temporary" shared_pointers:
func(A(), boost::shared_ptr<B>(new B));
because the compiler is allowed to optimise this as
tmp1 = new B;
tmp2 = A();
tmp3 = boost::shared_ptr<B>(tmp1)
func(tmp2,tmp3)
which might look OK on first glance, but if A() happens to throw an exception then B has been allocated, but the shared_ptr hasn't gotten a hold of it yet, so the pointer never gets released.
|
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 file. This has got all proper includes.
void some_method()
{
const char* filename = "sample.xml";
pattern_token_map* map = load_from_file( filename ); // Linker complains about this.
}
I am getting a linker error saying that undefined reference to load_from_file. I am not able to see what is going wrong here.
Any help would be appreciated.
Compiler : G++
OS : Ubuntu 9.10
Edit
Here is the linker command used.
g++ -L/home/nkn/silc-project/third_party/UnitTest++ -o tests.out src/phonetic_kit/pattern_token_map.o tests/pattern_token_map_tests.o tests/main.o -lUnitTest++
Error is from pattern_token_map_tests.o and the function is available in pattern_token_map.o. So I guess the order of linking is not making the problem. (I have removed some files from the command to simplify it)
| 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) {
// Implementation goes here
}
Then you'd be defining a new function rather than silc::load_from_file.
Avoid using directives ("using namespace ...;") outside of function scope, as a general guideline:
using namespace silc; // outside function scope: avoid
silc::pattern_token_map* // qualify return type
random_function(silc::pattern_token_map* p) { // and parameters
using namespace silc; // inside function scope: fine
pattern_token_map* p2 = 0; // don't have to qualify inside the function
// if you want to use the using directive
silc::pattern_token_map* p3 = 0; // but you can always do this
return 0;
}
|
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* a = new int[10];
calls operator new[] in newaop.cpp, which in turn calls my version of operator new. So it seems they are globally overloaded but for some reason not the array versions. Is there something I'm missing?
EDIT: My implementation of the operators are in a separate project which is compiled into a library and linked to statically. In retrospect, this might have been useful to include in the original post, as it probably has something to do with this. Although I still can't figure out why only the array versions are affected.
| 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, they are already globally defined, I only specified the implementation of the operators in a .cpp in my library (this was the wrong step). The code obviously only included the header files from the library and didn't ahve visibility to the implementations. Moreover, Visual Studio seems to have linked newaop.cpp and delete2.cpp into my application. These two files contain implementations for operator new[] and operator delete[] (bot not for regular new/delete!). This is most likely the reason why the compiler saw these two implementations and chose them over mine, which resided in a .cpp file in a library.
The solution to this was to move the implementation of my overloaded operators to a header file in the library which is directly included from my code.
|
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 BAR
}
}
However, I want to make these magic constants private - any ideas how? My first thought was to use an anonymous namespace thus:
// Foo.h
namespace Foo
{
namespace
{
// 'private' constants here
const int BAR = 1234;
}
inline void someFunc()
{
// Do something with BAR
}
}
However, this doesn't work and Foo::BAR is available to any cpp file that includes Foo.h? Is there a way to do this without creating an implementation cpp file?
| 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::magic
}
|
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()
{
Child child;
printf("ble: %i\n", ((Base*)&child.First)->Virtual());
printf("ble: %i\n", ((Base*)&child.Second)->Virtual());
system("PAUSE");
return 0;
}
I'd expect this to give this output:
ble: 1
ble: 2
and it does so, when compiled under GCC (3.4.5 I believe).
Compiling and running this under Visual Studio 2008 however, gives this:
ble: 2
ble: 2
What is interesting, is that if I give the Base-derived structs names (struct s1 : public Base), it works correctly.
Which behavior, if any, is correct? Is VS just being prissy, or is it adhering to the standard? Am I missing something vital here?
| 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 different name for the vtable surely is part of the bug.
There are several bugs reported at connection.microsoft.com that are related to anonymous types, none of which ever made it to "must-fix" status. Not the one you found though, afaict. Maybe the workaround is just too simple.
|
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 constructor
Now I have not written the copy constructor for both the classes, off course the default copy constructors will be called. The Person class’s default copy constructor will first call the base class’s copy constructor.
Now the problem is suppose I write the copy constructor for the base class only, what happens is, the default copy constructor of the derived class will call my written copy constructor.
Now suppose I write the copy constructor for both the classes . now the copy constructor of the derived class (i.e Teacher) will call the default constructor of the base class but not the copy constructor why?
Is only default copy constructor of the derived class can call the copy constructor of the base class automatically?
| 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 relevant and hopefully this will help the OP.
All user defined constructors call their base's default constructor by default (unless they explicitly call a different constructor), it doesn't matter if the base's default constructor is user defined or compiler generated.
When a copy constructor is generated by the compiler it will call the base class's copy constructor.
Compiler defined constructors are not special, they can be called explicitly:
class Base {
int num_
public:
Base(int n) : num_(n) { }
// copy constructor defined by compiler
};
class Derived : public Base {
float flt_;
public:
Derived(float f, int n) : Base(n), flt_(f) { }
// Copy constructor
Derived(const Derived& other)
: Base(other) // OK to explicitly call compiler generated copy constructor
, flt_(other.flt_)
{
}
};
For more details see this Wikipedia article.
|
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 output file to test if the read happened correctly. As I did that, I see ofstream writing my "filename" string(used to ask the user for the name of the file to open) into the file in random places, and there is no mention of it in the code.
Here is my code:
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
char filename[256] = "";
char currentLine[256] = "";
cout << "Please enter the name of the input file: " << endl;
cin.getline(filename,256);
vector <string> storage;//disregard for now
ifstream infile;
infile.open(filename);
string outputFile = ".output";
outputFile = filename + outputFile;
ofstream outfile(outputFile.c_str());
string line = "";
while(!infile.eof())
{
infile.read(currentLine, 256);
line = currentLine;
storage.push_back(line); //disregard for now
outfile << line; //testing to see if it read properly
}
}
Here is the input text:
1034 BLUE ELECTRIC FROBULATOR 5 1026
1039 GREEN ELECTRIC FROBULATOR 10 1026
1054 BLUE ELECTRIC DEFROBULATOR (MAGNESIUM COATING) 7 2000
1069 JELLO HAMMER V2 111 12
1050 BELL SILENCER 0 50
1090 SNAKE OIL 34 150
1070 MECHAGODZILLA COSTUME (PINK) 1 5000
1090 REFROBULATOR 3 9999
1091 REFROBULATOR REFILL (PACK OF 5) 1 4999
1092 REFROBULATOR REFILL (PACK OF 10) 1 8999
2003 FROBULATION TODAY (MAR) 4 5
2004 FROBULATION TODAY (APR) 9 5
2005 FROBULATION TODAY (MAY) 2 5
3102 FROBULATOR CUSTOMER WARRANTY 2YR 3 199
3103 FROBULATOR CUSTOMER WARRANTY 3YR 3 299
and here is the output text:
1034 BLUE ELECTRIC FROBULATOR 5 1026
1039 GREEN ELECTRIC FROBULATOR 10 1026
1054 BLUE ELECTRIC DEFROBULATOR (MAGNESIUM COATING) 7 2000
1069 JELLO HAMMER V2 111 12
1050 BELL SILENCER 0 50
1090 SNAKE OIL 34 150
1070 MECHAGODZILLA COSTUME (PINK) 1 5000
1090 Rinvoice.txtEFROBULATOR 3 9999
1091 REFROBULATOR REFILL (PACK OF 5) 1 4999
1092 REFROBULATOR REFILL (PACK OF 10) 1 8999
2003 FROBULATION TODAY (MAR) 4 5
2004 FROBULATION TODAY (APR) 9 5
2005 FROBULATION TODAY (MAY) 2 5
3102 FROBULATOR CUSTOMER WARRANTY 2YR 3 199
3103 invoice.txtFROBULATOR CUSTOMER WARRANTY 3YR 3 299
FILL (PACK OF 5) 1 4999
1092 REFROBULATOR REFILL (PACK OF 10) 1 8999
2003 FROBULATION TODAY (MAR) 4 5
2004 FROBULATION TODAY (APR) 9 5
2005 FROBULATION TODAY (MAY) 2 5
3102 FROBULATOR CUSTOMER WARRANTY 2YR 3 199
3103 invoice.txt
As you can see the "invoice.txt" shouldn't be in the output. Now what am I missing?
| 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 where the memory bloat is?
P.S. One could argue that "prematurely" optimizing for space in embedded systems isn't all that evil, because you leave yourself more room for data storage and feature creep. It also allows you to cut hardware production costs because your code can run on smaller ROM/RAM.
P.P.S. References to articles and books are welcome too!
P.P.P.S. These questions are closely related: 404615, 1561629
| 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 instead. :)
|
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 array?
| 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 constructor operator to block copying of the object, see later
// C++03:
YourClass(const YourClass &); // no definition
// C++11:
YourClass(const YourClass&) = delete;
public:
YourClass(size_t Size) : array(new int[Size]), size(Size)
{
// do extra init stuff here
};
~YourClass()
{
delete [] array;
}
};
To make this work easier, you may consider to use a smart pointer (for example, a boost::scoped_array in C++03, or plain std::unique_ptr in C++11), that you may initialize using the initializer list before the constructor or simply in the constructor.
class YourClass
{
private:
boost::scoped_array<int> array; // or in C++11 std::unique_ptr<int[]> array;
size_t size;
public:
YourClass(size_t Size) : array(new int[Size]), size(Size)
{
// do extra init stuff here
}
// No need for a destructor, the scoped_array does the magic
};
Both these solutions produce noncopyable objects (you didn't specify if they had to be copyable and their copy semantic); if the class don't have to be copied (which happens most of times), these both are ok, and the compiler will generate an error if you try to copy/assign one class to another, in the first case because the default copy constructor has been overloaded with a private one (or plain deleted in C++11), in the second case because boost::scoped_array and std::unique_ptr are noncopyable.
If, instead, you want to have copyable objects, then you must decide if you want to create a copy that shares the array (so, just a pointer copy) or if you want to create a new, separate array for the other object.
In the first case, you must be very careful before freeing the allocated memory, since other objects may be using it; a reference-counter is the most common solution. You can be helped in this by boost::shared_array (or std::shared_ptr in C++11), which does all the tracking work automatically for you.
If instead you want to do a "deep copy", you'll have to allocate the new memory and copy all the objects of the source array to the target array. This is not completely trivial to do correctly, and is usually accomplished through the "copy and swap idiom".
Still, the simplest solution is to use a std::vector as a private member: it would handle all the allocation/deallocation stuff by itself, constructing/destroying itself correctly when the object of your class is constructed/destructed. Moreover, it implements the deep-copy semantic out of the box. If you need to make your callers access the vector read-only, then, you could write a getter that returns a const_iterator or a const reference to the vector object.
|
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 some the odder machines out there.
|
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 after i build it, rebuild, clean, etc.
it's a win 32 console project. the release folder contains the .obj files, the manifest, the build log, idb, pch and pdb files (one of each)
| 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 output (EXE) is created in a different folder than the default one?
|
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 local user's hard drive (preferences, save game files, etc).
Access to such resources should be as simple as making a call like
std::auto_ptr<std::istream> defaultConfigIStream(
fslib.inputStream("self://defaultConfig.ini"));
std::auto_ptr<std::ostream> defaultConfigOStream(
fslib.outputStream("localappdata://config.ini"));
// Copies default configuration to local user's appdata folder
defaultConfigIStream >> defaultConfigOStream;
The actual way of doing things is actually different, with another abstraction layer used for background loading, but that's not important here.
What I want to know is how can I return that auto_ptr<> (or unique_ptr<>, you choose) considering that the std::streambuf<> associated with the std::[i/o]stream<> is not deleted by it when it's destroyed.
I am considering std::[i/o]stream<> doesn't assume ownership over the streambuf passed to it upon construction as the constructor doesn't present transfer of ownership semantics and Apache's STDCXX reference doesn't mention transer of ownership (nor do any of the stdlib references I've found on the internet).
What alternatives do I have? I might as well return a shared pointer and keep watching it until the FSlib manager keep a unique copy of the shared pointer, in which case it would destroy its unique copy as well as the streambuf. That's practical, considering the library's organizational model, but this isn't very elegant nor efficient for that matter.
I've tried taking a look at Boost.Iostreams, but it seems things are even worse with it for me, as streams themselves have their Device types strongly attached to their type (the Device for a stream has to be defined in its template parameter). This problem seems to make the use of Boost.Iostreams unfeasible for my library, as it needs to abstract away the concrete "source/sink" implementation of the streams so that streams can be used seamlessly to open a file located inside the executable itself, inside a file from the system's file system or inside an archive-type file, for example.
I could write a container class that handles these issues, but I'd rather do it more cleanly (i.e. just return the stream already; that's all it should need! ;).
Suggestions?
| 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()))
{
}
~config_istream() { delete rdbuf(); }
};
Have a look on how the fstream classes are implemented, they deal with a similar problem (filebuf has to be deleted together with fstream)
|
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 the violin.";
This should produce a sentence that reads
Frank and Joe sat down with Nancy to play cards, while Sherlock played the violin.
My question is: What is the optimal way to accomplish this? I am concerned that constantly using the + operator is ineffecient. Is there a better way?
| 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 << " played the violin.";
std::string sentence = stream.str();
|
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 value (or vice versa)?
|
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, arg2 ); // to save data
gameSave.DeleteSave(); // Delete the save
...
2) Create a namespace of functions
namespace SavedDataHandler {
SaveData( ... ) { ... }
DeleteSave( ... ) { ... }
...
}
that a user would call like
SavedDataHandler::SaveData( arg1, arg 2 );
SavedDataHandler::DeleteSave();
What would be preferred?
P.S. I thought about this when I was thinking about Scott Meyer's recommendation to prefer non-member non-friend functions to member functions. I've run into decisions where I have a function (usually some private member function to help the class do stuff), that could easily be made into a non-member since it doesn't operate on class privates.
However, the function is only used by that one class. Of course, the program might evolve to a point where another class may need it, but I find it hard to find a place for these non-member functions. It's easy when you have a lot of functions with a general purpose, but I find single non-member functions hard to organize into a specific place, and find that leaving it as a member keeps things clean. Any tips regarding this issue?
| 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 internal state, make it a member function of course.
But opinions differ and in the end probably the guide-lines of your employer are the final ones.
Edit:
... Of course its not that simple, but as you mentioned Scott Meyers already covered the details.
As for the organizational problem:
If you put helper functions in anonymous namespaces, they are already mostly decoupled from the class - if you then later decide to reuse them, it shouldn't be too hard to pull them out in a common namespace.
At this point you should also have a better view on the organization that fits, which can sometimes be hard in advance.
|
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 order, the file is simply the coordinates 3 vertices of each triangle floating in 3D space plus a normal vector to the triangle (the normal should be disregarded as it is not always done properly). There is nothing that links each triangle to one another, it is assumed that the object is closed.
One simple approach would be to divide a volume (in this case, a box) into millions of elements and determine if each element is inside the object defined in the STL file or not, then sum up the moments and calculate the centre of mass. This would work but its far from elegant and extremely slow.
Another method would be to convert the boundary representation into a number of packed tetrahedron solids. Form that I could calculate the centre of mass of each tetrahedron, its volume, and resulting moment and thus calculate the overall centre of mass from the sum of all tetrahedrons. The problem with this is that I don't know how to convert a surface representation of triangles into a volume representation of tetrahedrons (I'm assuming its a fairly non trivial task).
Dose anyone know of any methods or can think up of any methods that I could try? Or maybe even any reference material that talks about this?
For more information about STL files (only the first 2 sections are important, everything else is useless): http://en.wikipedia.org/wiki/STL_%28file_format%29
| 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 overall centroid.
We calculate volumes using the determinate method shown here (equation 32): http://mathworld.wolfram.com/Tetrahedron.html
The centroids of each of the tetrahedrons is simply the average of the 4 points.
The trick here is that due to the way the STL file is created, the triangles have a normal that point outwards from the part surface, following the right hand rule of the 3 verticies used to create the triangle. we can use this to our advantage by allowing us to have a consistent convention in which to determine if a volume of the tetrahedron should be added or subtracted from our net part (this is because the reference point we chose may not necessarily be inside the part and the overall part is not necessarily convex, it is, however a closed object).
Using the determine method to calculate the volume, the first three coordinate points will represent the three points of our triangle. The fourth point would be our common origin. If the normal created by the triangle (following the right hand rule going from point 1, 2, 3) points towards our common reference point, that volume will be calculated as not part of our overall solid, or negative volume (by pointing towards, i mean the vector created by the triangle's normal is pointing loosely towards the same side as a normal plane created by the vector from our reference point to the centroid of the tetrahedron). If the vector is pointing away from the reference point, it is then positive volume or inside the part. If it is normal, then the volume goes to zero as the triangle is in the same plane as the reference point.
We don't need to worry about actually keeping track of any of this as if we are consistent with our inputs (as in the triangles follow the right hand rule with normal facing outwards from the part) the determine will give us the correct sign.
Anyways, heres the code (its even more simple than the explanation).
class data // 3 vertices of each triangle
{
public:
float x1,y1,z1;
float x2,y2,z2;
float x3,y3,z3;
};
int main ()
{
int numTriangles; // pull in the STL file and determine number of triangles
data * triangles = new triangles [numTriangles];
// fill the triangles array with the data in the STL file
double totalVolume = 0, currentVolume;
double xCenter = 0, yCenter = 0, zCenter = 0;
for (int i = 0; i < numTriangles; i++)
{
totalVolume += currentVolume = (triangles[i].x1*triangles[i].y2*triangles[i].z3 - triangles[i].x1*triangles[i].y3*triangles[i].z2 - triangles[i].x2*triangles[i].y1*triangles[i].z3 + triangles[i].x2*triangles[i].y3*triangles[i].z1 + triangles[i].x3*triangles[i].y1*triangles[i].z2 - triangles[i].x3*triangles[i].y2*triangles[i].z1) / 6;
xCenter += ((triangles[i].x1 + triangles[i].x2 + triangles[i].x3) / 4) * currentVolume;
yCenter += ((triangles[i].y1 + triangles[i].y2 + triangles[i].y3) / 4) * currentVolume;
zCenter += ((triangles[i].z1 + triangles[i].z2 + triangles[i].z3) / 4) * currentVolume;
}
cout << endl << "Total Volume = " << totalVolume << endl;
cout << endl << "X center = " << xCenter/totalVolume << endl;
cout << endl << "Y center = " << yCenter/totalVolume << endl;
cout << endl << "Z center = " << zCenter/totalVolume << endl;
}
Extremely fast for calculating centres of mass for STL files.
|
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 most likely need to get my code running on a linux box. Minor changes may be unavoidable though...
I've found the header files and can include them but I'm having trouble with the linking, compiling, and executing within Eclipse.
Thanks.
| 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 main()
{
hash_map<const char*, int, hash<const char*>, eqstr> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
cout << "september -> " << months["september"] << endl;
cout << "april -> " << months["april"] << endl;
cout << "june -> " << months["june"] << endl;
cout << "november -> " << months["november"] << endl;
}
on gcc4.2 I am getting the error
listcheck.cc: In function 'int main()':
listcheck.cc:22: error: 'hash_map' was not declared in this scope
listcheck.cc:22: error: expected primary-expression before 'const'
listcheck.cc:22: error: expected `;' before 'const'
listcheck.cc:24: error: 'months' was not declared in this scope
while the same code compile with 3.4.
| 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 memory (that's mmaped in P1 and P2 at the same address), then P1 and P2 can both access the objects in R as C++ objects (no race conditions since all is read only).
Anyone familiar how to do this / gotchas?
| 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 inside the shared memory, and custom allocators that allocate inside the shared memory for creating std::vector and std::map objects.
|
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.
Are there any ways to express in C++ that I want the ifstream to only read in text that is an integer? I'm reluctant to use regular expressions if it turns out that there is a much simpler way to accomplish this.
| 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 conflates the discussion of a fluent interface with an example of a simple Glut app. Can someone provide a SUCCINCT C++ example of a class that illustrates a fluent interface (how does such an influence differ from an ordinary C++ interface for example)?
| 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 window params
app.setWindowPosition(200, 200);
app.setTitle("My OpenGL/GLUT App");
app.create();
}
After:
int main(int argc, char **argv) {
FluentGlutApp app(argc, argv);
app.withDoubleBuffer().withRGBA().withAlpha().withDepth()
.at(200, 200).across(500, 500)
.named("My OpenGL/GLUT App");
app.create();
}
|
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 failure or crash.
B. Save periodically, maybe after every major section has been finished
meaning i can narrow downs where the errors are.
Any other suggestions??
I don't want to be opening and saving all day with the large volume of text
i need to record, but i don't want to lose my granularity of the information.
I am writing in C++, sorry for not mentioning it prior.
| 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 only for functions but also for attributes). For example:
class C{
public:
int a;
void g(){ cout << "C:g()\n"; }
C() : a(0){}
};
class D : public C{
private:
using C::a;
using C::g;
public:
D() { a = 1; }
};
int main(void){
D d;
cout << d.a << endl; //error: a is inaccessible
C *cp = &d;
cout << cp->a << endl; //works
d.g(); //error: g is inaccessible
cp->g(); //works
return 0;
}
I think this limitation of access in the derived class is actually of no use, because you can always access g() and a from a pointer to the base class. So should't there be at least some kind of compiler warning? Or wouldn't it been even better to forbid such limitation of access by a derived class? The using declaration is not the only possibility to add constraints to access. It could also be done via overriding a base class' function an placing it in a section with more access constraints.
Are there some reasonable examples where it is indeed nessecary to limit access in such a way? If not I don't see why it should be allowed.
And another thing: at least with g++ the same code compiles well without the word 'using'. That means for the example above: it's possible to write C::a; and C::g; instead of using C::a; using C::g; Is the first only a shortcut for the latter or are there some subtle differences?
//EDIT:
so from the discussion and answers below my conclusion would be:
- it's allowed to limit access constraints in derived classes with public inheritance
- there are useful examples where it could be used
- it's use might cause problem in combination with templates (e.g. a derived class could not be a valid parameter for some template class/function any more although it's base is)
- a cleaner language design should not allow such use
- compiler could at least issue some kind of warning
| 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 called an access declaration. The effect of an access declaration qualified-id; is defined to be equivalent to the declaration usingqualified-id; [Footnote: Access declarations are deprecated; member using-declarations (7.3.3) provide a better means of doing the same things. In earlier versions of the C++ language, access declarations were more limited; they were generalized and made equivalent to using-declarations - end footnote]
I would say that most often it's not good to change public members to private or protected members in the derived class, because this will violate the substitution principle: You know a base class has some functions, and if you cast to a derived class then you expect those functions to be callable too, because the derived class is-a base. And like you already mentioned, this invariant is already enforced anyway by the language allowing to convert (which working implicitly!) to a base class reference, or qualifying the function name, and then calling the (then public) function.
If you want to forbid someone calling a set of functions of the base, then i think this hints that containment (or in rare cases, private inheritance) is a better idea.
|
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 time I checked it I found that the quality of the code was poor (of course this is subjective and argumentative).
You can have a look at Juce which has a dual license: GPL and commercial.
Qt (LGPL) has stylesheets to style the widgets, but it still let the operating system draw the windows decorations unless you instruct it to draw frameless windows and draw the decorations by yourself.
However, think twice before going the skinned application route. A typical example is Songbird (written in XUL) which used frameless windows and painted its own titlebar and windows buttons. Then they back-pedaled and switch back to system windows decorations after many users complained.
|
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 an easy way of getting this directly from the PLUID value.
Thanks
| 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_AND_ATTRIBUTES that you've located and check to see if the Attributes contain the required flag (SE_PRIVILEGE_ENABLED in your case).
Be aware that when you are checking for an enabled privilege you should also check that SE_PRIVILEGE_REMOVED is NOT set in the Attributes that you are checking; a privilege that has both SE_PRIVILEGE_REMOVED and SE_PRIVILEGE_ENABLED has been removed and is NOT enabled...
|
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 = ReadFromFuncThatMayBeProblem();
obj.member2 = ReadFromFuncThatMayBeProblem(); // Sometimes allocation error (2)
/* more members */
}
...
void operator =( const MyType& source )
{
if( this != &source )
{
member1 = source.member1; // std::wstring
member2 = source.member2; // Usually (1) happen on the second member. // std::wstring
/* more members */
}
}
Either (1) or (2) occur.
Now, if I simply continue on regardless of the error (with the debugger), the value is indeed entered in the map.
I don't know if ReadFromFuncThatMayBeProblem() is the culprit but it's a fairly complex function that I cannot devulge here.
Also, this is code that has worked (or at least appeared to work) before other sections of the application was ported to use OpenSSL. I don't know if that may have had any effect here, though.
So, what can I do to track down this allocation error, since I'm presuming that the above code is not in fact the problem?
Edit: More info:
There is no dtor for MyType.
However, MyType has a member of type SecondType that has a void* member. This is being deleted and null'd in that type's destructor. The constructor uses m_pData = new std::wstring( ( (std::wstring )source.m_pData) ); for strings. (And similar for other data types). Could that be an issue? (delete static_cast< std::wstring* >( m_pData );)
The other member types of MyType are std::wstring, unsigned long, bool, enum, structs (timeb among them) and SecondType.
| 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 another (changing size dynamically). While doing this, we use the input of the buffer and the size we should expand with. The size calculation was using modulo to calculate the factor of the re-size. This caused the buffer to either be too large or too small to fit the following operations.
Two days of debugging to change a '%' to a '/'.
Thanks for all support, though.
|
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. Is there an easy way to do this?
| 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, Chapter 40. Demangling.
|
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(dllexport) SOMECLASS
{
public:
SOMETYPE func(param A,char b[tot]);
};
}
tobeexported.cpp:
#include "stdafx.h"
#include "tobeexported.h"
...
using namespace SOMENAMESPACE;
SOMETYPE SOMECLASS:: func(param A,char b[tot])
{
...some stuff inside...
}
The dll is righly created and the code is already CLR-managed(looked with a disassembling software(reflector)) and contains the exported functions
then I "Add the Reference" in my c# application and the dll is found, but when
I open it with the object browser it is completely empty, neither class, nor object has been exported and ready to be used
can you help me please?
thanks
best regards
| 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]);
};
}
After successful compilation and referencing in the other project, the class should be visible. Exporting native C++ is not really portable, each compiler produces different results and is tedious to bind from within C#...
EDIT: added public access modifier to ref class...
|
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.8
Apparently the ABI changed in those last two 0.0.1's, as trying to run a program results in
/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.9' not found
I tried explicitly installing an older version of gcc but that didn't help.
Upgrading the target machines is out of my control, so not an option. What's the best way to get my builds to work on machines with an older libstdc++?
I searched in apt-cache for older libstdc++ versions to install, but apparently no older versions of 6 are available?
| 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, so you need a gcc-4.1.x.
In short, that's why there's only one libstdc++.so.6.0.x on your system, you only need the latest.
As for setting up your build system to use only a specific version of the compiler: make sure the standard g++ can't be used (rename the link, remove the package providing it, take it out of PATH), and start digging. Worked for me.
|
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 NSLog and the output is 2.99.
I needed to fix it fast so I used following method:
float n = 2.99499989f;
float round = (float)Math.Round(n, 2);
MessageBox.Show("round = " + round.ToString(CultureInfo.InvariantCulture));
This code shows 2.99, but computes round in double precision. I can't find Math.RoundF.
| (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 in the opposite direction as the float's value was rounded.
Others re-enforce this idea about printf:
C automatically converts the float values to double (it is a standard conversion made when you call a function that takes variable arguments, such as int printf...
https://stackoverflow.com/a/7480244/119418
https://stackoverflow.com/a/6395747/119418
I believe the reason the float rounds up is because 2.995F doesn't convert perfectly into binary and is = 2.99499989F, and we'd expect 2.995 to round up.
I believe the reason the float copied into a double rounds down is because 2.995 as a double <> 2.99499989 as a double, and 2.995 actual double value is greater than that value (more precision closer to its true decimal value), and so that value we'd expect to round down.
It might seem wrong that 2.99499989F rounds up to 3.00 even though it is seemingly less than 2.995, but keep in mind that the 2.99499989 is a decimal, not a float, and you are "converting" it into a float, basically converting base-10 to base-2, and it is really 1's and 0's, then asking it to be rounded in base-10 terms, which means a conversion has to happen. Well, there are at least 2 base-10 values that I mentioned that can convert to that number as a float, and the simplest of those is 2.995.
|
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 MyFixture : ClassUnderTest { };
TEST_FIXTURE(MyFixture, OneTest)
{
do_something();
CHECK(protected_field == true);
}
Nevertheless, I think this is not very clean, because problems relating inheritance could arise in some configurations and, anyway, just protected members can be accessed and tested.
I tried to declare test classes as friends, but as these are created in some special way by UnitTest++, I haven't managed to do it yet.
Does anyone have any idea of how to make test classes friends of the the classes under test?
Is there another way of approaching this problem in an easier or different way?
Thank you all in advance.
| 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.
However, if you absolutely need to test private functions, here is a list of methods I would consider in order of my own preference:
Private member variables are to be accessed via public setters and getters.
I would recommend making you private member function a non-static non-member function in a namespace that can be called e.g. details or internal. Don't declare it in the header file, just define it in the same file where your class functions are defined. Add its declaration in a myClass_internal.h header file in the unit test project and test it. Difficulties involved depend largely on the complexity of your architecture.
Make your test class inherit from your testable class. This doesn't involve changing your code much, but might require use of multiple inheritance, which in some places is even banned.
Make your test a friend of your testable class. Difficulty depends on the test framework you are using. Say, with gtest that I use, it's pretty hard :)
A hack with redefining public and private should be your absolutely last resort if everything else fails. Although I would rather think of changing the design to a more testable one instead.
|
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 pair these yourself manually). If you don't need to wait/notify, just lock/unlock, then you don't need the condition variable, just the mutex. Bear in mind that mutexes are not necessarily "recursive", This means that if you're already holding the lock, you can't take it again unless you set the init flag to say you want that behaviour.
Where you would have called java.lang.Object.wait, call pthread_cond_wait or pthread_cond_timedwait.
Where you would have called java.lang.Object.notify, call pthread_cond_signal.
Where you would have called java.lang.Object.notifyAll, call pthread_cond_broadcast.
As in Java, spurious wakeups are possible from the wait functions, so you need some condition which is set before the call to signal, and checked after the call to wait, and you need to call pthread_cond_wait in a loop. As in Java, the mutex is released while you're waiting.
Unlike Java, where you can't call notify unless you hold the monitor, you can actually call pthread_cond_signal without holding the mutex. It normally doesn't gain you anything, though, and is often a really bad idea (because normally you want to lock - set condition - signal - unlock). So it's best just to ignore it and treat it like Java.
There's not really much more to it, the basic pattern is the same as Java, and not by coincidence. Do read the documentation for all those functions, though, because there are various flags and funny behaviours that you want to know about and/or avoid.
In C++ you can do a bit better than just using the pthreads API. You should at least apply RAII to the mutex lock/unlock, but depending what C++ libraries you can use, you might be better off using a more C++-ish wrapper for the pthreads functions.
|
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 << arrayPointer[j * dim + i] << " ";
output << endl;
}
This seems to be a very slow operation, is a more efficient way of outputting text files like this to the hard drive?
Update:
Taking the two suggestions into mind, the new code is this:
ofstream output (fileName.c_str());
for (int j = 0; j < dim; j++)
{
for (int i = 0; i < dim; i++)
output << arrayPointer[j * dim + i] << "\t";
output << "\n";
}
output.close();
writes to HD at 500KB/s
But this writes to HD at 50MB/s
{
output.open(fileName.c_str(), std::ios::binary | std::ios::out);
output.write(reinterpret_cast<char*>(arrayPointer), std::streamsize(dim * dim * sizeof(double)));
output.close();
}
| 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 * dim + i]);
fprintf(fout, "\n");
}
fclose(fout);
Just change %d to be the correct type.
|
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 = cx1; i < cx2; i++)
{
for (j = cy1; j < cy2; j++)
{
if (i >= 0 && i < x && j >= 0 && j < y)
ngrd(i-cx1,j-cy2) = ?? // this->(i,j); ****
}
}
return ngrd;
}
Thanks!
| 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)
Both give a function object with a function call operator that takes a pointer to a std::vector<int> and calls clear on it.
Edit: As UncleBens mentions, the parantheses around the function name are actually illegal, so I've removed them from my answer.
|
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 the screen instead of out of it (which is one version of a left handed coordinate system, the y-axis pointing down is another).
If you chose to switch coordinate system, you will have to change some of the standard settings in OpenGL to make it work. For instance you probably want to call glCullFace(GL_FRONT) (or reverse the order of all triangles sent to OpenGL).
|
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 gotten permission to come up with a new programming assignment.
It has to be of equal difficulty and it can be in C++, Objective C or Java.
What direction should I go that has the same level of difficulty but is a little bit more modern and applicable to modern CS/life.
Thanks
|
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 science of computation. If you wish to understand computers, then you should understand scanners and parsers.
Still, if you are convinced that you should do some other assignment, why not write a tool to generate a scanner in C++? You could supply, as input, a set of regular expressions that define the tokens of the grammar, and it would produce a C++ program that would recognize the input tokens. Then, you will never need to write a scanner ever again!
|
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 that it doesn't work because it shouldn't because the compiler isn't aware per the standard of the types that T represent.
Is there a way of making explicit that the type must be a structure?
What I'm doing in the code that works in VC is:
In the base class:
T* x
new T
sizeof(T)
In those that extend it:
x->member
Edit: I tried to take the relevant code. Here it is:
struct SomeStructureType
{
int memberA;
int memberB;
}
template <typename T> class Base
{
protected:
T* s;
void addMember(string name,void* offset);
Base()
{
s = new T;
}
};
class Extender : public Base<SomeStructureType>
{
public:
Extender()
{
addMember("memberA",&s->memberA);
}
}
| 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 reference or pointer variables of that type... and others you cannot do: define variables of that type, create an object of the type, call any method or request any attribute from the type...
|
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 my particular needs ).
Thanks
| 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 only the encryption algorithms I needed for my particular application, ( in this example it was SHA-1 and a couple of others)
3) Very very lightweight. Because of the modularity, it ended up being a very lightweight addition to my code.
|
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 seperate statements (notably loop headers), but what is the difference if any between these two pieces of code? My guess is that the comma has been left in as the result of cut & pasting, but is it a bug and does it effect execution?
| 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 the latter to b. So b = 5. Note that the brackets are important here:
b = 3, 5;
Will evaluate b = 3, then 5 and the result of the whole expression is 5, nevertheless b == 3.
The comma operator is especially helpful in for-loops when your iterator code is not a simple i++, but you need to do multiple commands. In that case a semicolon doesn't work well with the for-loop syntax.
|
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 hardware characteristics.
So my solution is to start a thread, make a queue and make my own read and write functions. So every time my functions are called, the data will be stored on the queue and then in the loop thread will be actually read or written on the memory. My functions will use a mutex to synchronize the access to the queue. My wrapper is going to be on a dll. The main module will call my dll init function once to start the thread, and then it will call my read/write functions many times from different threads.
My questions is: Is it safe to do this? the original functions are non reentrant. I don't know if this is going to be a problem. Is there a better way to do this?
Any help will be appreciated.
Sorry I forgot something:
-The language to be used is C++
-The main program will call my wrapper dll but also will call other modules (dlls) that are going to call the wrapper dll.
| 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 to the same piece of hardware, then you're going to have to come up with some higher level contract. Your thread then provides the ordered access to the driver. You'll find that the mediator will also allow you to throttle.
The hard part it seems is knowing when it is okay to make the next call to the device. Does it have some sort of flag to let you know it is ready for reads and writes? Some other questions: How do you plan to communicate state to your clients? Since you are providing an async interface, you'll need to have some sort of error callback registration, etc. Take a look at a normal async driver interface for ideas.
But overall, sounds like a good strategy to start with. As another poster mentioned, more specifics would be nice.
|
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 to consider allocating the memory from your C code and passing a pointer into the C++ library to copy the data.)
|
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 error right, then I have to replace my double with an int. Is there a simple way around this?
okay, here's the function then:
void myClass::someFunction(const double* r)
{
//map is boost::unordered_map<Node*, double>
//nodes is a pointer to std::vector<Node*>
std::vector<Node*>::iterator it;
for(it = nodes->begin(); it != nodes->end(); it++)
{
//calculate the index
map[*it] = r[index]; //error
}
}
| 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 do efficiently, which is one reason that hashes were excluded from the original C++ standard in favour of maps that use a tree structure rather than a hash table, and only require operator<() to be defined, which is usually much easier to write than an efficient hash function.
I'd also observe that if you are using a pointer to a node as the hash key, it may be easier and quicker to store the double value in the node itself, rather than use a hashtable, as you effectively already have the node you want to hand.
|
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 reset a flag at the end of the block, but I need the flag to remain set for the whole block.
| 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 manually from eclipse, as we do now.
I see that there are generated makefile and support files (sources.mk, subdir.mk etc.), scattered around, which are not under version control (probably the subclipse plugin is "clever" enough to exclude them). I guess I can put them under svn and use in the script we need.
however, this feels shaky. have anybody tried it? Are there any issues to expect? Are there recommended ways to achieve what we need?
N.B. I don't believe that an idea of adopting another build system will be accepted nicely, unless it's SUPER-smooth. We are a small company of 4 developers running full-steam ahead, and any additional overhead or learning curve will not appreciated :)
thanks a lot in advance!
| 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).
There is no overall make file so you can not easily use the build order of your projects that Eclipse had calculated
BTW: I wrote an Eclipse plugin that builds up a workspace from a given (textual) list of projects and then triggers the build. That's possible but also not an easy task.
Unfortunately I can't post the plugin somewhere because I wrote it for my former employer...
|
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 /clr property on the dll (under Configuration Properties:General). Now, I thought that P/Invoke could handle plain-old win32 dlls. Indeed, if I build my dll without /clr and just copy it by hand to bin/Debug, then the app runs fine. So why is /clr required to add the dll as a reference? And if VS won't let me add it, is there some (clean) workaround so that my app finds the dll?
I see that someone had a similar issue here (though with a 3rd-party dll):
Unable to add a DLL Reference to VS 2008 The answer he got was to build a wrapper. But this isn't really necessary, since the app can use the dll just fine; it's just the Add Reference step that doesn't work. And besides, won't the wrapper code need a reference to the dll, raising the same problem as before? I'd really like an answer that doesn't involve writing a wrapper at all.
| 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 to a const object
This can be explained by the fact that, a non-const reference can be used to change the value of the variable it is referring to. Hence, C++ does not permit a non-const reference to a const variable.
Could this be a possible explanation? C++ does not allow:
int &ref = 7;
Because that is not logical, but:
const int &ref = 7;
Is almost equivalent to:
const int val = 7;
So literal initialization is permitted for const variables.
P.S.: I'm currently studying Lippman's C++ Primer.
| 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 that it is actually quite unusual to create non-parameter reference variables as you are doing - the main purpose of references is to serve as function parameters and return values.
|
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 = reinterpret_cast<const classname*>(a);
const classname* _b = reinterpret_cast<const classname*>(b);
return _a->N < _b->N ? -1 : _a->N > _b->N ? 1 : 0;
}
...
classname* arr = new classname[n];
...
qsort(arr, n, sizeof(arr[0]), compare_classname);
|
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 Debug (/MTd)" (under C/C++|Code Generation|Runtime Library). I believe LIBCMTD.lib is the one for multi-threaded debug, but what is MSVCRTD.lib, and what could be causing this error?
If it makes a difference, this DLL is for Windows CE.
| 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.
Also, beware of the trouble you can get into if the DLL was compiled with /MT. You'll have major problems when the DLL returns pointers to objects that the client needs to release. It can't, it doesn't use the same memory allocator.
|
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(true){}
};
EDIT 1:
Problem is A holds a lot of virtual functions, which A1 doesn't override but the stub needs to, for indidicating that you are working on a stub instead of an actual object. Here maintainability is the question, for every function that i add to A, i need to override it in stub. forgetting it means dangerous behaviour as A's virtual function gets executed with stub's data. Sure I can add an abstract class ABase and let A and Astub inherit from them. But the design has become rigid enough to allow this refactor.
A reference holder to A is held in another class B. B is initialized with the stub reference, but later depending on some conditions, the reference holder in B is reinitialized with the A1,A2 etc.. So when i do this BObj.GetA(), i can check in GetA() if the refholder is holding a stub and then give an error in that case. Not doing that check means, i would have to override all functions of A in AStub with the appropriate error conditions.
| 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 type at all.
In your specific example you have a "stub" class. Instead of doing...
if(!stub)
{
dosomething;
}
Just call
object->DoSomething();
and have the implemention in AStub be a empty
|
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 after it is erased.
does it mean Itr has to point to the begin of the set everytime after i erase the element from the set?
| 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? Basically, I want to control the calling of a's constructor from within b's constructor.
| 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 instance member and/or its initialization.
template<class T>
class singleton {
singleton();
singleton(singleton const &);
singleton & operator = (singleton const &);
public:
static T & instance;
};
template<class T> T & T::instance;
Any insight would be greatly appreciated!
EDIT:
With this class declaration...
template<class T>
class singleton {
singleton();
singleton(singleton const &);
singleton & operator = (singleton const &);
public:
static T instance;
};
template <class T> T singleton<T>::instance;
When I try to do this...
class foo : public singleton<foo> { };
I get this error...
error C2248: 'singleton::singleton'
: cannot access private member
declared in class 'singleton'
...
This diagnostic occurred in the compiler generated function 'foo::foo(void)'
My interpretation is that singleton wants to construct a foo object which, by inheritance, depends on the construction of a singleton whose constructor is private. I figured singleton would have access to its own constructor but I guess not. Any ideas?
EDIT 2:
I've realized that the approach of inheriting from singleton<T> has the problem of requiring change to the class to be used as a singleton. I've ended up with the following code for my eager-initializing singleton class template.
template<typename T>
class singleton_wrapper {
singleton_wrapper();
singleton_wrapper(singleton_wrapper const &);
singleton_wrapper & operator = (singleton_wrapper const &);
static T instance;
template<typename T> friend T & singleton();
};
template<typename T> T singleton_wrapper<T>::instance;
template<typename T>
T & singleton() {
return singleton_wrapper<T>::instance;
}
For class...
class foo {
public:
void bar() { }
};
...One would access a single instance of it (initialized before main()) using the following:
singleton<foo>().bar();
Thanks again for the help, especially GMan. I'm very pleased with my first experience on stackoverflow.
| 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>::instance = singleton<T>::instance;
Or, more simply, just ditch the reference altogether:
template <class T>
class singleton {
...
public:
static T instance;
};
template <class T> T singleton<T>::instance;
|
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"
class Tree
{
int counter_;
std::vector<Node> nodes_;
public:
Tree() : counter_(0) {}
void start() {
for (int i=0; i<3; ++i) {
Node node(this, i);
this->nodes_.push_back(node);
}
nodes_[0].hi(); // calling a function of Node
}
void incCnt() {
++counter_;
}
void decCnt() {
--counter_;
}
};
#endif /* TREE_20100118 */
Node.h:
#ifndef NODE_20100118
#define NODE_20100118
#include <iostream>
//#include "Tree.h"
class Tree; // compile error without this
class Node
{
Tree * tree_;
int id_;
public:
Node(Tree * tree, int id) : tree_(tree), id_(id)
{
// tree_->incCnt(); // trying to call a function of Tree
}
~Node() {
// tree_->decCnt(); // problem here and in the constructor
}
void hi() {
std::cout << "hi (" << id_ << ")" << endl;
}
};
#endif /* NODE_20100118 */
Calling Tree:
#include "Tree.h"
...
Tree t;
t.start();
This is just a simple example to illustrate the problem. So what I want is calling a function of Tree from a Node object.
Update #1: Thanks for the answers. I tried to solve the problem like in Java, i.e. using just one file per class. It seems I will have to start separating .cpp and .h files...
Update #2: Below, following the hints, I pasted the complete solution too. Thanks, problem solved.
| 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) : tree_(tree), id_(id)
{
tree_->incCnt();
}
Node::~Node()
{
tree_->decCnt();
}
etc
This also has the effect of keeping your headers readable, so it is easy to see a class's interface at a glance.
|
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 function with an implementation?
| 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 - if A::f() were public or protected). Something like:
class B : public A {
virtual void f() {
// class B doesn't have anything special to do for f()
// so we'll call A's
// note that A's declaration of f() would have to be public
// or protected to avoid a compile time problem
A::f();
}
};
The use case I can think of off the top of my head is when there's a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicitly. It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.
Note that even though it's permitted by the language, it's not something that I see commonly used (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).
|
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 programming with SDL and OpenGL on MacOSX and it even has XCode templates which come with the ObjC needed to set up the menus, and it's pretty much what I was looking for.
Thanks!
| 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++ and Objective-C work together). However, Cocoa is MUCH easier to work with than the older C++ based Carbon. I would consider Carbon to be legacy. When apple put out 10.6, a lot of the under-the-hood stuff was transitioning their codebase from Carbon to Cocoa (like the Finder, etc).
|
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 determine whether a line (or series of lines) is the start of a function (or method).
At the very least, a function declaration is a return type followed by the identifier and an argument list. Is there a way to determine in C# that a token is a valid return type? If not, is there any way to easily determine whether a line of code is the start of a function? Basically I need to be able to reliably distinguish something like.
bool isThere()
{
...
}
from
bool isHere = isThere()
and from
isThere()
As well as any other function declaration lookalikes.
| 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 would have to compile the code to know how to interpret these.
Then you need to parse the text immediately prior to some scope open braces to work out what they are. Your functions may be in global scope, class scope, or namespace scope, so you have to be able to parse namespaces and classes to identify the type of scope you are looking at. You can usually get away with fairly simple parsing (most programmers use a similar style - for example, it's uncommon for someone to put blank lines between the 'class Fred' and its open brace. But they might write 'class Fred {'. There is also the chance that they will put extra junk on the line - e.g. 'template class __DECLSPEC MYWEIRDMACRO Fred {'. However, you can get away with a pretty simple "does the line contain the word 'class' with whitespace on both sides? heuristic that will work in most cases.
OK, so you now know that you are inside a namepace, and inside a class, and you find a new open scope. Is it a method?
The main identifying features of a method are:
return type. This could be any sequence of characters and can be many tokens ("__DLLEXPORT const unsigned myInt32typedef * &"). Unless you compile the entire project you have no chance.
function name. A single token (but watch out for "operator =" etc)
an pair of brackets containing zero or more parameters or a 'void'. This is your best clue.
A function declaration will not include certain reserved words that will precede many scopes (e.g. enum, class, struct, etc). And it may use some reserved words (template, const etc) that you must not trip over.
So you could search up for a blank line, or a line ending in ; { or } that indicates the end of the previous statement/scope. Then grab all the text between that point and the open brace of your scope. Then extract a list of tokens, and try to match the parameter-list brackets. Check that none of the tokens are reserved words (enum, struct, class etc).
This will give you a "reasonable degree of confidence" that you have a method. You don't need much parsing to get a pretty high degree of accuracy. You could spend a lot of time finding all the special cases that confuse your "parser", but if you are working on a reasonably consistent code-base (i.e. just your own company's code) then you'll probably be able to identify all the methods in the code fairly easily.
|
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 GetAdaptersInfo, WMI, NetBIOS or Sockets.
Here is one of them: Three ways to get your MAC address.
They, shore, return a MAC address, but this address can be set by hands from adapter properties
Control Panel > Network and Internet > Network and Sharing Center > Change Adatper Settings > right click on adapter > Properties > click "configure" button > go to "Advanced" tab > chose "Network Address" and change it
The all mentioned methods are not match my needs, because a MAC address, being set with driver has greater priority, than true hardware MAC address. This "fake" address will be returned by all Win API functions, that i know, and therefore, the genuine protection can easy be broken.
Any help from you, guys, will be greatly appreciated.
Thanks.
| 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 what the MAC address is.
|
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 memory. So how should I do this?
| 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 constructor for this, but you need it anyways for your return statement)
|
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 this case?
I ask this question because one of my professors is adamant that all literal numbers in a program are magic numbers. It would be nice for me just to access an element of an array using a real number, instead of using a named constant for each element.
Thanks!
| 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 know how many files files there are in the directory, and how to load every image in it??
I am Sorry about my English.
| 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>
namespace fs = boost::filesystem;
typedef std::vector<fs::path> PathVector;
std::auto_ptr<PathVector> ImagesInFolder(const fs::path& folderPath) {
std::set<std::string> targetExtensions;
targetExtensions.insert(".JPG");
targetExtensions.insert(".BMP");
targetExtensions.insert(".GIF");
targetExtensions.insert(".PNG");
std::auto_ptr<PathVector> paths(new PathVector());
fs::directory_iterator end;
for(fs::directory_iterator iter(folderPath); iter != end; ++iter) {
if(!fs::is_regular_file(iter->status())) { continue; }
std::string extension = iter->path().extension();
std::transform(extension.begin(), extension.end(), extension.begin(), ::toupper);
if(targetExtensions.find(extension) == targetExtensions.end()) { continue; }
paths->push_back(iter->path());
}
return paths;
}
This doesn't answer the part of your question about how to actually put the paths into a listbox though.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.