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,671,532 | 2,671,648 | non-copyable objects and value initialization: g++ vs msvc | I'm seeing some different behavior between g++ and msvc around value initializing non-copyable objects. Consider a class that is non-copyable:
class noncopyable_base
{
public:
noncopyable_base() {}
private:
noncopyable_base(const noncopyable_base &);
noncopyable_base &operator=(const noncopyable_base &);
};
class noncopyable : private noncopyable_base
{
public:
noncopyable() : x_(0) {}
noncopyable(int x) : x_(x) {}
private:
int x_;
};
and a template that uses value initialization so that the value will get a known value even when the type is POD:
template <class T>
void doit()
{
T t = T();
...
}
and trying to use those together:
doit<noncopyable>();
This works fine on msvc as of VC++ 9.0 but fails on every version of g++ I tested this with (including version 4.5.0) because the copy constructor is private.
Two questions:
Which behavior is standards compliant?
Any suggestion of how to work around this in gcc (and to be clear, changing that to T t; is not an acceptable solution as this breaks POD types).
P.S. I see the same problem with boost::noncopyable.
| The behavior you're seeing in MSVC is an extension, though it's documented as such in a roundabout way on the following page (emphasis mine) http://msdn.microsoft.com/en-us/library/0yw5843c.aspx:
The equal-sign initialization syntax is different from the function-style syntax, even though the generated code is identical in most cases. The difference is that when the equal-sign syntax is used, the compiler has to behave as if the following sequence of events were taking place:
Creating a temporary object of the same type as the object being initialized.
Copying the temporary object to the object.
The constructor must be accessible before the compiler can perform these steps. Even though the compiler can eliminate the temporary creation and copy steps in most cases, an inaccessible copy constructor causes equal-sign initialization to fail (under /Za, /Ze (Disable Language Extensions)).
See Ben Voigt's answer for a workaround which is a simplified version of boost::value_initialized, as pointed out by litb in a comment to Ben's answer. The docs for boost::value_initalized has a great discussion of the problem, the workaround, and some of the pitfalls of various compiler issues.
|
2,671,732 | 2,671,971 | Why is C++ fwrite() producing larger output in release? | I recently wrote an implementation of the Canonical Huffman compression algorithm. I have a 500kb test file that can be compressed to about 250kb when running the debug and release builds from within Visual Studio 2008. However when I run the release build straight from the executeable the test file only compresses to about 330kb.
I am assuming that something is going wrong when the file is written using fwrite(). I have tested the program and confirmed that uncompressing the files always produces the correct uncompressed file.
Does anyone know why this could possibly be? How could the same executeable file be producing different sized outputs based on where it is launched from?
| Try running it through App Verifier and see what it finds.
|
2,672,085 | 2,672,106 | What is the difference between Static and Dynamic arrays in C++? | I have to do an assignment for my class and it says not to use Static arrays, only Dynamic arrays. I've looked in the book and online, but I don't seem to understand.
I thought Static was created at compile time and Dynamic at runtime, but I might be mistaking this with memory allocation.
Can you explain the difference between static array and dynamic array in C++?
| Static arrays are created on the stack, and have automatic storage duration: you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size at compile time:
int foo[10];
Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size during runtime, but you need to allocate and free them yourself since they're not part of the stack frame:
int* foo = new int[10];
delete[] foo;
|
2,672,091 | 2,672,143 | Marshal managed string[] to unmanaged char** | This is my c++ struct (Use Multi-Byte Character Set)
typedef struct hookCONFIG {
int threadId;
HWND destination;
const char** gameApps;
const char** profilePaths;
} HOOKCONFIG;
And .Net struct
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct HOOKCONFIG {
public int threadId;
public IntPtr destination;
// MarshalAs?
public string[] gameApps;
// MarshalAs?
public string[] profilePaths;
}
I got some problem that how do I marshal the string array?
When I access the struct variable "profilePaths" in C++ I got an error like this:
An unhandled exception of type 'System.AccessViolationException' occurred in App.exe
Additional information: Attempted to read or write protected memory. This is often an
indication that other memory is corrupt.
MessageBox(0, cfg.profilePaths[0], "Title", MB_OK); // error ... Orz
| Easy way: Change prototype to IntPtr[]:
public IntPtr[] gameApps;
public IntPtr[] profilePaths;
Now when you call you need to roughly the following psudo-code:
GCHandle handle = GCHandle.Alloc(string);
gameApps = new IntPtr[] { GCHandle.ToIntPtr(handle) };
// Unmanaged call
handle.Free();
|
2,672,294 | 2,672,306 | Is it possible to send array over network? | I'm using C++ and wondering if I can just send an entire int array over a network (using basic sockets) without doing anything. Or do I have to split the data up and send it one at a time?
| You could definitely send an array in one send, however you might want to do some additional work. There are issues with interpreting it correctly at the receiving end. For example, if using different machine architectures, you may want to convert the integers to network order (e.g., htonl).
Another thing to keep in mind is the memory layout. If it is a simple array of integers, then it would be contiguous in memory and a single send could successfully capture all the data. If, though, (and this is probably obvious), you have an array with other data, then the layout definitely needs consideration. A simple example would be if the array had pointers to other data such as a character string, then a send of the array would be sending pointers (and not data) and would be meaningless to the receiver.
|
2,672,367 | 2,672,386 | three out of five file streams wont open, i believe its a problem with my ifstreams | #include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
using namespace std;
int main()
{
ifstream in_stream; // reads itemlist.txt
ofstream out_stream1; // writes in items.txt
ifstream in_stream2; // reads pricelist.txt
ofstream out_stream3;// writes in plist.txt
ifstream in_stream4;// read recipt.txt
ofstream out_stream5;// write display.txt
int wrong=0;
in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items
if( in_stream.fail() )// check to see if itemlist.txt is open
{
wrong++;
cout << " the error occured here0, you have " << wrong++ << " errors" << endl;
cout << "Error opening the file\n" << endl;
exit(1);
}
else{
cout << " System ran correctly " << endl;
out_stream1.open("ITEMLIST.txt", ios::out); // list of avaliable items
if(out_stream1.fail() )// check to see if itemlist.txt is open
{
wrong++;
cout << " the error occured here1, you have " << wrong++ << " errors" << endl;
cout << "Error opening the file\n";
exit(1);
}
else{
cout << " System ran correctly " << endl;
}
in_stream2.open("PRICELIST.txt", ios::in);
if( in_stream2.fail() )
{
wrong++;
cout << " the error occured here2, you have " << wrong++ << " errors" << endl;
cout << "Error opening the file\n";
exit (1);
}
else{
cout << " System ran correctly " << endl;
}
out_stream3.open("PRICELIST.txt", ios::out);
if(out_stream3.fail() )
{
wrong++;
cout << " the error occured here3, you have " << wrong++ << " errors" << endl;
cout << "Error opening the file\n";
exit (1);
}
else{
cout << " System ran correctly " << endl;
}
in_stream4.open("display.txt", ios::in);
if( in_stream4.fail() )
{
wrong++;
cout << " the error occured here4, you have " << wrong++ << " errors" << endl;
cout << "Error opening the file\n";
exit (1);
}
else{
cout << " System ran correctly " << endl;
}
out_stream5.open("display.txt", ios::out);
if( out_stream5.fail() )
{
wrong++;
cout << " the error occured here5, you have " << wrong++ << " errors" << endl;
cout << "Error opening the file\n";
exit (1);
}
else{
cout << " System ran correctly " << endl;
}
| Your code works. I think your current directory is not what you think it is.
Where are these files stored? Is your current directory the Debug/Release directory where the executable is stored or something like that?
You need to call close before opening the files for writing.
Avoid using the exit(0) function, as it doesn't give the C++ runtime the chance to cleanup gracefully. Throw a std::runtime_error instead.
|
2,672,398 | 2,672,440 | Throw exception from constructor initializer | What is the best way to throw exception from the constructor initializer?
For example:
class C {
T0 t0; // can be either valid or invalid, but does not throw directly
T1 t1; // heavy object, do not construct if t0 is invalid, by throwing before
C(int n)
: t0(n), // throw exception if t0(n) is not valid
t1() {}
};
I thought maybe making wrapper, e.g. t0(throw_if_invalid(n)).
What is the practice to handle such cases?
| There are multiple ways of going about this, I think. From what I understand, n can only take on a specific range of numbers. For that, you might prevent the constructor from even being run:
template <typename T, T Min, T Max>
class ranged_type_c
{
public:
typedef T value_type;
ranged_type_c(const value_type& pX) :
mX(pX)
{
check_value();
}
const value_type& get(void) const
{
return mX;
}
operator const value_type&(void) const
{
return get();
}
// non-const overloads would probably require a proxy
// of some sort, to ensure values remain valid
private:
void check_value(void)
{
if (mX < Min || mX > Max)
throw std::range_error("ranged value out of range");
}
value_type mX;
};
Could be more fleshed out, but that's the idea. Now you can clamp the range:
struct foo_c
{
foo_c(ranged_value_c<int, 0, 100> i) :
x(i)
{}
int x;
};
If you pass a value that does not lie from 0-100, the above would throw.
At runtime, I think your original idea was best:
template <typename T>
const T& check_range(const T& pX, const T& pMin, const T& pMax)
{
if (pX < pMin || pX > pMax)
throw std::range_error("ranged value out of range");
return pValue;
}
struct foo
{
foo(int i) :
x(check_range(i, 0, 100))
{}
int x;
}
And that's it. Same as above, but 0 and 100 can be replaced with a call to some function that returns the valid minimum and maximum.
If you do end up using a function call to get valid ranges (recommended, to keep clutter to a minimum and organization higher), I'd add an overload:
template <typename T>
const T& check_range(const T& pX, const std::pair<T, T>& pRange)
{
return check_range(pX, pRange.first, pRange.second); // unpack
}
To allow stuff like this:
std::pair<int, int> get_range(void)
{
// replace with some calculation
return std::make_pair(0, 100);
}
struct foo
{
foo(int i) :
x(check_range(i, get_range()))
{}
int x;
}
If I were to choose, I'd pick the runtime methods even if the range was compile-time. Even with low optimization the compiler will generate the same code, and it's much less clumsy and arguably cleaner to read than the class version.
|
2,672,536 | 2,672,575 | Specializing a class template constructor | I'm messing around with template specialization and I ran into a problem with trying to specialize the constructor based on what policy is used. Here is the code I am trying to get to work.
#include <cstdlib>
#include <ctime>
class DiePolicies {
public:
class RollOnConstruction { };
class CallMethod { };
};
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
template<unsigned sides = 6, typename RollPolicy = DiePolicies::RollOnConstruction>
class Die {
// policy type check
BOOST_STATIC_ASSERT(( boost::is_same<RollPolicy, DiePolicies::RollOnConstruction>::value ||
boost::is_same<RollPolicy, DiePolicies::CallMethod>::value ));
unsigned m_die;
unsigned random() { return rand() % sides; }
public:
Die();
void roll() { m_die = random(); }
operator unsigned () { return m_die + 1; }
};
template<unsigned sides>
Die<sides, DiePolicies::RollOnConstruction>::Die() : m_die(random()) { }
template<unsigned sides>
Die<sides, DiePolicies::CallMethod>::Die() : m_die(0) { }
...\main.cpp(29): error C3860: template argument list following class template name must list parameters in the order used in template parameter list
...\main.cpp(29): error C2976: 'Die' : too few template arguments
...\main.cpp(31): error C3860: template argument list following class template name must list parameters in the order used in template parameter list
Those are the errors I get in Microsoft Visual Studio 2010. I'm thinking either I can't figure out the right syntax for the specialization, or maybe it isn't possible to do it this way.
| Your constructor is not a template function. You should specialize the whole class.
|
2,672,538 | 2,672,598 | How might one develop a program like FRAPS? | I would like to make a program to capture video.
What is the best way to capture video?
I know C++ and I'm learning assembly. I found in my assembly book that I can get data from the video card. Would that be the best way?
I know FRAPS hooks into programs, but I would like my program to take video of the entire screen.
I would like something something fast, with low memory usage if possible. A requirement is that the program must be usable on other computers, despite dissimilar hardware.
| The way Fraps works, it's impossible to capture the entire screen (unless you're running a full-screen DirectX application, of course). You're apparently trying to emulate the functionality of CamStudio, more so than Fraps.
CamStudio is open-source (here is the SorceForge page) so perhaps you could start by studying the source code? I would wager that it's not really for beginners, however.
|
2,672,593 | 2,672,605 | Easy way to check if item is in list? | I'm writing a search algorithm in C++, and one of the things I need to do is have a few if statements that check cells above, below, left of, and right of.
Each time a cell is found to be open and added to the stack, I want it added to a list of cells already checked.
I want to be able to say in the if statement if(thisCell is not in checkedCells).
Any simple ideas?
| For this purpose it's better to use the std::set container, because it provides you with the ability to search for items faster than a list. Then you can write:
std::set<itemType> myset;
...
if (myset.find(item) != myset.end()) {
// item is found
}
A larger example can be found by googling. For example, here.
|
2,672,688 | 2,672,737 | Beginner: Sending data over sockets | Can anyone find an example of a simple server/client thing? I'm willing to use any C++ library or even Winsocks it self. I've Googled around but want some opinion on a good article for beginners/sites.
| If you're willing to use a C++ library, I heartily recommend Qt. It gives you an easy way to communicate with sockets, and much more. In particular see the QtNetwork module - a few of its relevant classes for your cause: QTcpSocket, QTcpServer, QUdpSocket.
|
2,672,866 | 2,672,889 | Create graph using adjacency list | #include<iostream>
using namespace std;
class TCSGraph{
public:
void addVertex(int vertex);
void display();
TCSGraph(){
head = NULL;
}
~TCSGraph();
private:
struct ListNode
{
string name;
struct ListNode *next;
};
ListNode *head;
}
void TCSGraph::addVertex(int vertex){
ListNode *newNode;
ListNode *nodePtr;
string vName;
for(int i = 0; i < vertex ; i++ ){
cout << "what is the name of the vertex"<< endl;
cin >> vName;
newNode = new ListNode;
newNode->name = vName;
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
void TCSGraph::display(){
ListNode *nodePtr;
nodePtr = head;
while(nodePtr){
cout << nodePtr->name<< endl;
nodePtr = nodePtr->next;
}
}
int main(){
int vertex;
cout << " how many vertex u wan to add" << endl;
cin >> vertex;
TCSGraph g;
g.addVertex(vertex);
g.display();
return 0;
}
| There is a problem in you addvertex method:
You have:
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
but it should be:
if (!head) // check if the list is empty.
head = newNode;// if yes..make the new node the first node.
else { // list exits.
nodePtr = head;
while(nodePtr->next) // keep moving till the end of the list.
nodePtr = nodePtr->next;
nodePtr->next = newNode; // add new node to the end.
}
Also you are not making the next field of the newNode NULL:
newNode = new ListNode;
newNode->name = vName;
newNode->next= NULL; // add this.
Also its a good practice to free up the dynamically allocated memory. So instead of having an empty destructor
~TCSGraph();
you can free up the list in the dtor.
EDIT: More bugs
You have a missing ; after the class declaration:
class TCSGraph{
......
}; // <--- add this ;
Also your destructor is only declared. There is no def. If you don't want to give any def, you must at least have a empty body. So replace
~TCSGraph();
with
~TCSGraph(){}
|
2,673,063 | 2,673,297 | Namespaces vs. Header files | I'm asking about the best practice widely used in C++ projects. I need to have my own types in the project. It's a collection of couple of typedefs.
Is including header file containing the types good practice in C++ or is it better to use namespaces. If so, why? What are the pros and cons of the two ways?
Right now it looks like this:
types.h:
#ifndef TYPES_H
#define TYPES_H
#include <list>
// forward declaration
class Class;
typedef int TInt;
// ...
typedef std::list<Class> class_list;
#endif
class.h:
#ifndef CLASS_H
#define CLASS_H
#include "types.h"
class Class
{
public:
// ...
TInt getMethod();
private:
// ...
};
How would it look like with namespaces?
| From a dependency point of view, naming all types in a single header is likely to be a maintenance nightmare. It's understandable for the typedef because you want a unique definition, but there is no reason to forward declare the class here.
// types.h
namespace myproject
{
typedef int TInt;
} // namespace myproject
There is no point in forward declaring the Class symbol: you pollute your own namespace. Let each file decide independently if they need the symbol or not and forward declare it on their own.
It's not pretty to declare ClassList either: it should only be available to those who need it. You could create a specific header for forward declaration of Class related stuff:
// class_fwd.h
namespace myproject
{
class Class;
typedef std::list<Class> ClassList;
} // namespace myproject
// class.h
#include "myproject/class_fwd.h"
namespace myproject
{
class Class {};
} // namespace myproject
|
2,673,162 | 2,673,318 | Creating an independent draw thread using pthreads (C++) | I'm working on a graphical application which looks something like this:
while (Simulator.simulating)
{
Simulator.update();
InputManager.processInput();
VideoManager.draw();
}
I do this several times a second, and in the vast majority of cases my computation will be taking up 90 - 99% of my processing time. What I would like to do is take out the processInput and draw functions and have each one run independently.
That way, I can have the input thread always checking for input (at a reasonable rate), and the draw thread attempting to redraw at a given frame rate.
The simulator is already (internally) multithreaded and there is no issues with multiple threads writing to the same data (each one processes a segment).
My issue is I'm not sure how I can properly do this. How would I properly initialize my pthread_t and associated pthread_attr_t so that the thread runs without blocking what I'm doing? In other words, how can I create two threads, each of which run an infinite loop?
To generalize even more, I'm trying to figure out how to do this:
for (int i = 0; i < threads; i++)
pthread_create(&th[i], NULL, func[i], NULL)
for (int i = 0; i < threads; i++)
pthread_join(th[i], NULL);
Where func[i] is some arbitrary function which runs in an infinite loop doing some arbitrary thing.
Any help or even a link is appreciated, thanks!
Edit: I should mention it is an interactive simulator, so I do need to have two infinite loops running independent of each other. I can only seem to run at once.
| First I would suggest using boost::thread as opposed to pthreads since you are using C++. With boost::thread you can do something like this:
#include <boost/thread.hpp>
void input_thread()
{
//...
}
void draw_thread()
{
//...
}
int main()
{
boost::thread input_th(&input_thread);
boost::thread draw_th(&draw_thread);
input_th.join();
draw_th.join();
return 0;
}
The constructor of a boost::thread automatically spawns a new thread and calls the function passed in. You can also use member functions as threads by using boost::bind. The join function blocks until the thread exits. This is necessary because if main() exits, all of your threads are killed.
Hopefully that will get you started, but the hard part is synchronizing (sharing data among threads). I suggest you look at the documentation for mutexes and condition variables. Remember that you need to make sure that only one thread is writing to the same memory location at once. Mutexes help solve this problem. Condition variables help by allowing you to signal and wait for signals between threads.
For instance, in the input thread you may fill a buffer with input then use a condition variable to signal to the draw thread that input is ready. In each thread, a mutex should be locked when accessing the buffer so that it is not overwritten by the input thread while the draw thread is trying to read it. As Goz suggested, a double buffer would make this easier and probably more efficient.
|
2,673,225 | 2,683,094 | using graphviz with qt | i have a compiler project and i want to print the ast after the compile complete
so can i print this ast to qt (on c++) panel using graphviz ?
note : i dont know if there is a binding between qt or c++ and graphviz , so if it doesnt work please help me to find the alternative .
thanks .
| i did this once. gcc has a flag to generate a .dot file of the AST. this file can then be displayed by graphviz. but be warned the AST is huge and is of limited use for all but the smallest functions.
see:
http://digitocero.com/en/blog/exporting-and-visualizing-gccs-abstract-syntax-tree-ast
|
2,673,409 | 2,673,522 | Swap bits in c++ for a double | Im trying to change from big endian to little endian on a double. One way to go is to use
double val, tmp = 5.55;
((unsigned int *)&val)[0] = ntohl(((unsigned int *)&tmp)[1]);
((unsigned int *)&val)[1] = ntohl(((unsigned int *)&tmp)[0]);
But then I get a warning: "dereferencing type-punned pointer will break strict-aliasing rules" and I dont want to turn this warning off.
Another way to go is:
#define ntohll(x) ( ( (uint64_t)(ntohl( (uint32_t)((x << 32) >> 32) )) << 32) | ntohl( ((uint32_t)(x >> 32)) ) )
val = (double)bswap_64(unsigned long long(tmp)); //or
val = (double)ntohll(unsigned long long(tmp));
But then a lose the decimals.
Anyone know a good way to swap the bits on a double without using a for loop?
| I'd probably try something like this:
template <typename T>
void swap_endian(T& pX)
{
// should static assert that T is a POD
char& raw = reinterpret_cast<char&>(pX);
std::reverse(&raw, &raw + sizeof(T));
}
Short and sweet (and relatively untested). The compiler will make all the necessary optimizations. The above is well-defined for any POD type, and doesn't rely on any implementation details.
A copy version, for when you don't want to modify the argument:
template <typename T>
T swap_endian_copy(T pX)
{
swap_endian(pX);
return pX;
}
|
2,673,495 | 2,673,516 | 'Invalid conversion from some_type** to const some_type**' | I've got a function that requires const some_type** as an argument (some_type is a struct, and the function needs a pointer to an array of this type). I declared a local variable of type some_type*, and initialized it. Then I call the function as f(&some_array), and the compiler (gcc) says:
error: invalid conversion from ‘some_type**’ to ‘const some_type**’
What's the problem here? Why can't I convert a variable to const?
| See: Why can't I pass a char ** to a function which expects a const char **? from the comp.lang.c FAQ.
|
2,673,508 | 3,160,064 | Correct usage(s) of const_cast<> | As a common rule, it is very often considered a bad practice to use const_cast<>() in C++ code as it reveals (most of the time) a flaw in the design.
While I totally agree with this, I however wonder what are the cases were using const_cast<>() is ok and the only solution.
Could you guys please give me some examples you know/you encountered ?
Thank you very much.
| const_cast is also used to remove volatile modifiers, as put into practice in this (controversed) article:
http://www.drdobbs.com/184403766
|
2,673,687 | 2,673,692 | Ambiguous constructor call | I'm trying to create a simple date class, but I get an error on my main file that says, "call of overloaded Date() is ambiguous." I'm not sure why since I thought as long as I had different parameters for my constructor, I was ok. Here is my code:
header file:
#ifndef DATE_H
#define DATE_H
using std::string;
class Date
{
public:
static const int monthsPerYear = 12; // num of months in a yr
Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object
void print() const; // print date in month/day/year format
~Date(); // provided to confirm destruction order
string getMonth(int month) const; // gets month in text format
private:
int month; // 1 - 12
int day; // 1 - 31
int year; // any year
int checkDay(int) const;
};
#endif
.cpp file
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include "Date.h"
using namespace std;
Date::Date()
{
time_t seconds = time(NULL);
struct tm* t = localtime(&seconds);
month = t->tm_mon;
day = t->tm_mday;
year = t->tm_year;
}
Date::Date(int mn, int dy, int yr)
{
if (mn > 0 && mn <= monthsPerYear)
month = mn;
else
{
month = 1; // invalid month set to 1
cout << "Invalid month (" << mn << ") set to 1.\n";
}
year = yr; // could validate yr
day = checkDay(dy); // validate the day
// output Date object to show when its constructor is called
cout << "Date object constructor for date ";
print();
cout << endl;
}
void Date::print() const
{
string str;
cout << month << '/' << day << '/' << year << '\n';
// new code for HW2
cout << setfill('0') << setw(3) << day; // prints in ddd
cout << " " << year << '\n'; // yyyy format
str = getMonth(month);
// prints in month (full word), day, year
cout << str << " " << day << ", " << year << '\n';
}
and my main.cpp
#include <iostream>
#include "Date.h"
using std::cout;
int main()
{
Date date1(4, 30, 1980);
date1.print();
cout << '\n';
Date date2;
date2.print();
}
| Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object
These are both callable with no parameters. It can't be default constructed, because it's ambiguous how to construct the object.
Honestly, having those three with default parameters doesn't make much sense. When would I specify one but not the others?
|
2,673,966 | 2,678,878 | Measure time between library call and callback | Hi: In an iPhone application I use a library(C++) which asynchronously makes a callback when computation is finished.
Now I want to measure the time which is spent -including the method which calls the library- until the callback is made. Are there any possibilities to do this with the Instruments application from Apple? What are the best practices?
| In the past I have used the following for making network calls I had to optimize - although at first it seems a bit convoluted, it certainly gives the most accurate times I have seen.
uint64_t time_a = mach_absolute_time();
// do stuff
uint64_t time_b = mach_absolute_time();
[self logTime:(time_b-time_a)];
- (void) logTime:(uint64_t)machTime {
static double timeScaleSeconds = 0.0;
if (timeScaleSeconds == 0.0) {
mach_timebase_info_data_t timebaseInfo;
if (mach_timebase_info(&timebaseInfo) == KERN_SUCCESS) {
double timeScaleMicroSeconds = ((double) timebaseInfo.numer / (double) timebaseInfo.denom) / 1000;
timeScaleSeconds = timeScaleMicroSeconds / 1000000;
}
}
NSLog(@"%g seconds", timeScaleSeconds*machTime);
}
|
2,674,046 | 2,678,816 | Several numpy arrays with SWIG | I am using SWIG to pass numpy arrays from Python to C++ code:
%include "numpy.i"
%init %{
import_array();
%}
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)};
class Class
{
public:
void test(float* data, int n)
{
//...
}
};
and in Python:
c = Class()
a = zeros(5)
c.test(a)
This works, but how can I pass multiple numpy arrays to the same function?
| I found out the answer from a collegue of mine:
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data1, int n1), (float* data2, int n2)};
class Class
{
public:
void test(float* data1, int n1, float* data2, int n2)
{
//...
}
};
Now two numpy arrays are passed to Class::test.
|
2,674,351 | 2,674,360 | what is the name of this pattern? | What is the name of that kind of structure?
Or where can I read about that.
class A : public B < A > { ... }
| Check out the Curiously recurring template pattern.
|
2,674,370 | 2,674,373 | Stream overloading in C++ | why does
void operator<<(ostream out, Test &t);
return an error whereas
void operator<<(ostream &out, Test &t);
does not ?
| Because you cannot copy streams, you have to pass them per reference.
Note that the canonical form of operator<< is this:
std::ostream& operator<<(std::ostream& out, const Test &t)
{
// write t into out
return out;
}
returning the stream is important so that you can string output together:
std::cout << Test() << '\n';
|
2,674,462 | 2,684,426 | Lua and C++: separation of duties | Please help to classify ways of organizing C++/Lua game code and to separate their duties. What are the most convenient ways, which one do you use?
For example, Lua can be used for initializing C++ objects only or at every game loop iteration. It can be used for game logic only or for graphics, too. Some game engines provide full control to all subsytems from scripts! I really do not like this approach (no separation at all).
Is it a good idea to implement all game objects (npc, locations) as Lua tables without C++ objects? Or it is better to mirror them (Lua tables to control C++ objects)? Or something else?
Thank you.
Edit. My classification: Lua and C++: separation of duties.
Topic's continuation: Lua, game state and game loop
| My approach has been to limit what is exposed to Lua as much as possible. I have never found a need for a "main" or other such function which is called every time the scene is rendered (or more). Some Lua engines (like LOVE) do this however. I prefer to define objects with optional callback functions for common events that you may want the object to respond to such as a collision, mouse click, entering or leaving the game world, etc..
The end result is very declarative, almost a config file for objects. I have a function for creating classes or types of objects and another for creating objects based on these types. The objects then have a collection of methods which can be called when responding to various events. All of these Lua methods map to C/C++ methods which in turn modify the object's private properties. Here is an example of a bucket object which can capture ball objects:
define {
name='ball';
texture=png('images/orb.png');
model='active';
shape='circle';
radius=16;
mass=1.0;
elastic=.7;
friction=.4;
}
define {
name='bucket';
model='active';
mass=1;
shape='rect';
width=60;
height=52;
texture=png('images/bucket.png');
elastic=.5;
friction=.4;
oncontact = function(self, data)
if data.subject:type() == 'ball' then
local a = data.subject:angleTo(self:getxy())
if a < 130 and a > 50 then
--update score etc..
end
end
end;
}
I would not take this as the "one true way" to implement your scripting API. One of the beauties of Lua is that it supports many different styles of API. This is just what I have found works well for the games that I make - 2D physics based games.
|
2,674,622 | 2,674,789 | Member variable pointers to COM objects | Is there any problem with keeping member variable pointer refernces to COM objects and reussing the reference through out the class in C++.
Is anybody aware of a reason why you would want to call .CreateInstance every time you wanted a to use the COM object i.e. you were getting a fresh instance each time.
I cannot see any reason who you would want to do this,
Thanks,
(No is an acceptable answer!!!)
| There is no general rule in this case because there are a number of variables that decide whether it is a good idea or not.
First: If you own the COM objects in question i.e. have source code and control over how they are used, then yes its perfectly safe.
If COM objects are 3rd party COM objects sometimes crappy code in them may force you to "createInstance" on them every time you use them - out of necessity (and self preservation).
If the COM object is acting as a proxy object you may need to create them every time you use them because of stuff behind the scene i.e. other clients using the same object.
there are more situations, but to summarize: it depends...
|
2,674,625 | 2,674,762 | How close can I get C# to the performance of C++ for small intensive tasks? | I was thinking about the speed difference of C++ to C# being mostly about C# compiling to byte-code that is taken in by the JIT compiler (is that correct?) and all the checks C# does.
I notice that it is possible to turn a lot of these functions off, both in the compile options, and possibly through using the unsafe keyword as unsafe code is not verifiable by the common language runtime.
Therefore if you were to write a simple console application in both languages, that flipped an imaginary coin an infinite number of times and displayed the results to the screen every 10,000 or so iterations, how much speed difference would there be? I chose this because it's a very simple program.
I'd like to test this but I don't know C++ or have the tools to compile it. This is my C# version though:
static void Main(string[] args)
{
unsafe
{
Random rnd = new Random();
int heads = 0, tails = 0;
while (true)
{
if (rnd.NextDouble() > 0.5)
heads++;
else
tails++;
if ((heads + tails) % 1000000 == 0)
Console.WriteLine("Heads: {0} Tails: {1}", heads, tails);
}
}
}
Is the difference enough to warrant deliberately compiling sections of code "unsafe" or into DLLs that do not have some of the compile options like overflow checking enabled? Or does it go the other way, where it would be beneficial to compile sections in C++? I'm sure interop speed comes into play too then.
To avoid subjectivity, I reiterate the specific parts of this question as:
Does C# have a performance boost from using unsafe code?
Do the compile options such as disabling overflow checking boost performance, and do they affect unsafe code?
Would the program above be faster in C++ or negligably different?
Is it worth compiling long intensive number-crunching tasks in a language such as C++ or using /unsafe for a bonus? Less subjectively, could I complete an intensive operation faster by doing this?
| The example given is flawed because it does not show real life usage of both programming languages. Using simple datatypes to measure the speed of a language will not bring anything interesting. Instead, I suggest you create a template class in C++ and compare it with what is possible in C# for class generics. In the end, objects will bring some important results and you will see that C++ is faster than C#. Not to mention that you are comparing a lower level programming language with C#.
Does C# have a performance boost from
using unsafe code?
Yes, it will have a boost but it is not suggested that you write only code with unsafe. Here is why: Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet. http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx
Would the program above be faster in
C++ or negligably different?
Yes the program would be slightly faster in C++. C++ is a lower programming language and even faster if you start using the algorithm library (random_shuffle comes to mind).
Is it worth compiling long intensive
number-crunching tasks in a language
such as C++ or using /unsafe for a
bonus? Less subjectively, could I
complete an intensive operation faster
by doing this?
It depends on the project...
|
2,674,649 | 2,674,796 | C++ setTimout function? | What's the cheapest way for a JavaScript like setTimeout-function in C++?
I would need this:
5000 miliseconds from now, start function xy (no parameters, no return value).
The reason for this is I need to initialize COM for text to speech, but when I do it on dll attach, it crashes.
It works fine however if I do not call CoInitialize from dllmain.
I just need to call CoInitialize and CoCreateInstance, and then use the instance in other functions. I can catch the uninitialized instance by checking for NULL, but I need to initialize COM - without crashing.
| Calling CoInitialize() from DllMain() is a bad thing to do; there are LOTS of restrictions on what you can do from DllMain(); see here: http://blogs.msdn.com/larryosterman/archive/2004/04/23/118979.aspx
Even if it DID work reliably then initialising COM from within DllMain() isn't an especially nice thing to do as COM is initialised per thread and you don't know what the application itself wants to do with regards to COM apartments for the thread that you want to initialise COM for... This means that you might initialise COM in one way and then the application might need to initialise it in another way and might fail because of what your DLL had done...
You COULD spin up a thread in DllMain() as long as you are careful (see here http://blogs.msdn.com/oldnewthing/archive/2007/09/04/4731478.aspx) and then initialise COM on that thread and do all your COM related work on that thread. You would need to marshal whatever data you need to use COM with from whatever thread you're called on to your own COM thread and make the COM call from there...
And then there's the question of whether the instance of the COM object that you create (could you reliably do what you want to do) would be usable from the thread that was calling into your DLL to make the call... You do understand how you'd have to marshal the interface pointer if required, etc?
Alternatively you should expose YOUR functionality via COM and then have the application load your DLL as a COM DLL and everything will work just fine. You can specify the apartment type that you need and the app is responsible for setting things up for you correctly.
So, in summary, you don't need the answer to your question.
|
2,674,913 | 2,674,996 | bad file descriptor with close() socket (c++) | I'm running out of file descriptors when my program can't connect another host. The close() system call doesn't work, the number of open sockets increases. I can se it with
cat /proc/sys/fs/file-nr
Print from console:
connect: No route to host
close: Bad file descriptor
connect: No route to host
close: Bad file descriptor
..
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <iostream>
using namespace std;
#define PORT 1238
#define MESSAGE "Yow!!! Are we having fun yet?!?"
#define SERVERHOST "192.168.9.101"
void
write_to_server (int filedes)
{
int nbytes;
nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
if (nbytes < 0)
{
perror ("write");
}
}
void
init_sockaddr (struct sockaddr_in *name,
const char *hostname,
uint16_t port)
{
struct hostent *hostinfo;
name->sin_family = AF_INET;
name->sin_port = htons (port);
hostinfo = gethostbyname (hostname);
if (hostinfo == NULL)
{
fprintf (stderr, "Unknown host %s.\n", hostname);
}
name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
}
int main()
{
for (;;)
{
sleep(1);
int sock;
struct sockaddr_in servername;
/* Create the socket. */
sock = socket (PF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror ("socket (client)");
}
/* Connect to the server. */
init_sockaddr (&servername, SERVERHOST, PORT);
if (0 > connect (sock,
(struct sockaddr *) &servername,
sizeof (servername)))
{
perror ("connect");
sock = -1;
}
/* Send data to the server. */
if (sock > -1)
write_to_server (sock);
if (close (sock) != 0)
perror("close");
}
return 0;
}
Fix:
if (0 > connect (sock,
(struct sockaddr *) &servername,
sizeof (servername)))
{
perror ("connect");
}
else
write_to_server (sock);
if (close (sock) != 0)
perror("close");
| It looks like the problem is in the structure of your program. Every time through your infinite loop, you're creating a new socket. I'd suggest moving this out of the loop and re-using it.
If you'd like to just fix the way you're doing it now though, use close inside the "connect" failed if statement you have now. The descriptor is allocated by the 'socket' call and only connected with the 'connect' call. By setting your 'sock' variable to -1, you're throwing away the descriptor allocated by 'socket'. Call close, then set it to -1 and you should be set.
|
2,675,016 | 2,675,077 | Semaphores in unmanaged code | I've been using the Semaphore class to create semaphores. However, the examples use managed code (requires /clr), and I need to use unmanaged code because it seems FreeType doesn't like working with managed code.
How can I create two simple threads which use a semaphore in unmanaged code?
| Use native Windows semaphore objects.
|
2,675,037 | 2,675,197 | Thread Local Memory, Using std::string's internal buffer for c-style Scratch Memory | I am using Protocol Buffers and OpensSSL to generate, HMACs and then CBC encrypt the two fields to obfuscate the session cookies -- similar Kerberos tokens.
Protocol Buffers' API communicates with std::strings and has a buffer caching mechanism; I exploit the caching mechanism, for successive calls in the the same thread, by placing it in thread local memory; additionally the OpenSSL HMAC and EVP CTX's are also placed in the same thread local memory structure ( see this question for some detail on why I use thread local memory and the massive amount of speedup it enables even with a single thread).
The generation and deserialization, "my algorithms", of these cookie strings uses intermediary void *s and std::strings and since Protocol Buffers has an internal memory retention mechanism I want these characteristics for "my algorithms".
So how do I implement a common scratch memory ? I don't know much about the rdbuf(streambuf - strinbuf ??) of the std::string object. I would presumeably need to grow it to the lowest common size ever encountered during the execution of "my algorithms". Thoughts ?
My question I guess would be: " is the internal buffer of a string re-usable, and if so, how ?"
Edit (new question):
It seems uppon reflection after Vlad's post that I do need a std::string as well a void * c-style scratch buffer. My question would then be: do popular stl's string implementations retain memory when they dont need it ? (my needs will probably stay between 128-bytes to 10-KB).
| You shouldn't expect the whole content of your std::string to reside in TLS, since std::string makes allocations and reallocations for data on its own. A simple idea would be to allocate a structure on heap and store a pointer to it in the TLS.
Edit:
AFAIK rdbuf is a feature of streams, not of string (see here and here).
Edit:
I would suggest using std::vector instead of string, it should be contiguous. Again, it's perhaps better to put just a pointer to the vector into TLS. The comments to the same article say that the standard requires even string to be contiguous, starting from &(str[0]) char.
|
2,675,228 | 2,675,229 | How to create pointer-to-mutable-member? | Consider the following code:
struct Foo
{
mutable int m;
template<int Foo::* member>
void change_member() const {
this->*member = 12; // Error: you cannot assign to a variable that is const
}
void g() const {
change_member<&Foo::m>();
}
};
Compiler generates an error message. The thing is that the member m is mutable therefore it is allowed to change m. But the function signature hides mutable declaration.
How to decalre pointer-to-mutable-member to compile this code?
If it is impossible please link to Standard C++.
| This code is ill-formed according to C++ Standard 5.5/5:
The restrictions on cv-qualification,
and the manner in which the
cv-qualifiers of the operands are
combined to produce the cv-qualifiers
of the result, are the same as the
rules for E1.E2 given in 5.2.5. [Note:
it is not possible to use a pointer to member that refers to a mutable
member to modify a const class
object.
For example,
struct S {
mutable int i;
};
const S cs;
int S::* pm = &S::i; // pm refers to mutable member S::i
cs.*pm = 88; // ill-formed: cs is a const object
]
You could use wrapper class to workaround this problem as follows:
template<typename T> struct mutable_wrapper { mutable T value; };
struct Foo
{
mutable_wrapper<int> m;
template<mutable_wrapper<int> Foo::* member>
void change_member() const {
(this->*member).value = 12; // no error
}
void g() const {
change_member<&Foo::m>();
}
};
But I think you should consider redesign your code.
|
2,675,262 | 2,676,125 | Does anyone know of a simple yet flexible 2d scene graph in c++? | I'm searching a simple 2d scene graph written in c++, possibly on top of OpenGL but that's not mandatory: the perfect thing would be the Cocos2d/Cocos2d-iphone scenegraph in c++.
Do you know of any existing implementations?
| Here are a few ideas:
SGL - It is designed for 3D scene graphs, but also might support 2D. The website looks pretty informative.
Papyrus C++ Cairo Scenegraph Library
|
2,675,870 | 2,675,887 | Getting error while linking with g++ | I try to compile and link my application in 2 steps :
Compiling:
g++ -c -o file1.o file1.cc general_header.h
g++ -c -o file2.o file2.cc general_header.h
g++ -c -o file3.o file3.cc general_header.h
Linking:
g++ -o myApp file1.o file2.o file3.o
I'm getting a link error as following:
file1.o: file not recognized: File format not recognized
collect2: ld returned 1 exit status
Am i doing something wrong ?
Thanks
| No need to include header files in your input files list
g++ -c -o file1.o file1.cc
|
2,675,928 | 4,949,592 | How to identify Draft from Inbox and Sent mails In ALL MAIl mailbox | I am working on a mail client Application for downloading gmail emails,
which uses IMAP C-client library.
I want to download emails from "ALLMAIL" mailbox folder.
as you know ALLMAIL folder consists of Inbox,Sent Mail and Draft Mails.
Here my requirement is to distinguish Draft from Inbox and Sent mails.
Usually if we download envelop of emails, that should give email's Draft info.
But Gmail is failing to set this draft info.
So can you please suggest how to identify draft?
Thanks In advance
Subbi
| Gmail IMAP has some issue with setting the DRAFT flag, I faced the same issue when i was working with it. I deviced a workaround where I checked the delivered-to and return-path mail headers, if these headers where not there I assumed this to be a draft message.
|
2,676,226 | 2,676,264 | What is a good format for command line output when it is being used for further processing? | I have written a console application in Delphi that queries information from several locations. This application will be launched by another process, and the output to STDOUT will be captured by the launching process.
The information I am retrieving is to be interpreted by the calling application for reporting purposes. What is the best way to output this data to STDOUT so that it can be easily parsed? JSON? XML? CSV? The data, specifically, is remote workstation information, so it will pull things back like running processes, and details about each process.
Does anyone have any experience with this or suggestions?
| If you want something that can be easily parsed, especially if it has to be done quickly, go with the simplest format that can effectively communicate the information you need. CSV if you can, otherwise try JSON. Definitely not XML unless you really, really need all the extra complexity for some reason.
|
2,676,337 | 2,676,419 | Custom iterator for a class based on two sets | I have a class that contains two sets. They both contain the same key type but have different compare operations.
I would like to provide an iterator for the class that iterates through the elements of both sets. I want to start with one set, then when I increment an iterator pointing to the last element of the first set, I want to go to the first element of the second set. How do I do this? I would like to preserve the bidirectional iterator semantics of std::set, but if it turns out that implementing a forward iterator is much easier, so be it.
I'm willing to use the Boost Iterator library if that would help.
| I implemented a very similar iterator using the boost libraries:
Have a read from here:
http://www.boost.org/doc/libs/1_42_0/libs/iterator/doc/iterator_facade.html#a-basic-iterator-using-iterator-facade
For a forward iterator you will need to implement the operator++, to change that to a bidirectional iterator you need to implement operator--.
The implementation is up to you, but all is explained in the documentation.
|
2,676,443 | 2,676,463 | Inheriting private members in C++ | suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private data members
| A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
|
2,676,503 | 2,682,646 | Qt "no matching function for call" | I have
no matching function for call to 'saveLine::saveLine()'
error when compiling my application. The construcor is never actually called.
saveLine class definition:
class saveLine
{
public:
saveLine(QWidget *parent);
private:
QPushButton *selectButton, *acceptButton;
QLabel *filePath;
QLineEdit *allias;
};
saveLine is used in another class which is defined as follows:
class MWindow : public QWidget
{
Q_OBJECT
public:
MWindow(QWidget *parent=0);
private:
saveLine line1;
};
error points to MWindow constructor implementation
MWindow::MWindow(QWidget *parent):QWidget(parent)
{
this->setWindowTitle("Launcher");
this->resize(600,600);
}
What should i do? I intend to use saveLine class in a vector, to create lines at runtime.
EDIT: i've misdeclared line1, it should read
saveLine *line1;
but now it gives another error
ISO C++ forbids declaration of 'saveLine' with no type
and
expected ';' before '*' token
on this line. It seems like saveLine is no longer considered a class, how so?
|
but now it gives another error
ISO C++ forbids declaration of
'saveLine' with no type
You need to add a forward declaration to tell the compiler that saveLine class exists:
Like this:
//declare that there will be a class saveLine
class saveLine;
class MWindow : public QWidget
{
Q_OBJECT
public:
MWindow(QWidget *parent=0);
private:
saveLine *line1;
};
|
2,676,522 | 2,676,614 | When is the right time to draw? | I just finished essential part of my own personal 2D engine in C++ and I'm kinda deciding how to complete the part where it is actually supposed to display everything on the screen, namely when do I call that function which does the job.
I don't have much idea of how does the graphic card work, my biggest experience is calling bios graphic services to write some stuff on the screen. Could you give me a hint on this please? Or maybe some keywords I should try to google?
| look up render loop.
In a game, you will do it in a loop. You can also look up game loop which is a related concept if you're working on a game.
|
2,676,988 | 2,677,589 | How to change size of STL container in C++ | I have a piece of performance critical code written with pointers and dynamic memory.
I would like to rewrite it with STL containers, but I'm a bit concerned with performance. Is there a way to increase the size of a container without initializing the data?
For example, instead of doing
ptr = new BYTE[x];
I want to do something like
vec.insert(vec.begin(), x, 0);
However this initializes every byte to 0. Isn't there a way to just make the vector grow?
I know about reserve() but it just allocates memory, it doesn't change the size of the vector, and doesn't allows me to access it until I have inserted valid data.
Thank you everyone.
| vec.resize( newsize ) is defined to have the same effect as
vec.insert( vec.end(), newsize - vec.size(), T() )
if newsize > vec.size()… but the compiler may have difficulty determining that it is growing, not shrinking, and by how much. You might try profiling with both.
If you're sure that the default initialization is taking time, explicitly eliminate it with your own constructor. (Even if the implicit constructor is fine, it's good to show intent.)
struct BYTE {
char v;
BYTE() {} // no default initialization!
BYTE( char x ) : v(x) {}
operator char&() { return v; }
operator char const&() const { return v; }
char *operator&() { return &v; } // not sure about operator&...
char const *operator&() const { return &v; } // probably good in this case
};
|
2,676,990 | 2,677,005 | Is it a good idea to apply some basic macros to simplify code in a large project? | I've been working on a foundational c++ library for some time now, and there are a variety of ideas I've had that could really simplify the code writing and managing process. One of these is the concept of introducing some macros to help simplify statements that appear very often, but are a bit more complicated than should be necessary.
For example, I've come up with this basic macro to simplify the most common type of for loop:
#define loop(v,n) for(unsigned long v=0; v<n; ++v)
This would enable you to replace those clunky for loops you see so much of:
for (int i = 0; i < max_things; i++)
With something much easier to write, and even slightly more efficient:
loop (i, max_things)
Is it a good idea to use conventions like this? Are there any problems you might run into with different types of compilers? Would it just be too confusing for someone unfamiliar with the macro(s)?
| IMHO this is generally a bad idea. You are essentially changing well known and understood syntax to something of your own invention. Before long you may find that you have re-invented the language. :)
|
2,677,029 | 2,677,098 | read numbers from files in columns, one column whole numbers, other column numbers with decimals | int price=' '; // attempt to grab a decimal number - but not the correct way
int itemnum=' '; // attempt to grab a whole number - but not the right way
while((price== (price*1.00)) && (itemnum == (itemnum*1)))
What is a way to get numbers in 2 diff columns where one column is whole numbers and the other are numbers with decimal places?
| The best way would be to get each separately. If it is from a file then you can do this:
int itemnum;
double price;
inputFile >> itemNum >> price; //If the columns are ItemNumber then Price
or
inputFile >> price >> itemnum; //If the columns are the other way around
The >> operator is nice in C++ because it attempts to cast the input to whatever type you are using.
EDIT: Here is a small example for a file:
#include <fstream>
#include <iostream>
int main()
{
int input1;
double input2;
//Open file
std::ifstream inFile;
inFile.open("myFile.txt"); //or whatever the file name is
while(!inFile.eof())
{
//Get input
inFile >> input1 >> input2;
//Print input
std::cout << input1 << " " << input2 << " ";
}
//Close file
inFile.close();
return 0;
}
The file for this could have this data: 120 12.956 121 13.001 1402 12345.8
and the output would be: 120 12.956 121 13.001 1402 12345.8
It will work if the numbers are in columns too.
|
2,677,037 | 2,677,526 | C++ macro "if class is defined" | Is there such macro in C++ (cross-compiler or compiler-specific):
#if isclass(NameSpace::MyClass)
Would be useful.
| If you do not care about portability, the __if_exists statement in VC++ meets your needs.
|
2,677,097 | 2,677,123 | Can I free memory passed to SysAllocString? | When allocating a new BSTR with SysAllocString via a wchar_t* on the heap, should I then free the original wchar_t* on the heap?
So is this the right way?
wchar_t *hs = new wchar_t[20];
// load some wchar's into hs...
BSTR bs = SysAllocString(hs);
delete[] hs;
Am I supposed to call delete here to free up the memory? Or was that memory just adoped by the BSTR?
| As its name implies, SysAllocString allocates its memory, it does not "adopt" its argument's memory. BSTRs are size-prefixed and null-terminated, so "adopting" a c-style string is impossible, as there is no space for the size prefix.
|
2,677,158 | 2,677,209 | understanding of FPS and the methods they use | Just looking on resources that break down how frames per second work. I know it has something to do with keeping track of Ticks and figure out how many ticks occured between each frame. But I never ran into any resources on why exactly you have to use the methods you use in order to get a smooth frame work. I am trying to get a thourough understanding of this. Can any explain or provide any good resources ? Thanks
| There are basically two approaches.
In ActionScript (and many other engines), you request the player to call a certain function at a certain framerate. For Flash games, you'll set the framerate to be 30 FPS, and then you'll implement a function that listens for ENTER_FRAME events to do what you need to do. This means you get roughly 33 ms per frame (1000ms/30FPS=33.33ms/frame). If your code that responds to ENTER_FRAME takes more than 33 ms, you'll get some stuttering.
In home-rolled main loops (like you'd generally do in C++/SDL, for example), you run the main loop as fast as possible. This means the time between each frame will be variable. You still need to keep the "guts" of your frame code less than 33 ms to make sure you'll get at least 30 FPS, but your game will run faster than 30 FPS if not a lot's going on. To account for this, you need to program all your logic in terms of elapsed time since last frame, and abandon using frames themselves as a unit of time.
|
2,677,221 | 2,677,245 | Someone is using the struct name as a variable name too. What does the code really say? | This morning we found an old chunk of code that was causing a library call to crash.
struct fred
{
int a;
int b;
int c;
};
fred fred[MAX_SIZE+1];
memset( fred, 0, sizeof(fred) * MAX_SIZE+1 );
It appears that the sizeof(fred) may have been the full array size, rather than the structure size, as it was overwriting a great deal of memory.
The fact that it compiled without warning on several different systems seemed odd.
Is there a correct semantic for this case where the type and variable name are colliding?
or is this some sort of undefined behavior? or just a defect?
| Number one would be, don't do this as it's confusing - but you've already discovered this.
The variable hides the name of the struct, but you can still use struct fred to refer to the type.
e.g.
fred fred[MAX_SIZE+1];
memset( fred, 0, sizeof(struct fred) * (MAX_SIZE+1) );
Alternatively, why not just use the size of the complete object. That way your memset call is robust in the face of changes to either the array size or type. You can do:
memset( fred, 0, sizeof fred );
You must have the parentheses when using a type id with sizeof but it's not needed when you use an object.
|
2,677,577 | 2,677,818 | How to overload operator<< for qDebug | I'm trying to create more useful debug messages for my class where store data. My code is looking something like this
#include <QAbstractTableModel>
#include <QDebug>
/**
* Model for storing data.
*/
class DataModel : public QAbstractTableModel {
// for debugging purposes
friend QDebug operator<< (QDebug d, const DataModel &model);
//other stuff
};
/**
* Overloading operator for debugging purposes
*/
QDebug operator<< (QDebug d, const DataModel &model) {
d << "Hello world!";
return d;
}
I expect qDebug() << model will print "Hello world!". However, there is alway something like "QAbstractTableModel(0x1c7e520)" on the output.
Do you have any idea what's wrong?
| After an hour of playing with this question I figured out model is pointer to DataModel and my operator << takes only references.
|
2,677,719 | 2,677,778 | How can I extract the current user's account picture? | I am trying to extract the current user's account picture in Windows 7, but I can't seem to figure out where it is located. I have found that the picture is sometimes written to the User's temp folder, but only after performing certain actions. It isn't always guaranteed to be there. Has anyone had any luck extracting this image? Thanks!
Update: I am trying to extract the image using C++, but help in any language would be a big step. :)
| It's described here under User Profile Tiles in Windows 7. It doesn't seem very encouraging.
|
2,677,770 | 2,677,814 | vector::erase with pointer member | I am manipulating vectors of objects defined as follow:
class Hyp{
public:
int x;
int y;
double wFactor;
double hFactor;
char shapeNum;
double* visibleShape;
int xmin, xmax, ymin, ymax;
Hyp(int xx, int yy, double ww, double hh, char s): x(xx), y(yy), wFactor(ww), hFactor(hh), shapeNum(s) {visibleShape=0;shapeNum=-1;};
//Copy constructor necessary for support of vector::push_back() with visibleShape
Hyp(const Hyp &other)
{
x = other.x;
y = other.y;
wFactor = other.wFactor;
hFactor = other.hFactor;
shapeNum = other.shapeNum;
xmin = other.xmin;
xmax = other.xmax;
ymin = other.ymin;
ymax = other.ymax;
int visShapeSize = (xmax-xmin+1)*(ymax-ymin+1);
visibleShape = new double[visShapeSize];
for (int ind=0; ind<visShapeSize; ind++)
{
visibleShape[ind] = other.visibleShape[ind];
}
};
~Hyp(){delete[] visibleShape;};
};
When I create a Hyp object, allocate/write memory to visibleShape and add the object to a vector with vector::push_back, everything works as expected: the data pointed by visibleShape is copied using the copy-constructor.
But when I use vector::erase to remove a Hyp from the vector, the other elements are moved correctly EXCEPT the pointer members visibleShape that are now pointing to wrong addresses! How to avoid this problem? Am I missing something?
| I think you're missing an overloaded assignment operator for Hyp.
|
2,677,785 | 2,677,800 | Visual Studio 2010 Linker Finding Multiply Defined Symbols (Where It Shouldn't) | I've just started with C++, and maybe there's something that I'm doing wrong here, but I'm at a loss. When I try to build the solution, I get 4 LNK2005 errors like this one:
error LNK2005: "public: double __thiscall Point::GetX(void)const " (?GetX@Point@@QBENXZ) already defined in CppSandbox.obj
(there's one for each get/set method, and they all allegedly occur in Point.obj)
And then finally this error:
error LNK1169: one or more multiply defined symbols found
Which reportedly occurs in CppSandbox.exe. I'm not sure what causes this error - it appears to happen when I build or rebuild the solution... Really at a loss, to be honest.
The three files below are the entirety of what I added to the default VS2010 blank project (they're copied in their entirety). Thanks for any help you can offer.
Point.h
class Point
{
public:
Point()
{
x = 0;
y = 0;
};
Point(double xv, double yv)
{
x = xv;
y = yv;
};
double GetX() const;
void SetX(double nval);
double GetY() const;
void SetY(double nval);
bool operator==(const Point &other)
{
return GetX() == other.GetX() && GetY() == other.GetY();
}
bool operator!=(const Point &other)
{
return !(*this == other);
}
private:
double x;
double y;
};
Point.cpp
#include "Point.h"
double Point::GetX() const
{
return x;
}
double Point::GetY() const
{
return y;
}
void Point::SetX(double nv)
{
x = nv;
}
void Point::SetY(double nv)
{
y = nv;
}
CppSandbox.cpp
// CppSandbox.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "Point.cpp"
int main()
{
Point p(1, 2);
Point q(1, 2);
Point r(2, 3);
if (p == q) std::cout << "P == Q";
if (q == p) std::cout << "Equality is commutative";
if (p == r || q == r) std::cout << "Equality is broken";
return 0;
}
| The problem is in CppSandbox.cpp:
#include "Point.cpp"
You are including the cpp file instead of the header file, so its contents are compiled twice and everything in it is therefore defined twice. (It's compiled once when Point.cpp is compiled, and a second time when CppSandbox.cpp is compiled.)
You should include the header file in CppSandbox.cpp:
#include "Point.h"
Your header file should also have include guards.
|
2,677,851 | 3,669,030 | Open-source projects using C++ and XML data binding | I'm looking for open-source projects that make use of two things: (1) C++ and (2) XML data binding. For those who don't know, data binding tools make use of XML schema and code generators such as Codesynthesis xsd, Liquid Technologies. I know CIAO/DAnCE project, an implementation of CORBA Component Model that uses XML Schema Compiler (XSC) but I'm hoping to find more.
| I have tried http://www.codesynthesis.com/products/xsd/ a few months back and I thought the resulting C++ interface was pretty clean. (It's style is similar to STL / boost APIs)
Other than that the gSOAP toolkit appears to have something too. ( http://www.cs.fsu.edu/~engelen/soapdoc2.html#tth_sEc1.4 )
|
2,677,907 | 2,677,947 | Invalid conversion from int to int** C++ | Not sure why I'm getting this error. I have the following:
int* arr = new int[25];
int* foo(){
int* i;
cout << "Enter an integer:";
cin >> *i;
return i;
}
void test(int** myInt){
*myInt = foo();
}
This call here is where I get the error:
test(arr[0]); //here i get invalid conversion from int to int**
| The way you've written it, test takes a pointer to a pointer to an int, but arr[0] is just an int.
However, in foo you are prompting for an int, but reading into a location that is the value of an uninitialized pointer. I'd have thought you want foo to read and return and int.
E.g.
int foo() {
int i;
cout << "Enter an integer:";
cin >> i;
return i;
}
In this case it would make sense for test to take a pointer to an int (i.e. void test(int* myInt)).
Then you could pass it a pointer to one of the int that you dynamically allocate.
test(&arr[0]);
|
2,677,913 | 2,680,055 | How would I go about sharing variables in a C++ class with Lua? | I'm fairly new to Lua, I've been working on trying to implement Lua scripting for logic in a Game Engine I'm putting together. I've had no trouble so far getting Lua up and running through the engine, and I'm able to call Lua functions from C and C functions from Lua.
The way the engine works now, each Object class contains a set of variables that the engine can quickly iterate over to draw or process for physics. While game objects all need to access and manipulate these variables in order for the Game Engine itself to see any changes, they are free to create their own variables, a Lua is exceedingly flexible about this so I don't forsee any issues.
Anyway, currently the Game Engine side of things are sitting in C land, and I really want them to stay there for performance reasons. So in an ideal world, when spawning a new game object, I'd need to be able to give Lua read/write access to this standard set of variables as part of the Lua object's base class, which its game logic could then proceed to run wild with.
So far, I'm keeping two separate tables of objects in place-- Lua spawns a new game object which adds itself to a numerically indexed global table of objects, and then proceeds to call a C++ function, which creates a new GameObject class and registers the Lua index (an int) with the class. So far so good, C++ functions can now see the Lua object and easily perform operations or call functions in Lua land using dostring.
What I need to do now is take the C++ variables, part of the GameObject class, and expose them to Lua, and this is where google is failing me. I've encountered a very nice method here which details the process using tags, but I've read that this method is deprecated in favor of metatables.
What is the ideal way to accomplish this? Is it worth the hassle of learning how to pass class definitions around using libBind or some equivalent method, or is there a simple way I can just register each variable (once, at spawn time) with the global lua object? What's the "current" best way to do this, as of Lua 5.1.4?
| One approach is to use
a lightuserdata pointing to the C++ variable
a C function to access the C++ variable using the lightuserdata
keep the lightuserdata as an upvalue of the C function so one function suffices for all variables
use the number of arguments to the function to select between getting and setting the variable
For example:
int game_state_var_accessor (lua_State *L)
{
int *p = lua_topointer(L, lua_upvalueindex(1));
if (lua_gettop(L) == 0)
{ // stack empty, so get
lua_pushinteger(L, *p);
return 1;
}
else
{ // arg provided, so set
*p = lua_tointeger(L,1);
return 0;
}
}
When you make a new game state you can create accessors for each variable using:
lua_pushlightuserdata(L, (int *)p); // where p points to your variable
lua_pushcclosure(L, game_state_var_accessor, 1);
The accessor is now on the stack and can be bound to a global name, or to the name of a method in a Lua class. If your Lua class table is on the stack at index t this would be:
lua_setfield(L, t, "name_of_accessor");
|
2,677,990 | 2,678,096 | Explain ML type inference to a C++ programmer | How does ML perform the type inference in the following function definition:
let add a b = a + b
Is it like C++ templates where no type-checking is performed until the point of template instantiation after which if the type supports the necessary operations, the function works or else a compilation error is thrown ?
i.e. for example, the following function template
template <typename NumType>
NumType add(NumType a, NumType b) {
return a + b;
}
will work for
add<int>(23, 11);
but won't work for
add<ostream>(cout, fout);
Is what I am guessing is correct or ML type inference works differently?
PS: Sorry for my poor English; it's not my native language.
| I suggest you have a look at this article: What is Hindley-Milner? (and why is it cool)
Here is the simplest example they use to explain type inference (it's not ML, but the idea is the same):
def foo(s: String) = s.length
// note: no explicit types
def bar(x, y) = foo(x) + y
Just looking at the definition of bar, we can easily see that its type must be (String, Int)=>Int. That's type inference in a nutshell. Read the whole article for more information and examples.
I'm not a C++ expert, but I think templates are something else that is closer to genericity/parametricity, which is something different.
|
2,678,175 | 2,678,191 | Iterator to last element in std::list | #include <list>
using std::list;
int main()
{
list <int> n;
n.push_back(1);
n.push_back(2);
n.push_back(3);
list <int>::iterator iter = n.begin();
std::advance(iter, n.size() - 1); //iter is set to last element
}
is there any other way to have an iter to the last element in list?
| Yes, you can go one back from the end. (Assuming that you know that the list isn't empty.)
std::list<int>::iterator i = n.end();
--i;
|
2,678,254 | 2,678,305 | Technical reasons for names containing underscores? | Are there any technical reasons for the use of the underscore in names like (for example) scoped_lock in the Boost library? Why not call it `ScopedLock?
Please note I am not asking about stylistic reasons.
| From the Boost Library Requirements and Guidelines,
Given the intent to propose portions of boost for the next revision of the C++ standard library, boost decided to follow the standard library's conventions.
|
2,678,316 | 2,678,333 | How to call a bool function | I did not see anything that address my particular code problem.
I have a bool function in a class; the bool function is named:
bool Triplet::operator ==(const Triplet& operand)const {
if( (data[0] == operand.data[0]) &&
(data[1] == operand.data[1]) &&
(data[2] == operand.data[2]))
return true;
...
And I am trying to call it in Main but having problems just getting the call right. Apparently if I leave out any thing in the wording it gives an error that I have too few aruguments and if I try to use the entire wording of the function, I get the error that I need a semi-colon, but I already have a semi-colon at the end of the call, so I know that something else is wrong and I simply cannot figure out what is wrong!
Any help would be appreciated!
Thanks in advance.
| That is a C++ operator overload, it is designed so it can change the behaviour of the normal operator:
Triplet a, b;
if (a == b) // calls Triplet::operator==()
If you really want to, you can call the operator by name:
if (a.operator==(b))
|
2,678,423 | 2,678,502 | Why two subprocesses created by Java behave differently? | I use Java Runtime.getRuntime().exec(command) to create a subprocess and print its pid as follows:
public static void main(String[] args) {
Process p2;
try {
p2 = Runtime.getRuntime().exec(cmd);
Field f2 = p2.getClass().getDeclaredField("pid");
f2.setAccessible(true);
System.out.println( f2.get( p2 ) );
} catch (Exception ie)
{
System.out.println("Yikes, you are not supposed to be here");
}
}
I tried both C++ executable and Java executable (.jar file). Both executables will continuously print out "Hello World" to stdout.
When cmd is the C++ executable, the pid is printed out to console but the subprocess gets killed as soon as main() returns. However, when I call the .jar executable in cmd, the subprocess does not get killed, which is the desired behavior.
I don't understand why same Java code, with different executables can behave so differently. How should I modify my code so that I could have persistent subprocesses in Java?
PS: I am using Ubuntu 9.10 and OpenJDK-1.6. (Not sure if they matters~)
Newbie in this field. Any suggestion is welcomed.
Lily
| The C++ EXE is almost certainly marked as a console app. I'm thinking a jar would be considered a GUI app by default, and would do the standard detach-from-the-main-process thing.
If you were to take the C++ code and turn it into a GUI app, i think you'd see it behave similarly to the jar.
|
2,678,463 | 2,680,430 | How to find dynamically loaded modules (the static ones) programatically in windows | I'm trying to port the unix utility ldd to windows, because dependency walker and cygcheck don't quite give me the usage I'm looking for. (also for the learning experience)
Ive been looking all over MSDN, for a windows API that lists dll dependencies of an executable, or even the storage format in the complied exe (just to filter it out), but I've been unable to find anything.
If anyone knows what API call windows uses for listing modules to load, or what patterns I can search for in an executable to find modules to load, please help me out
:)
thanks!
-note: I'm not looking to profile for dynamic modules, just list the ones that are required at runtime
| Modules loaded with loadlibrary api cannot be found in the exe imports table. So to trace those module we have to use one of the several api monitoring tools.
http://www.rohitab.com/apimonitor
www.apimonitor.com
If that is not the case you can simply get all the imports from
dumpbin /import abc.exe
(i am not exactly sure about the command line syntax)
dumpbin is a tool from windows sdk (visual studio also contains it)
|
2,678,476 | 2,687,246 | Boost::Container::Vector with Enum Template Argument - Not Legal Base Class | I'm using Visual Studio 2008 with the Boost v1.42.0 library. If I use an enum as the template argument, I get a compile error when adding a value using push_back(). The compiler error is: 'T': is not a legal base class and the location of the error is move.hpp line 79.
#include <boost/interprocess/containers/vector.hpp>
class Test {
public:
enum Types {
Unknown = 0,
First = 1,
Second = 2,
Third = 3
};
typedef boost::container::vector<Types> TypesVector;
};
int main() {
Test::TypesVector o;
o.push_back(Test::First);
return 0;
}
If I use a std::vector instead it works. And if I resize the Boost version first and then set the values using the [] operator it also works.
Is there some way to make this work using push_back()?
Template backtrace of the error:
error C2516: 'T' : is not a legal base class
1> main.cpp(21) : see declaration of 'T'
1> main.cpp(21) : see reference to class template instantiation 'boost::interprocess::rv' being compiled
1> with
1> [
1> T=Test::Types
1> ]
| I think you have find really a bug. I have posted to the Boost ML to track the issue and try to have more info.
For the moment the single workaround I see is to specialize the rv class as follows, but I'm not sure this will work on all the cases.
namespace boost {
namespace interprocess {
template <>
class rv<Test::Types>
{
Test::Types v;
rv();
~rv();
rv(rv const&);
void operator=(rv const&);
operator Test::Types() const {return v;}
};
}}
If this do not works you can try using int instead of enum.
enum {
Unknown = 0,
First = 1,
Second = 2,
Third = 3
};
typedef int Types;
Of course this has the drawback to loss the enum safety.
|
2,678,665 | 2,681,510 | g_signal_connect error invalid use of member | I'm trying to compile some code and I'm getting the following error:
error: invalid use of member (did you forget the ‘&’ ?)
This is coming from the g_signal_connect call:
g_signal_connect ((gpointer) Drawing_Area_CPU, "expose-event",
G_CALLBACK (graph_expose), NULL);
Drawing_Area_CPU is a GtkWidget * and graph_expose is defined as:
gboolean graph_expose(GtkWidget *widget, GdkEventExpose *event, gpointer data);
So far as i can tell im doing everything right, but still i get this error. Can anyone help please?
UPDATE:
Sorry guys, i got confused, my graph_expose function is in a class, and I'm trying to do the g_signal_connects from the constructor of that class, would that affect this problem in any way?
| As GTK+ is written in plain C, callbacks have to be either plain functions or static methods, so if you want to be able to use class methods as callbacks, you must use some kind of static proxy method:
class foo {
foo () {
g_signal_connect (GtkWidget *widget, GdkEventExpose *event,
G_CALLBACK (foo::graph_expose_proxy), this);
}
gboolean graph_expose (GtkWidget *widget, GdkEventExpose *event) {
// sth
}
static gboolean graph_expose_proxy (GtkWidget *widget, GdkEventExpose *event, gpointer data) {
foo *_this = static_cast<foo*>(data);
return _this->graph_expose (widget, event);
}
}
Or, alternatively, you could use GTKmm, which is C++ binding for GTK+.
|
2,678,711 | 2,678,846 | Vector Troubles in C++ | I am currently working on a project that deals with a vector of objects of a People class. The program compiles and runs just fine, but when I use the debugger it dies when trying to do anything with the PersonWrangler object. I currently have 3 different classes, one for the person, a personwrangler which handles all of the people collectively, and a game class that handles the game input and output.
Edit: My basic question is to understand why it is dying when it calls outputPeople. Also I would like to understand why my program works exactly as it should unless I use the debugger. The outputPeople function works the way I intended that way.
Edit 2: The callstack has 3 bad calls which are:
std::vector >::begin(this=0xbaadf00d)
std::vector >::size(this=0xbaadf00d)
PersonWrangler::outputPeople(this=0xbaadf00d)
Relevant code:
class Game
{
public:
Game();
void gameLoop();
void menu();
void setStatus(bool inputStatus);
bool getStatus();
PersonWrangler* hal;
private:
bool status;
};
which calls outputPeople where it promptly dies from a baadf00d error.
void Game::menu()
{
hal->outputPeople();
}
where hal is an object of PersonWrangler type
class PersonWrangler
{
public:
PersonWrangler(int inputStartingNum);
void outputPeople();
vector<Person*> peopleVector;
vector<Person*>::iterator personIterator;
int totalPeople;
};
and the outputPeople function is defined as
void PersonWrangler::outputPeople()
{
int totalConnections = 0;
cout << " Total People:" << peopleVector.size() << endl;
for (unsigned int i = 0;i < peopleVector.size();i++)
{
sort(peopleVector[i]->connectionsVector.begin(),peopleVector[i]->connectionsVector.end());
peopleVector[i]->connectionsVector.erase( unique (peopleVector[i]->connectionsVector.begin(),peopleVector[i]->connectionsVector.end()),peopleVector[i]->connectionsVector.end());
peopleVector[i]->outputPerson();
totalConnections+=peopleVector[i]->connectionsVector.size();
}
cout << "Total connections:" << totalConnections/2 << endl;
}
Where hal is initialized
Game::Game()
{
PersonWrangler* hal = new PersonWrangler(inputStartingNum);
}
| 0xBAADFOOD is a magic number to alert you to the fact that you're dealing with uninitialized memory. From the stack trace, we see that this in PersonWrangler::outputPeople is invalid. Thus hal doesn't point to a valid PersonWrangler (that is, assuming frame 4 is a call to Game::menu). To resolve this sort of thing yourself, step through the code, starting at Game::Game(), examining Game::hal as you go, to see what might be going wrong.
In Game::Game, hal is a local variable that shadows Game::hal. When Game::Game exits, this hal goes out of scope and leaks memory, while Game::hal remains uninitialized. What you want is:
Game::Game()
{
hal = new PersonWrangler(inputStartingNum);
}
Debuggers fill uninitialized memory with magic numbers to make it easier to spot errors. In a production build, memory isn't filled with anything in particular; the content of uninitialized memory is undefined, and might hold valid values. This is why a production build might not fail when a debug build will.
|
2,678,718 | 2,679,581 | How do I build a filtered_streambuf based on basic_streambuf? | I have a project that requires me to insert a filter into a stream so that outgoing data will be modified according to the filter. After some research, it seems that what I want to do is create a filtered_streambuf like this:
template <class StreamBuf>
class filtered_streambuf: public StreamBuf
{ ... }
And then insert a filtered_streambuf<> into whichever stream I need to be filtered. My problem is that I don't know what invariants I need to maintain while filtering a stream, in order to ensure that
Derived classes can work as expected. In particular, I may find I have filtered_streambufs built over other filtered_streambufs.
All the various stream inserters, extractors and manipulators work as expected.
The trouble is that I just can't seem to work out what the minimal interface is that I need to supply in order to guarantee that an iostream will have what it needs to work correctly.
In particular, do I need to fake the movement of the protected pointer variables, or not? Do I need a fake data buffer, or not? Can I just override the public functions, rewriting them in terms of the base streambuf, or is that too simplistic?
| Boost.Iostreams may be useful to you.
From the documentation:
Boost.Iostreams has three aims:
To make it easy to create standard C++ streams and stream buffers for
accessing new Sources and Sinks.
To provide a framework for defining Filters and attaching them to standard
streams and stream buffers.
To provide a collection of ready-to-use Filters, Sources and
Sinks.
I've barely used that libary myself, so I can't comment any further.
|
2,678,882 | 2,678,934 | Why are there defined constants and declared constants in CPP? | Why are there two ways to "declare" constants in CPP?
Which is better, or should I write, which of them should I use when?
#define MYCON 100
const int MYCON=100
| Short rule: For conditional compilation (like different code fragments for DEBUG and RELEASE) use #define. For all other cases use const construction.
|
2,678,998 | 2,679,358 | Fonts in a multi-platform environment | What is the best way to deal with fonts in a multi-platform distributed system? If I want to use a common font across all systems to show to the user, what's the best way to do this. From the little I've been reading each platform looks to have fonts that are of the same family (ie serif, sans-serif) but with different names. CSS looks to have the functionality baked in where it will make the best selection it can of font on the users machine. Is there similar functionality either in system libraries or external libraries for Windows & Linux. I'm using C++ mainly?
Can someone point me in the right direction for documentation as well?
Thanks
| fontconfig is a cross-platform library for finding fonts by either direct name (Times Roman) or common aliases like serif - it's what most modern Linux software, like the GNOME & KDE desktops, use to find fonts, and is used in conjunction with libraries like Pango for text layout and FreeType for font rasterizing.
|
2,679,056 | 2,679,073 | get error when i try to open file using specific path | i get errors when i try to open a file using the file path
out_stream5.open("C:pathshowitems.txt", ios::out);
warning C4129: 'o' : unrecognized character escape sequence
error C2100: illegal indirection
| I presume you're working on Windows. The problem is probably that you need to escape the backslashes:
out_stream5.open("C:\\path\\showitems.txt", ios::out);
|
2,679,182 | 2,679,202 | Have macro 'return' a value | I'm using a macro and I think it works fine -
#define CStrNullLastNL(str) {char* nl=strrchr(str,'\n'); if(nl){*nl=0;}}
So it works to zero out the last newline in a string, really its used to chop off the linebreak when it gets left on by fgets.
So, I'm wondering if I can "return" a value from the macro, so it can be called like
func( CStrNullLastNL( cstr ) ) ;
Or will I have to write a function
| For a macro to "return a value", the macro itself has to be an expression. Your macro is a statement block, which cannot evaluate to an expression.
You really ought to write an inline function. It will be just as fast and far more maintainable.
|
2,679,274 | 2,679,285 | Simple matrix example using C++ template class | I am trying to write a trivial Matrix class, using C++ templates in an attempt to brush up my C++, and also to explain something to a fellow coder.
This is what I have som far:
template class<T>
class Matrix
{
public:
Matrix(const unsigned int rows, const unsigned int cols);
Matrix(const Matrix& m);
Matrix& operator=(const Matrix& m);
~Matrix();
unsigned int getNumRows() const;
unsigned int getNumCols() const;
template <class T> T getCellValue(unsigned int row, unsigned col) const;
template <class T> void setCellValue(unsigned int row, unsigned col, T value) const;
private:
// Note: intentionally NOT using smart pointers here ...
T * m_values;
};
template<class T> inline T Matrix::getCellValue(unsigned int row, unsigned col) const
{
}
template<class T> inline void Matrix::setCellValue(unsigned int row, unsigned col, T value)
{
}
I'm stuck on the ctor, since I need to allocate a new[] T, it seems like it needs to be a template method - however, I'm not sure I have come accross a templated ctor before.
How can I implemnt the ctor?
| You can access T in the constructor, so the constructor itself needs not be a template. For example:
Matrix::Matrix(const unsigned int rows, const unsigned int cols)
{
m_values = new T[rows * columns];
}
Consider using a smart pointer, like boost::scoped_array or std::vector for the array to make resource management a bit easier.
If your matrix has a fixed size, another option would be to take the rows and columns as template parameters along with T:
template <class T, unsigned Rows, unsigned Columns>
class Matrix
{
T m_values[Rows * Columns];
};
The biggest advantage is the size is then part of the type of a matrix, which can be useful for enforcing rules at compile-time, for example, ensuring two matrices are of compatible sizes when doing matrix multiplication. It also doesn't require the array to be dynamically allocated, which makes resource management a bit easier.
The biggest disadvantage is that you can't change the size of the matrix, so it may not work for what you need.
|
2,679,465 | 2,679,493 | mmap() for large file I/O? | I'm creating a utility in C++ to be run on Linux which can convert videos to a proprietary format. The video frames are very large (up to 16 megapixels), and we need to be able to seek directly to exact frame numbers, so our file format uses libz to compress each frame individually, and append the compressed data onto a file. Once all frames are finished being written, a journal which includes meta data for each frame (including their file offsets and sizes) is written to the end of the file.
I'm currently using ifstream and ofstream to do the file i/o, but I am looking to optimize as much as possible. I've heard that mmap() can increase performance in a lot of cases, and I'm wondering if mine is one of them. Our files will be in the tens to hundreds of gigabytes, and although writing will always be done sequentially, random access reads should be done in constant time. Any thoughts as to whether I should investigate this further, and if so does anyone have any tips for things to look out for?
Thanks!
| On a 32-bit machine your process is limited to 2-3 GB of user address space. This means that (allowing for other memory use) you won't be able to map more than ~1 GB of your file at a time. This does NOT mean that you cannot use mmap() for very large files - just that you need to map only part of the file at a time.
That being said, mmap() can still be a large win for large files. The most significant advantage is that you don't waste memory for keeping the data TWICE - one copy in the system cache, one copy in a private buffer of your application - and CPU time to make those copies. It can be an even more major speedup for random access - but the "random" part must be limited in range to your current mapping(s).
|
2,679,467 | 2,679,510 | C++0x optimizing compiler quality | I do some heavy numbercrunching and for me floating-point performance is very important.
I like performance of Intel compiler very much and quite content with quality of assembly it produces.
I am thinking at some point to try C++0x mainly for sugar parts, like auto, initializer list, etc, but also lambdas. at this point I use those features in regular C++ by the means of boost.
How good of assembly code do compilers C++0x generate? specifically Intel and gcc compilers.
Do they produce SSE code? is performance comparable to C++? are there any benchmarks?
My Google search did not reveal much.
Thank you.
ps: at some point am going to test it myself but would like to know what to expect relative to C++.
| You can expect the same optimization for your code, because the compiler certainly didn't get worse at optimizing. So only using the new C++0x features might impact it. But I doubt your core routines would suddenly be completely changed to somehow use C++0x-only features.
Keep in mind things like auto and lambda are just syntactic sugar. That will have no effect on compiler optimization because they're just methods of generating the same code you would anyway. So you'd only need to worry about the new "stuff" like initializer lists. But I'd be surprised if that was inefficient as well.
You should also expect many improvements, because of move-semantics. No longer must you copy data around but merely move it around. Design your code to take advantage of this for most benefit.
|
2,679,515 | 2,679,525 | visual studio 2005 to 2010 with boost | About a month a go I spent almost an entire week trying to figure out how to build the boost libraries for vs2005 and today I updated to vs2010.
Do I need to remove boost for vs 2005(I uninstalled vs2005) and go through the build process for 2010 or will it magically work and I can go take a nap?
| You need to rebuild Boost for the new version of Visual C++.
I don't believe anyone has released a binary distribution for Visual C++ 2010 yet. The BoostPro site would be the best place to get a binary distribution, and they don't have them yet.
It shouldn't be too difficult to build Boost if you follow the instructions in the Boost Getting Started Guide.
Whether or not you take a nap is up to you. If you build Boost from source, you may as well take one since the build is rather lengthy.
|
2,679,680 | 2,679,688 | Getting window style | I'm trying to check if a window has a certain style using GetWindowLong(hWnd, GWL_STYLE) but that gives me a LONG type of variable. how would you check for a specific style from that say a const value type 'WS_CAPTION'?
| use the bitwise & operator to compare with that long type,
example
if (szLng & WS_CAPTION){
// that window has caption
}
|
2,679,717 | 2,679,794 | Version of STL optimized for compile time? | I'm looking for a variant of the STL (it's okay if it doesn't have all the functionality) that's optimized for short compile times -- I get bothered by long compile times that delay my compile-debug-edit cycle.
I'm mainly interested in the containers of the STL: vector/map, and not so much the algorithms.
Thanks!
| Take a look at your compiler's options for precompiled headers. In GCC, for example, passing a header as if it is a source causes it to be precompiled.
It reduced time significantly for my little test, but only if you don't count the time spent precompiling:
Shadow:code dkrauss$ ls maps*
maps.cpp maps.h maps2.cpp
Shadow:code dkrauss$ cat maps*
#include "maps.h"
using namespace std;
map<int,int> ints;
map<string, string> strings;
map<int, string> is;
map<string, int> si;
int main() {
bang(ints);
bang(strings);
bang(is);
bang(si);
extern void more();
more();
}
#include <string>
#include <map>
template< class K, class V >
void bang( std::map<K,V> &v ) {
v[ K() ] = V();
v.erase( v.begin() );
}
#include "maps.h"
using namespace std;
map<int,int> ints2;
map<string, string> strings2;
map<int, string> is2;
map<string, int> si2;
void more() {
bang(ints2);
bang(strings2);
bang(is2);
bang(si2);
}
Shadow:code dkrauss$ time g++ maps*.cpp -o maps
real 0m1.091s
user 0m0.857s
sys 0m0.132s
Shadow:code dkrauss$ time g++ maps.h
real 0m0.952s
user 0m0.406s
sys 0m0.110s
Shadow:code dkrauss$ ls maps*
maps maps.cpp maps.h maps.h.gch maps2.cpp
Shadow:code dkrauss$ time g++ maps*.cpp -o maps
real 0m0.718s
user 0m0.552s
sys 0m0.095s
Shadow:code dkrauss$
|
2,679,844 | 2,679,856 | Is it bad practice to use multi-dimensional arrays in C/C++? | Some programmers seem to violently hate them, while others seem to think they're fine. I know that anything that can be done to a multi-dimensional array can also be done to a regular array, so they're functionally equivalent. Is it bad practice to use multi-dimensional arrays, or does it not matter?
| Do you need to store multi-dimensional data where you know the dimensions ahead of time? If so, use a multi-dimensional array.
If you don't know the dimensions ahead of time (i.e., you're going to have to dynamically allocate the array), then you either need to either
allocate a one-dimensional array and emulate an n-dimensional array using index arithmetic, or
allocate an array of pointers to arrays of elements to get actual multidimensional array semantics
It depends on the specific use case, but as a rule of thumb, I almost always prefer the former because it makes for less memory management hassle and fewer heap allocations. The complexity for both approaches grows as the number of dimensions increases, but, in my opinion, it grows much faster for the latter approach due to the extra levels of indirection.
|
2,679,885 | 2,679,905 | Using pthread in c++ | I am using pthread.h in a *.cc file. when I try to use pthread_exit(0); or pthread_join(mythrds[yy],NULL); it says:
.cc:(.text+0x3e): undefined reference to `pthread_exit'
when complied very similar code in a *.c file with gcc it work perfect. How Can I use pthread's in c++.. (I also added -lpthread)
..
void *myThreads ( void *ptr )
{
...
pthread_exit(0);
}
..
flags:
g++ -lpthread -Wall -static -W -O9 -funroll-all-loops -finline -ffast-math
| You might try using the -pthread option to g++.
-pthread
Adds support for multithreading with the pthreads library. This
option sets flags for both the preprocessor and linker.
|
2,679,964 | 2,679,985 | C++ unicode UTF-16 encoding | I have a wide char string is L"hao123--我的上网主页", and it must be encoded to "hao123--\u6211\u7684\u4E0A\u7F51\u4E3B\u9875". I was told that the encoded string is a special “%uNNNN” format for encoding Unicode UTF-16 code points. In this website, it tells me it's JavaScript escapes. But I don't know how to encode it with C++.
It there any library to get this to work? or give me some tips.
Thanks my friends!
| Embedding unicode in string literals is generally not a good idea and is not portable; there is no guarantee that wchar_t will be 16 bits and that the encoding will be UTF-16. While this may be the case on Windows with Microsoft Visual C++ (a particular C++ implementation), wchar_t is 32 bits on OS X's GCC (another implementation). If you have some sort of localized string constants, it's best to use a configuration file in some particular encoding and to interpret them as having been encoded in that encoding. The International Components for Unicode (ICU) library provides pretty good support for interpreting and handling unicode. Another good library for converting between (but not interpreting) encoding formats is libiconv.
Edit
It is possible I am misinterpreting your question... if the problem is that you have a string in UTF-16 already, and you want to convert it to "unicode-escape ASCII" (i.e. an ASCII string where unicode characters are represented by "\u" followed by the numeric value of the character), then use the following pseudo-code:
for each codepoint represented by the UTF-16 encoded string:
if the codepoint is in the range [0,0x7F]:
emit the codepoint casted to a char
else:
emit "\u" followed by the hexadecimal digits representing codepoint
Now, to get the codepoint, there is a very simple rule... each element in the UTF-16 string is a codepoint, unless it is part of a "surrogate pair", in which case it and the element after it comprise a single codepoint. If so, then the unicode standard defines an procedure for combinging the "leading surrogate" and the "trailing surrogate" into a single code point. Note that UTF-8 and UTF-16 are both variable-length encodings... a code point requires 32 bits if not represented with variable length. The Unicode Transformation Format (UTF) FAQ explains the encoding as well as how to identify surrogate pairs and how to combine them into codepoints.
|
2,679,967 | 2,679,992 | boost::shared_ptr in Objective-C++ | This is a better understanding of a question I had earlier.
I have the following Objective-C++ object
@interface OCPP
{
MyCppobj * cppobj;
}
@end
@implementation OCPP
-(OCPP *) init
{
cppobj = new MyCppobj;
}
@end
Then I create a completely differently obj which needs to use cppobj in a boost::shared_ptr (I have no choice in this matter, it's part of a huge library which I cannot change)
@interface NOBJ
-(void) use_cppobj_as_shared_ptr
{
//get an OCPP obj called occ from somewhere..
//troubling line here
}
@end
I have tried the following and that failed: I tried synthesising cppobj. Then I created a shared_ptr in "troubling line" in the following way:
MyCppobj * cpp = [occ cppobj];
bsp = boost::shared_ptr<MyCppobj>(cpp);
It works fine first time around. Then I destroy the NOBJ and recreate it. When I for cppobj it's gone. Presumably shared_ptr decided it's no longer needed and did away with it.
So I need help. How can I keep cppobj alive?
Is there a way to destroy bsp (or it's reference to cppobj) without destroying cppobj?
| shared_ptr supports custom deallocators. What you can do, is, do nothing.
void no_destroy(MyCppObj*)
{}
bsp = boost::shared_ptr<MyCppObj>(cpp, &no_destroy);
|
2,679,979 | 2,680,110 | C++ Event (Focus) Handling | Due to comments I added the following code
(in BasicPanel)
Connect(CTRL_ONE, wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Connect(CTRL_TWO,wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Connect(CTRL_THREE, wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Connect(CTRL_FOUR, wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Connect(CTRL_FIVE, wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
(enums)
CTRL_NAME = wxID_HIGHEST + 5, // 6004
CTRL_ADDRESS = wxID_HIGHEST + 6, // 6005
CTRL_PHONENUMBER = wxID_HIGHEST + 7, // 6006
CTRL_SS = wxID_HIGHEST + 8, // 6007
CTRL_EMPNUMBER = wxID_HIGHEST + 9 // 6008
(The OnKillFocus Function - the declaration is included as suggested)
void BasicPanel::OnKillFocus(wxFocusEvent& event) {
switch (event.GetId()) {
case 6004:
...
break;
... ... ...
}
All of these added to the code do nothing when the user changes focus on which text box they are using...
Q1:I am using wxWidgets (C++) and have come accost a problem that i can not locate any help. I have created several wxTextCtrl boxes and would like the program to update the simple calculations in them when the user 'kills the focus.' I could not find any documentation on this subject on the wxWidgets webpage and Googling it only brought up wxPython. The two events i have found are: EVT_COMMAND_KILL_FOCUS - EVT_KILL_FOCUS for neither of which I could find any snippet for. Could anyone give me a short example or lead me to a page that would be helpful?
Q2:Would i have to create an event to handle the focus being killed for each of my 8 wxTextCtrl boxes? In the case that i have to create a different event: How would i get each event to differentiate from each other? I know i will have to create new wxID's for each of the wxTextCtrl boxes but how do I get the correct one to be triggered?
class BasicPanel : public wxPanel { ...
wxTextCtrl* one;
wxTextCtrl* two;
wxTextCtrl* three;
wxTextCtrl* four; ... }
| Okay, first off, here is the code to put in your BasicPanel class:
void OnKillFocus(wxFocusEvent& event);
Then add the following to the end of your BasicPanel constructor:
Connect(ID_TEXTCTRL,
wxEVT_KILL_FOCUS ,
(wxObjectEventFunction)&BasicPanel::OnKillFocus);
You will need to repeat the above code for each text control and replace ID_TEXTCTRL with the actual ID of the controls.
Then the code below will get called whenever one of the controls loses focus.
void BasicPanel::OnKillFocus(wxFocusEvent& event)
{
// code goes here...
}
To determine the ID of the control that generated the event within OnKillFocus, you can use the following:
event.GetId()
|
2,680,103 | 2,680,135 | Is it safe to call a function to initialize a class in a ctor list? | I have Angle class that I want initialized to a random value. The Angle constructor can accept an int from a random() function. Is it safe to place this call in the ctor list:
foo::foo() : Angle(random(0xFFFF)) {...}
or do I have to do it in the body of the constructor?
foo::foo() { Angle = Angle(random(0xFFFF)); ...}
If it matters, the foo class is derived from another class and does have virtual methods. In addition, no exception handling is allowed in our app.
| If random cannot throw (hard to believe that it could), there is no problem with this. Side effects are allowed in constructor initializers. It's good practice to do any initialization there, if it takes only little code.
|
2,680,310 | 2,680,524 | Passing Derived Class Instances as void* to Generic Callbacks in C++ | This is a bit of an involved problem, so I'll do the best I can to explain what's going on. If I miss something, please tell me so I can clarify.
We have a callback system where on one side a module or application provides a "Service" and clients can perform actions with this Service (A very rudimentary IPC, basically). For future reference let's say we have some definitions like so:
typedef int (*callback)(void*); // This is NOT in our code, but makes explaining easier.
installCallback(string serviceName, callback cb); // Really handled by a proper management system
sendMessage(string serviceName, void* arg); // arg = value to pass to callback
This works fine for basic types such as structs or builtins.
We have an MI structure a bit like this:
Device <- Disk <- MyDiskProvider
class Disk : public virtual Device
class MyDiskProvider : public Disk
The provider may be anything from a hardware driver to a bit of glue that handles disk images. The point is that classes inherit Disk.
We have a "service" which is to be notified of all new Disks in the system, and this is where things unravel:
void diskHandler(void *p)
{
Disk *pDisk = reinterpret_cast<Disk*>(p); // Uh oh!
// Remainder is not important
}
SomeDiskProvider::initialise()
{
// Probe hardware, whatever...
// Tell the disk system we're here!
sendMessage("disk-handler", reinterpret_cast<void*>(this)); // Uh oh!
}
The problem is, SomeDiskProvider inherits Disk, but the callback handler can't receive that type (as the callback function pointer must be generic).
Could RTTI and templates help here?
Any suggestions would be greatly appreciated.
| While I am not 100% sure I think static_cast from T* to void* and back to the original pointer type T* should work. As I see it the problem is that reinterpret_cast only changes the type of pointer without altering its actual value and static_cast in case of inheritance should adjust a pointer so that it points to the beginning of the object.
DISCLAIMER: You are on the dark side of the language here and I cannot guarantee it will work at all.
|
2,680,311 | 2,680,987 | Does gcc's STL support rvalue references now? | I know Visual Studio 2010's standard library has been rewritten to support rvalue references, which boosts its performance considerably.
Does the standard library implementation of gcc 4.4 (and above) support rvalue references?
| I found this from the STL of gcc 4.4 :
#ifdef __GXX_EXPERIMENTAL_CXX0X__
_Vector_base(_Vector_base&& __x)
: _M_impl(__x._M_get_Tp_allocator())
{
this->_M_impl._M_start = __x._M_impl._M_start;
this->_M_impl._M_finish = __x._M_impl._M_finish;
this->_M_impl._M_end_of_storage = __x._M_impl._M_end_of_storage;
__x._M_impl._M_start = 0;
__x._M_impl._M_finish = 0;
__x._M_impl._M_end_of_storage = 0;
}
#endif
|
2,680,369 | 2,680,771 | How is inheritance implemented at the memory level? | Suppose I have
class A { public: void print(){cout<<"A"; }};
class B: public A { public: void print(){cout<<"B"; }};
class C: public A { };
How is inheritance implemented at the memory level?
Does C copy print() code to itself or does it have a pointer to the it that points somewhere in A part of the code?
How does the same thing happen when we override the previous definition, for example in B (at the memory level)?
| Compilers are allowed to implement this however they choose. But they generally follow CFront's old implementation.
For classes/objects without inheritance
Consider:
#include <iostream>
class A {
void foo()
{
std::cout << "foo\n";
}
static int bar()
{
return 42;
}
};
A a;
a.foo();
A::bar();
The compiler changes those last three lines into something similar to:
struct A a = <compiler-generated constructor>;
A_foo(a); // the "a" parameter is the "this" pointer, there are not objects as far as
// assembly code is concerned, instead member functions (i.e., methods) are
// simply functions that take a hidden this pointer
A_bar(); // since bar() is static, there is no need to pass the this pointer
Once upon a time I would have guessed that this was handled with pointers-to-functions in each A object created. However, that approach would mean that every A object would contain identical information (pointer to the same function) which would waste a lot of space. It's easy enough for the compiler to take care of these details.
For classes/objects with non-virtual inheritance
Of course, that wasn't really what you asked. But we can extend this to inheritance, and it's what you'd expect:
class B : public A {
void blarg()
{
// who knows, something goes here
}
int bar()
{
return 5;
}
};
B b;
b.blarg();
b.foo();
b.bar();
The compiler turns the last four lines into something like:
struct B b = <compiler-generated constructor>
B_blarg(b);
A_foo(b.A_portion_of_object);
B_bar(b);
Notes on virtual methods
Things get a little trickier when you talk about virtual methods. In that case, each class gets a class-specific array of pointers-to-functions, one such pointer for each virtual function. This array is called the vtable ("virtual table"), and each object created has a pointer to the relevant vtable. Calls to virtual functions are resolved by looking up the correct function to call in the vtable.
|
2,680,892 | 2,681,635 | How do you run your unit tests? Compiler flags? Static libraries? | I'm just getting started with TDD and am curious as to what approaches others take to run their tests. For reference, I am using the google testing framework, but I believe the question is applicable to most other testing frameworks and to languages other than C/C++.
My general approach so far has been to do one of three things:
Write the majority of the application in a static library, then create two executables. One executable is the application itself, while the other is the test runner with all of the tests. Both link to the static library.
Embed the testing code directly into the application itself, and enable or disable the testing code using compiler flags. This is probably the best approach I've used so far, but clutters up the code a bit.
Embed the testing code directly into the application itself, and, given certain command-line switches either run the application itself or run the tests embedded in the application.
None of these solutions are particularly elegant...
How do you do it?
| I tend to favour static libs over dlls so most of my C++ code ends up in static libs anyway and, as you've found, they're as easy to test as dlls.
For code that builds into an exe I either have a separate test project which simply includes the source files that are under test and that are usually built into the exe OR I build a new static lib that contains most of the exe and test that in the same way that I test all of my other static libs. I find that I usually take the 'most code in a library' approach with new projects and the 'pull the source files from the exe project into the test project' approach when I'm retro fitting tests to existing applications.
I don't like your options 2 and 3 at all. Managing the build configurations for 2 is probably harder than having a separate test project that simply pulls in the sources it needs and including all of the tests into the exe as you suggest in 3 is just wrong ;)
|
2,681,337 | 2,681,437 | dynamical binding or switch/case? | A scene like this:
I've different of objects do the similar operation as respective func() implements.
There're 2 kinds of solution for func_manager() to call func() according to different objects
Solution 1: Use virtual function character specified in c++. func_manager works differently accroding to different object point pass in.
class Object{
virtual void func() = 0;
}
class Object_A : public Object{
void func() {};
}
class Object_B : public Object{
void func() {};
}
void func_manager(Object* a)
{
a->func();
}
Solution 2: Use plain switch/case. func_manager works differently accroding to different type pass in
typedef enum _type_t
{
TYPE_A,
TYPE_B
}type_t;
void func_by_a()
{
// do as func() in Object_A
}
void func_by_b()
{
// do as func() in Object_A
}
void func_manager(type_t type)
{
switch(type){
case TYPE_A:
func_by_a();
break;
case TYPE_B:
func_by_b();
default:
break;
}
}
My Question are 2:
1. at the view point of DESIGN PATTERN, which one is better?
2. at the view point of RUNTIME EFFCIENCE, which one is better? Especailly as the kinds of Object increases, may be up to 10-15 total, which one's overhead oversteps the other? I don't know how switch/case implements innerly, just a bunch of if/else?
Thanks very much!
|
from the view point of DESIGN PATTERN, which one is better?
Using polymorphism (Solution 1) is better.
Just one data point: Imagine you have a huge system built around either of the two and then suddenly comes the requirement to add another type. With solution one, you add one derived class, make sure it's instantiated where required, and you're done. With solution 2 you have thousands of switch statements smeared all over the system and it is more or less impossible to guarantee you found all the places where you have to modify them for the new type.
from the view point of RUNTIME EFFCIENCE, which one is better? Especailly as the kinds of Object
That's hard to say.
I remember a footnote in Stanley Lippmann's Inside the C++ Object Model, where he says that studies have shown that virtual functions might have a small advantage against switches over types. I would be hard-pressed, however, to cite chapter and verse, and, IIRC, the advantage didn't seem big enough to make the decision dependent on it.
|
2,681,405 | 2,682,643 | How to detect missing font characters | Is there a way to detect that all characters are displayed properly with the current font? In some environments and fonts certain characters are replaced with a square symbol.
I'd like to automatically verify that all characters used in the GUI are supported by the current font.
| I found a possible solution using the QFontMetrics class. Here is a an example function to query whether all characters are available in the current text of a QLabel:
bool charactersMissing(const QLabel& label) {
QFontMetrics metrics(label.font());
for (int i = 0; i < label.text().size(); ++i) {
if (!metrics.inFont(label.text().at(i))) {
return true;
}
}
return false;
}
Of course displaying to the user which character is missing would be good, but of course that has to be done with a different font :)
|
2,681,446 | 2,683,060 | Howto access thread data outside a thread | Question: I start the MS Text-to-speech engine in a thread, in order to avoid a crash on DLL_attach. It starts fine, and the text to speech engine gets initialized, but I can't access ISpVoice outside the thread. How can I access ISpVoice outside the thread ? It's a global variable after all...
You find XPThreads here:
http://www.codeproject.com/KB/threads/XPThreads.aspx
#include <windows.h>
#include <sapi.h>
#include "XPThreads.h"
ISpVoice * pVoice = NULL;
unsigned long init_engine_thread(void* param)
{
Sleep(5000);
printf("lolthread\n");
//HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
HRESULT hr = CoInitialize(NULL);
if(FAILED(hr) )
{
MessageBox(NULL, TEXT("Failed To Initialize"), TEXT("Error"), 0);
char buffer[2000] ;
sprintf(buffer, "An error occured: 0x%08X.\n", hr);
FILE * pFile = fopen ( "c:\\temp\\CoInitialize_dll.txt" , "w" );
fwrite (buffer , 1 , strlen(buffer) , pFile );
fclose (pFile);
}
else
{
printf("trying to create instance.\n");
//HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice);
//hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice);
//HRESULT hr = CoCreateInstance(__uuidof(ISpVoice), NULL, CLSCTX_INPROC_SERVER, IID_ISpVoice, (void **) &pVoice);
HRESULT hr = CoCreateInstance(__uuidof(SpVoice), NULL, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice);
if( SUCCEEDED( hr ) )
{
printf("Succeeded\n");
hr = pVoice->Speak(L"The text to speech engine has been successfully initialized.", 0, NULL);
}
else
{
printf("failed\n");
MessageBox(NULL, TEXT("Failed To Create COM instance"), TEXT("Error"), 0);
char buffer[2000] ;
sprintf(buffer, "An error occured: 0x%08X.\n", hr);
FILE * pFile = fopen ( "c:\\temp\\CoCreateInstance_dll.txt" , "w" );
fwrite (buffer , 1 , strlen(buffer) , pFile );
fclose (pFile);
}
}
return NULL;
}
XPThreads* ptrThread = new XPThreads(init_engine_thread);
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
//init_engine();
LoadLibrary(TEXT("ole32.dll"));
ptrThread->Run();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
if(pVoice != NULL)
{
pVoice->Release();
pVoice = NULL;
}
CoUninitialize();
break;
}
return TRUE;
}
| Firstly, your problem is that you are expecting the thread that you start when the file's static initialisers are run to have completed whilst your DllMain() is running and yet you're doing nothing to synchronise with it. Of course if you WERE doing something to synchronise with it then you would be falling foul of the problems that were detailed in the link that I posted in response to your other question...
Secondly, COM interface pointers are, generally, thread specific. You can't, generally, obtain one in one thread via CoCreateInstance() or QueryInterface() and then just use it in another thread. To be able to use a use an interface pointer in another thread you need to marshal it to that thread using something like CoMarshalInterface() (see here). But before you can do that you need to make sure that you have initialised COM on the thread and you can't do that for all the reasons that I raised in answer to your previous question.
Thirdly, you have no reason to be calling CoUninitialize() in your DllMain() as a) you have no idea what thread you're being called on and b) you weren't responsible for calling CoInitialize() on that random thread that is owned by the application.
Fourthly, the call to LoadLibrary() is VERY BAD for the reasons pointed out in this link that I posted in answer to your earlier question.
So, in summary, as I said in reply to your other question, you can not do what you want to do in DllMain(). It's not the place to do it. As I stated before, what you COULD do is run up a thread when you get your DLL_PROCESS_ATTACH notification but abide by the rules when you do so so that you don't deadlock and load your COM object in there. You can then ONLY access the interface pointer from that thread and you'll have to do your own marshalling to pass values from the threads that call into your DLL across to your COM thread. Even then there's probably a better way to do what you're doing (such as exposing the whole of whatever it is you're building as it's OWN COM object) but you're not giving enough context for anyone to come up with an answer to the REAL problem that you have.
Oh and finally... The XPThreads thing that you are using is based on the flawed assumption that you HAVE to wait for the thread handle that you get back from CreateThread(), you don't, you could just close it after you create your thread as you're not interested in waiting for it. You might like to take a look at this question to see why you probably shouldn't be using CreateThread() and should, instead, be using _beginthreadex().
|
2,681,490 | 2,681,922 | Invalidate() debug assertion failed message (MFC, VC++) | I've made a custom control, and when I want it to repaint on the screen I call Invalidate(), and afterwards UpdateWindow(), but i get message:
debug assertion failed for a file afxwin2.inl in line 150 which is:
AFXWIN_INLINE void CWnd::Invalidate(BOOL bErase)
{ ASSERT(::IsWindow(m_hWnd)); ::InvalidateRect(m_hWnd, NULL, bErase); }
The thing is that when I run the same app in release mode, it doesn't report any message! So this clue makes me think it's about some environment configuration I should change.
What do you think?
Thanks.
| Well,
ASSERT(::IsWindow(m_hWnd));
is an assertion. Assertions are statements which verify that something is true and kill your program if it's not. They're intended to be used for debugging and development rather than for being in the program once it has been released, so they are normally only compiled in in debug builds. So, it wouldn't be there in a release build, and you wouldn't get the error message. That does not mean that there isn't a problem in the release build. It just means that that it's not running the statement to check whether there's a problem.
I don't know a lot about the error in question, but looking at it,
::IsWindow(m_hWnd)
is obviously false (hence the error message). The documentation for IsWindow() would appear to indicate that the problem is that the window handle in question is not a handle for a valid window. Perhaps it hasn't been created properly, or it has already been destroyed. You'll have to figure out why your window handle is invalid.
A quick google search for "mfc iswindow" brings up this thread on msdn which might be of help to you.
|
2,681,533 | 3,183,287 | How can I determine which dependency would cause a C++ compilation unit to be rebuilt? | I have a legacy C++ application with a deep graph of #includes. Changes to any header file often cause recompiles of seemingly unrelated source files.
The application is built using a Visual Studio 2005 solution (sln) file.
Can MSBUILD be invoked in a way that it reports which dependency(ies) are causing a source file to be recompiled?
Is there any other tool that might be able to help?
NOTE: I'm only looking for a tool to tell me why a file would be rebuilt, not some restrospective magic telling me why it was rebuilt.
| If you dial up the verbosity to detailed or above (Tools>Options>Project>Build or /v:detailed) then MSBuild will log, just before it runs the compiler, exactly what header file or source file caused it to run the compiler.
Is that what you're asking for?
Dan/MSBuild
|
2,681,709 | 2,681,781 | What iterator to return for non-existing map How to signkey? | I want to have a function which searches for a key in a collection of maps and returns an iterator to the found key. But what should be returned in case the key cannot be found? I cannot return map::end since the collection of maps can be empty.
Thanks.
map<string, string>::iterator CConfFile::GetKey(const string &SectionName, const string &KeyName)
{
maps<string, map<string, string> >::const_iterator Section = _Sections.find(SectionName);
if (Section != _Sections.end()) {
map<string, string> &Keys = SectionPtr->second;
map<std::string, string>::const_iterator Key = Keys.find(KeyName);
if (Key != Keys.end())
return Key;
}
cerr << "Key " << KeyName << "not found\n";
return WHAT???;
}
| If you return an iterator, then that implies that one can actually iterate over all the values. If thats indeed the case, you would have to return a custom iterator type anyway and you should have no problem to denote a special end iterator.
If the iterator isn't intended to be used as an iterator, it might be better to return a pointer to the found object, and a null pointer in case there isn't any.
|
2,681,887 | 2,682,084 | writing string into file before calling the close() | I am using ofstream() to write data into file, i want the program to perform such a way that it should be keep on writting the string into the file as soon as the value gets assingned to string variable, and it should be writting before calling the close().
The need is,
I am getting the keystrokes of the keyboard, and i want it to be stored it in to the file... so when ever a key is pressed i want it to be written into the file........
can anyone help me to do that in c++.........
| Call flush() on the ofstream after writing to it. That will cause the output to be actually written instead of being buffered.
|
2,681,890 | 2,682,056 | c++ Array passing dilemma | I am writing a function that takes a string, string pointer and an int.
The function splits the string based on a set of rules and puts each token into an array. I need to return the array out of the function with the number of elements in the int variable etc. I am stuck as to how I return the array as I can not use auto other wise it is destroyed and I am reluctant to use new as I feel this is patchy.
I have other ideas on how to go about this but would like to see how other people go about this first. I could also be wrong and it could be possible to pass an auto out of an array. I can also not use vectors so there goes a copy constructor.
Vector can not be used as this was a challenge set out to me and I was asked not use to templates.
| This is more of a C than a C++ question given those restrictions.
The common C pattern for returning an array is actually to get the caller to pass in an array to fill. This lets the caller decide on the allocation (and hence deallocation).
Your function prototype would look like
int Function(string str1, string_ptr str2, int n, int* pOutArray, int cOutArray);
Where the function returns the number of elements written the pOutArray.
In the implementation you put in handling for pOutArray being NULL, in which case you just count the number of elements, and return that. This lets you call the function in one of several ways depending on your needs :-
int out[5]={0};
int cFilled = Function(s1,s2,x,out,_countof(out));
// Further code can use up to 5<cFilled elements from the array.
or,
int cElt = Function(s1,s2,x,NULL,0);
int* pOut = malloc(sizeof(int)*cElt);
Function(s1,s2,x,pOut,cElt);
// pOut now contains exactly the number of elements extracted.
free(pOut);
|
2,681,959 | 2,716,225 | Problem with "moveable-only types" in VC++ 2010 | I recently installed Visual Studio 2010 Professional RC to try it out and test the few C++0x features that are implemented in VC++ 2010.
I instantiated a std::vector of std::unique_ptr, without any problems. However, when I try to populate it by passing temporaries to push_back, the compiler complains that the copy constructor of unique_ptr is private. I tried inserting an lvalue by moving it, and it works just fine.
#include <utility>
#include <vector>
int main()
{
typedef std::unique_ptr<int> int_ptr;
int_ptr pi(new int(1));
std::vector<int_ptr> vec;
vec.push_back(std::move(pi)); // OK
vec.push_back(int_ptr(new int(2))); // compiler error
}
As it turns out, the problem is neither unique_ptr nor vector::push_back but the way VC++ resolves overloads when dealing with rvalues, as demonstrated by the following code:
struct MoveOnly
{
MoveOnly() {}
MoveOnly(MoveOnly && other) {}
private:
MoveOnly(const MoveOnly & other);
};
void acceptRValue(MoveOnly && mo) {}
int main()
{
acceptRValue(MoveOnly()); // Compiler error
}
The compiler complains that the copy constructor is not accessible. If I make it public, the program compiles (even though the copy constructor is not defined).
Did I misunderstand something about rvalue references, or is it a (possibly known) bug in VC++ 2010 implementation of this feature?
| Unfortunately, /Za is buggy. It performs an elided-copy-constructor-accessibility check when it shouldn't (binding rvalue references doesn't invoke copy constructors, even theoretically). As a result, /Za should not be used.
Stephan T. Lavavej, Visual C++ Libraries Developer (stl@microsoft.com)
|
2,682,063 | 2,682,070 | C++ : Initializing base class constant static variable with different value in derived class? | I have a base class A with a constant static variable a. I need that instances of class B have a different value for the static variable a. How could this be achieved, preferably with static initialization ?
class A {
public:
static const int a;
};
const int A::a = 1;
class B : public A {
// ???
// How to set *a* to a value specific to instances of class B ?
};
| You can't. There is one instance of the static variable that is shared by all derived classes.
|
2,682,708 | 2,683,038 | Exiting from the Middle of an Expression Without Using Exceptions | Solved: I figured out a clean way to do it with setjmp()/longjmp(), requiring only a minimal wrapper like:
int jump(jmp_buf j, int i) { longjmp(j, i); return 0; }
This allows jump() to be used in conditional expressions. So now the code:
if (A == 0) return;
output << "Nonzero.\n";
Is correctly translated to:
return
((A == 0) && jump(caller, 1)),
(output << "Nonzero.\n"),
0;
Where caller is a jmp_buf back to the point of invocation in the calling function. Clean, simple, and efficient to a degree that is far less implementation-defined than exceptions. Thank you for your help!
Is there a way to emulate the use of flow-control constructs in the middle of an expression? Is it possible, in a comma-delimited expression x, y, for y to cause a return?
Edit: I'm working on a compiler for something rather similar to a functional language, and the target language is C++. Everything is an expression in the source language, and the sanest, simplest translation to the destination language leaves as many things expressions as possible. Basically, semicolons in the target language become C++ commas. In-language flow-control constructs have presented no problems thus far; it's only return. I just need a way to prematurely exit a comma-delimited expression, and I'd prefer not to use exceptions unless someone can show me that they don't have excessive overhead in this situation.
The problem of course is that most flow-control constructs are not legal expressions in C++. The only solution I've found so far is something like this:
try {
return
x(), // x();
(1 ? throw Return(0) : 0); // return 0;
} catch (Return& ret) {
return ref.value;
}
The return statement is always there (in the event that a Return construct is not reached), and as such the throw has to be wrapped in ?: to get the compiler to shut up about its void result being used in an expression.
I would really like to avoid using exceptions for flow control, unless in this case it can be shown that no particular overhead is incurred; does throwing an exception cause unwinding or anything here? This code needs to run with reasonable efficiency. I just need a function-level equivalent of exit().
| You may want to research cfront, which is a program from the late 80's/early 90's that translated C++ into C (no templates or exceptions back then), because there were few, if any, native C++ compilers.
The way it handled inline functions is very similar to what you are trying to do: lots of trinary (?:) operators, commas, and parentheses. However, it could not convert an inline function with control flow more complex than if/then, e.g. a for or while loop, to an expression, and would have to implement that function as non-inline.
The only way to "prematurely exit a comma-delimited expression" would be with the trinary operator and parentheses. For example:
(
first thing,
second thing,
test expression?
(
next thing if successful,
another thing,
return value
)
:( // How often can you use an emoticon as an operator, anyway?
something to do if unsuccessful,
more cleanup,
return value
)
)
If the compiler doesn't short-circuit the then and else clauses of the trinary operator, you're out of luck.
|
2,682,760 | 2,683,510 | OpenSSL Bio chains: Clarrification on documentation | The documentation for Openssl memory BIO sinks is here.
I am creating a BIO chain to turn binary strings into base64 strings. The source/sink is always a memory location, and this enables me to just keep the same chain arround. However the data (should) go into a memory buffer managed by OpenSSL when I write to it, and it should come from a user supplied memory buffer when read from the chain.
BIO_set_mem_buf() is the function used to set a user supplied buffer, and I will set the BIO_NOCLOSE property as I manage my memory using new. Now in order to use the same chain for writing I need to change the memory bio into managing its own memory. My question is:
" Will BIO_reset() change it back to managing its own memory after a user has supplied a custom buffer ? Are there any performance consequences of using a single chain for what I want to do ?"
| I'm not sure to get you right but here is how I usually proceed with OpenSSL:
I consider OpenSSL's BIO structures to be some kind of opaque streams.
Whatever data I have to pass to (or get from) OpenSSL, it is usually stored in a custom data structure of my own, then copied to/from an OpenSSL BIO for processing.
As you stated, the documentation of OpenSSL is not really clear on some points. Since we cannot reasonably make an assumption of its internal behavior, I believe this way of doing things to be safer.
However, in case you need high performance and want to avoid the useless copy (this would be legitimate), you better ask the OpenSSL Users mailing-list. Their answers will be acurate and I believe that only them can answer things which aren't precisely described into the documentation.
|
2,682,990 | 2,683,013 | Cannot Convert from int[][] to int* | I have a 3x3 array that I'm trying to create a pointer to and I keep getting this array, what gives?
How do I have to define the pointer? I've tried every combination of [] and *.
Is it possible to do this?
int tempSec[3][3];
int* pTemp = tempSec;
| You can do int *pTemp = &tempSec[0][0];
If you want to treat a 3x3 array as an int*, you should probably declare it as an int[9], and use tempSec[3*x+y] instead of tempSec[x][y].
Alternatively, perhaps what you wanted was int (*pTemp)[3] = tempSec? That would then be a pointer to the first element of tempSec, that first element itself being an array.
You can in fact take a pointer to a 2D array:
int (*pTemp)[3][3] = &tempSex;
You'd then use it like this:
(*pTemp)[1][2] = 12;
That's almost certainly not what you want, but in your comment you did ask for it...
|
2,683,025 | 2,683,796 | how to print std::map value in gdb | I have a std::map< std::string, std::string> cont;
I want to see cont[ "some_key" ] in gdb. When I'm trying
p cont[ "some_ket" ]
I'm getting this message: One of the arguments you tried to pass to operator[] could not be converted to what the function wants.
I'm using GNU gdb Red Hat Linux (6.3.0.0-1.162.el4rh). Thanks
| The latest gdb has python support baked in so one could easily write a function to print out the contents of any stl structure. However you'd have to learn the API and write the script. Luckily gcc 4.5 will ship with the needed python scripts to get gdb to intelligently handle stl data structures.
EDIT: you don't have to wait for GCC 4.5 (which by the way has already been released), you can just grab the code from SVN.
|
2,683,101 | 2,683,131 | How can I use C++ with Objective-C in XCode | I want to use/reuse C++ object with Objective-C.
I have a hello.h that has the class definition, and hello.cpp for class implementation.
class Hello
{ int getX() ... };
And I use this class in Objective-C function.
#include "hello.h"
...
- (IBAction) adderTwo:(id)sender
{
Hello *hi = new Hello();
int value = hi->getX();
NSLog(@"Hello %d", value);
[textField setIntValue:value];
When I compile the code in Xcode, I get this error message.
class Hello *XXXXX
Users/smcho/Desktop/cocoa/adderTwo/hello.h:9:0
/Users/smcho/Desktop/cocoa/adderTwo/hello.h:9:
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Hello'
What went wrong?
| Make sure you compile that file as "Objective-C++".
The simplest way is to rename it as *.mm.
If you don't want to rename the *.m file,
Select your file.
Open the File Info dialog (Cmd+I)
In File Type, select "sourcecode.cpp.objcpp"
|
2,683,588 | 2,683,691 | What is the fastest way to compute sin and cos together? | I would like to compute both the sine and co-sine of a value together (for example to create a rotation matrix). Of course I could compute them separately one after another like a = cos(x); b = sin(x);, but I wonder if there is a faster way when needing both values.
Edit:
To summarize the answers so far:
Vlad said, that there is the asm command FSINCOS computing both of them (in almost the same time as a call to FSIN alone)
Like Chi noticed, this optimization is sometimes already done by the compiler (when using optimization flags).
caf pointed out, that functions sincos and sincosf are probably available and can be called directly by just including math.h
tanascius approach of using a look-up table is discussed controversial. (However on my computer and in a benchmark scenario it runs 3x faster than sincos with almost the same accuracy for 32-bit floating points.)
Joel Goodwin linked to an interesting approach of an extremly fast approximation technique with quite good accuray (for me, this is even faster then the table look-up)
| Modern Intel/AMD processors have instruction FSINCOS for calculating sine and cosine functions simultaneously. If you need strong optimization, perhaps you should use it.
Here is a small example: http://home.broadpark.no/~alein/fsincos.html
Here is another example (for MSVC): http://www.codeguru.com/forum/showthread.php?t=328669
Here is yet another example (with gcc): http://www.allegro.cc/forums/thread/588470
Hope one of them helps.
(I didn't use this instruction myself, sorry.)
As they are supported on processor level, I expect them to be way much faster than table lookups.
Edit:
Wikipedia suggests that FSINCOS was added at 387 processors, so you can hardly find a processor which doesn't support it.
Edit:
Intel's documentation states that FSINCOS is just about 5 times slower than FDIV (i.e., floating point division).
Edit:
Please note that not all modern compilers optimize calculation of sine and cosine into a call to FSINCOS. In particular, my VS 2008 didn't do it that way.
Edit:
The first example link is dead, but there is still a version at the Wayback Machine.
|
2,683,778 | 2,684,087 | How to detect segmentation fault details using Valgrind? | I have a std::map< std::string, std::string> which initialized with some API call. When I'm trying to use this map I'm getting segmentation fault. How can I detect invalid code or what is invalid or any detail which can help me to fix problem? Code looks like this:
std::map< std::string, std::string> cont;
some_func( cont ); // getting parameter by reference and initialize it, someone corrupted memory (cont) inside this function
std::cout << cont[ "some_key" ] << '\n'; // segmentation fault here, cannot access "some_key"
| In general I'm not sure how that line could be generating a seg fault: the bracket operator will always return a std::string (creating an empty one if needed) and it should always be valid for printing.
Is it possible that instead, the call stack you see is pointing to the next line to execute and it's dying in some_func? We don't see the code for it, so I can't say if it could be causing the problem.
Alternately is some_func using char* (invokes temp std::string) to initialize strings in the map? It's possible that it could be introducing an invalid string into the map that "happens to work" for a while but when some_func returns it doesn't interact with the print well.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.