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 |
|---|---|---|---|---|
6,380,420 | 6,380,440 | Why can't I overload ostream's << operator? | EDIT: Passed Expression exp and string expression by const reference
I'm trying to allow a class to be display via cout in the following manner:
#include <iostream>
class Expression {
private:
std::string expression;
public:
Expression(const std::string& expression):
expression(expression) { }
frie... | Surely you need std::ostream in all locations? i.e.:
friend std::ostream& operator <<(std::ostream& os, Expression& exp) ...
^^^
|
6,380,422 | 6,380,546 | Better way to handle read buffer in C++ | I am working a linux server using epoll. I have this code to read buffer
int str_len = read(m_events[i].data.fd, buf, BUF_SIZE);
if (str_len == 0) {
if (!removeClient(m_events[i].data.fd))
break;
close(m_events[i].data.fd);
} else {
char *pdata = buf;
pushWork(pdata);
}
buf is d... |
is there any other nice way to handle
this in c++ ? This code is kind of c
style I think I have a better way to
do this in c++
Like I suggested in one of your previous questions, the Boost.Asio library is the de-facto C++ networking library. I strongly suggest you spend some time reading about it and studying t... |
6,380,641 | 6,380,723 | Executable Scenarios (BDD) for C++ | Does anyone know of a BDD framework for C++ that allows the execution of (Gherkin) scenarios such as:
Feature: Table support in nbehave
Scenario: a table
Given a list of people:
|Name |Country|
|Morgan |Sweden |
|Jimmy |Sweden |
|Jimmy |USA |
When I search for people from Sweden
Then I shou... | I've found a project called Cukebins: https://github.com/paoloambrosio/cukebins/wiki/Release-0.2. I haven't tried it and I don't know how well it works. Renamed to Cucumber-CPP and moved to https://github.com/cucumber/cucumber-cpp/
There's also a discussion with some alternatives here: http://groups.google.com/group/cu... |
6,380,666 | 6,380,704 | need help changing single character in char* | I'm getting back into c++ and have the hang of pointers and whatnot, however, I was hoping I could get some help understanding why this code segment gives a bus error.
char * str1 = "Hello World";
*str1 = '5';
ERROR: Bus error :(
And more generally, I am wondering how to change the value of a single character in a cst... | When you say char *str = "Hello World"; you are making a pointer to a literal string which is not changeable. It should be required to assign the literal to a const char* instead, but for historical reasons this is not the case (oops).
When you say char str[] = "Hello World;" you are making an array which is initializ... |
6,380,862 | 6,380,882 | how to provide a swap function for my class? | What is the proper way to enable my swap in STL algorithms?
1) Member swap. Does std::swap use SFINAE trick to use the member swap.
2) Free standing swap in the same namespace.
3) Partial specialization of std::swap.
4) All of the above.
Thank you.
EDIT: Looks like I didn't word my question clearly. Basically, I have a... |
is the proper use of swap. Write it this way when you write "library" code and want to enable ADL (argument-dependent lookup) on swap. Also, this has nothing to do with SFINAE.
// some algorithm in your code
template<class T>
void foo(T& lhs, T& rhs) {
using std::swap; // enable 'std::swap' to be found
... |
6,380,897 | 6,382,562 | How do I properly implement `operator/`? | MAJOR EDIT: Can someone please explain to me how to fix operator/ so that it will work properly? i realize that the shift is not always correct, such as for 10 / 3, which will cause infinite loops. so how do i fix that?
the entire code is at http://ideone.com/GhF0e
uint128_t operator/(uint128_t rhs){
// Save some c... | In the expression "copyn > (copyd << 1)", "copyd << 1" can overflow, leading to the infinite loop you're observing. I would suggest checking for the overflow, or making the check something more like "(copyn >> n) > copyd".
|
6,380,949 | 6,382,095 | problems with circular movement calculations | Question rescinded by original poster
Hey so when running the following code my square is supposed to travel around in a circle, but there is some kind of issue with the function that calculates the x,y movement that should happen based on the velocity and angle of travel.
It succesfully travels around and around, but... | It seems I was wrong in assuming the triangle formed and used to calculate the movement required to get to the x, y coordinates would always automatically use the Y axis as the side opposite of the 'Angle', and istead the coordinates were backwards for Quadrant 2 and 4, Thanks for the other feedback though!
Here's the ... |
6,380,981 | 6,381,032 | C/C++ C4047 differs in levels of indirection from 'int'? | So I am attempting to compile SQLite (using a different Target Device then is usually used) and I am getting a weird warning and error and I'm not sure what it means for how to fix it. Here is the message I get after I attempt to compile from within Visual Studio:
4>Compiling...
4>interop.c
4> sqlite3.c(11857) : e... | The declaration of your localtime function is not available at the point it is being used. Under C rules, the compiler therefore assumes it's an unknown function returning an int. It then warns about converting that int to a tm* (that's what the "levels of indirection" thing is about).
The solution is to declare localt... |
6,381,301 | 6,381,427 | How to parse data in C++ | final byte LOGIN_REQUEST = 1;
long deviceId = 123456789;
String nickname = "testid";
Socket mSocket = new Socket("localhost", 12021);
ByteBuffer bBuffer = ByteBuffer.allocate(1);
bBuffer.order(ByteOrder.LITTLE_ENDIAN);
//1
bBuffer.put(LOGIN_REQUEST);
//8
bBuffer.putLong(deviceId);
byte[] bStri... | The below code will effectively do the trick. I am assuming a java int is 32bit
#include <inttypes.h>
// Declare variables
unsigned char login_req;
int64_t device_id;
uint32_t name_len;
char* name_str;
// Populate variables;
login_req = pdata[0];
memcpy( &device_id, pdata+1, 8 );
memcpy( &name_len,... |
6,381,349 | 6,381,387 | Hooking output from the console | I was wondering if there is any way to read the output of a console command, from executing it in code. OK that's probably not the clearest way I could have put that, so let's have an example:
My project PingSweepr is, as the name implies, a simple network ping sweeper that uses the C++ system() command to automate pin... | Have you tried looking at the popen function? This older question has some discussion:
Capturing stdout from a system() command optimally
|
6,381,524 | 6,381,606 | How to pass a member function pointer to an overloaded method in a template function? | I referred to this somewhat similar question. However here the scenario is different:
struct A
{
void foo (int i) {} // choice
void foo (double i) {}
};
template<typename ObjType, typename FuncPtr>
void ReceiveFuncPtr (ObjType o, FuncPtr pf)
{
(o.*pf)(1);
}
int main ()
{
A obj;
ReceiveFuncPtr(obj, &A::foo); ... | how about this:
template<typename ObjType>
void ReceiveFuncPtr (ObjType o, void (ObjType::*pf)(int))
{
(o.*pf)(1);
}
|
6,381,566 | 6,400,915 | Cannot Debug Shared Library - Symbols Not Loading Properly | I am currently writing a small library, and I want to check it for leaks (among other things); however, for some reason, gdb is not loading the library symbols. I have read many other posts on here (and various other places on the internet) about this, however, I cannot seem to find a solution. Here is what is going on... | I found the reason this wasn't working: I was calling an old function call to initialize a pointer in my test executable. Since the object was never being created, I could never step into the library. Once I updated the function call, all worked well.
That said, if anyone experiences similar issues while all symbols ap... |
6,381,637 | 6,381,679 | Char array to long to char array |
Possible Duplicate:
Converting a four character string to a long
I want to convert a char array to a long and back again but I'm a bit stuck.
This is a fragment of the code I've got so far:
char mychararray[4] = {'a', 'b', 'c', 'd'};
unsigned long * mylong = (unsigned long *)&mychararray;
cout << *mylong << endl;
W... |
You're assuming sizeof(long) == 4, which can be wrong. (Especially on 64 bit platforms). If that assumption is broken, you're in undefined behavior territory: manipulating mylong will read/write beyond mychararray's allocated memory.
Your second line has no effect if you don't use *mylong on the third line
You can ge... |
6,381,643 | 6,381,996 | GUI and Text Mode C++ design to remove redundancy (optional parameter? function overloading?) | Using C++, I have a text mode and a GUI mode implemented using FLTK chosen by command line option and I see a lot of redundancy in the codes except for an extra parameter in the GUI case which I need to pass in the main window widget. I'm wondering if there are ways to remove the redundancy? Maybe I have some design ... | Parameter is not the way to go. Subclassing Game is the way to go. Any method that needs access to the window is virtual and overridden appropriately in the window-specific subclass.
class Game // I hate K&R braces, sorry
{
public:
enum GameType { cli, win };
static Game &GameFactory(GameType gt)
{... |
6,381,665 | 6,381,674 | How to nullify an array? | having an array:
char* arr[some_size] = {nullptr};
and later initializing some of its elem's is there any way that I can reset this array in other way than iterate over its elements and set them to nullptr?
I would like to avoid this:
for(unsigned i = 0; i < some_size;++i)
{
arr[i] = nullptr;
}
| You can either iterate over it yourself, or you can call a function that iterates over it for you:
#include <algorithm>
// choose either one:
std::fill_n(arr, some_size, nullptr);
std::fill(arr, arr + some_size, nullptr);
One way or another, iteration must occur.
|
6,381,744 | 6,381,795 | Please suggest an e-book for anti design pattern? | I would like to know "anti-design". Please suggest an e-book for anti design pattern.
| You may like to check out:
The daily wtf & Anti patterns
|
6,381,783 | 6,381,822 | Quickly and safely determine random number within range | How would I quickly and safely* determine a random number within a range of 0 (inclusive) to r (exclusive)?
In other words, an optimized version of rejection sampling:
u32 myrand(u32 x)
{
u32 ret = rand();
while(ret >= x)
ret = rand();
return(ret);
}
*By safely, I mean a uniform distribution.
| Rejection sampling is the way to go if you want to have a uniform distribution on the result. It is notoriously difficult to do anything smarter. Using the modulo operator for instance results in an uneven distribution of the result values for any number that's not a power of 2.
The algorithm in you post however can be... |
6,381,799 | 6,381,819 | C++ returning boolean as 95 | Problem with returning booleans in c++..
bool find( const TrieNode &node, const string word )
{
if (word.length() == 0)
{
if (node.isWord)
{
cout << "TRUE" << endl;
return true;
}
else
{
cout << "FALSE" << endl;
return false;
... | Your missing a final return statement, so your getting whatever is in the low byte of EAX, which is random garbage. your probably want return true; at the very end of your function.
Your should pump the warning level of your compiler as it should be telling you this (something along the lines of "not all control paths ... |
6,381,872 | 6,382,197 | Is it possible to have a static member variable in my templated class, without the class's user having to know about it? | I have a templated container class, something like this toy code:
template <class ItemType> class MyVector
{
public:
MyVector() : _numItems(0), _items(NULL) {/* empty */}
/** Returns a reference to the first item in our array,
* or a default-constructed item if the array is empty.
*/
const ItemType ... | If it is a template, the compiler will do the magic for you. Just put the static member in the header, and the compiler will see to that it is just instantiated once.
template <class ItemType>
class MyVector
{
public:
//...
private:
static const ItemType _defaultItem;
};
template <class ItemType>
const Ite... |
6,381,911 | 6,381,954 | unsigned char to enum | I am working on a network program and I have this code in my thread pool
unsigned char type = pdata[0];
Packet *packet = m_packetFactory->createInstance(type);
CreateInstance take an enum type to crate a packet based on the enum variable;
Client is using java and serialize the first byte like this
final byte LOGIN_RE... | If you are sure the data is valid, simply cast it to the enum type:
enum MyEnum{
EXAMPLE_1 = 0,
...
};
char type = 0;
MyEnum etype = static_cast<MyEnum>(type);
|
6,382,029 | 6,382,056 | strcpy throws memory exception | #include<stdio.h>
#include<string.h>
#include<iostream.h>
using namespace std;
int main()
{
const char *a="hello";
char *b;
strcpy(b,a);
cout<<b;
return 0;
}
This code theows memory exception . why ?
| char* b is a pointer that is yet to be pointed at any memory... it simply holds a random address. You attempt to copy the content of a over the memory at that address. Instead, first point b at some memory - either a local array or from new char[].
char buffer[128];
char* b = buffer;
char* b = new char[128];
// use ... |
6,382,097 | 6,382,141 | c++: Behaviour of pointer data member in class inheritance hierarchy | class Base {
protected:
string m_strName;
char* pchChar;
public:
Base()
{
m_strName = "Base";
pchChar = NULL;
};
void display()
{
printf(" display name : %s %c\n",m_... | You forgot *:
printf(" display name : %s %c\n",m_strName.c_str(), *pchChar);
It should be *pchChar, not pchChar. Because you're printing it as %c.
Or you can use %s as format string, and your printf would work, if the c-string is null-terminated string. Currently its not null-terminated. You should be doing this:
pch... |
6,382,462 | 6,382,514 | Virtual protected function error | I have Packet class contains virtual method and I have LogInRequest class which extends the packet class
Packet.h file
class Packet {
public:
Packet();
virtual ~Packet();
protected:
virtual char* toByte() = 0;
virtual void fromByte(char *d) = 0;
virtual Packet* handle() = 0;
short m_bodySize... | When you try to call a method through a pointer or reference, the compiler will verify the access specifier of the function in the static type of the object, even if it will dispatch the call to the dynamic type.
In your Packet class you have stated that you don't want user code (other than Packet, friends and derived ... |
6,382,632 | 6,382,678 | How to avoid crashing while calling function throwing exception from .so | Here is what I did, I want to gracefully handle this exception:
code_snippet: my.cpp
#include<iostream>
extern "C" void some_func()
{
throw "(Exception Thrown by some_func!!)";
}
code_snippet: exception.c
#include <stdio.h>
extern void some_func();
int so_main()
{
some_func();
return 0;
}
From above two s... | Try compiling src/exception.c with -fexceptions
-fexceptions
Enable exception handling. Generates extra code needed to propagate exceptions. For some targets, this implies GNU CC will generate frame unwind information for all functions ...
However, you may need to enable this option when compiling C code that ne... |
6,382,913 | 6,382,977 | Very slow to execute system command | I have a C++ program that records a lot of data to disk continuously for a long time. As such I have a thread that monitors the disk space available and once it hits a certain percentage does some stuff.
This is on a dual quad core x64 CentOS system and the recording is happening on directly connected SATA disks tha... | An alternative to using system is an OS-specific API call, like statvfs.
But I agree it's weird that it's taking that long. Can you recreate this?
|
6,383,007 | 6,383,036 | Killing a child process if it takes too much time | When using the fork system call in C++, what is the easiest way to kill a child process if it takes too much time to execute what it is supposed to execute?
Like if somehow it gets into an infinite loop.. What should the parent process do to set the timeout for the child process?
| Use WNOHANG with waitpid and sleep in between. Something like this should do it:
while (times < max_times) {
sleep(5); /* sleep 5 seconds */
rc = waitpid(-1, &status, WNOHANG);
if (rc < 0) {
perror("waitpid");
exit(1);
}
if (WIFEXITED(status) || WIFSIGNALED(status)) {
/* it's... |
6,383,032 | 6,383,094 | C++ semantic type wrapping | I have a data type for example class Vector3. Now I need to create several classes with same interface as Vector3, but with higher level semantic (for example: Position, Velocity). Using typedef is not enough, because I need these types to be distinct so that they can be used for overloading. In C++0x I could probably ... | Consider using a tag struct
struct tagPosition {};
struct tagDirection {};
struct tagGeneric {};
namespace detail
{
template <typename Tag=tagGeneric>
class Vector3
{
// business as usual
};
}
typedef detail::Vector3<tagPosition> Position;
typedef detail::Vector3<tagDirection> Direction;
... |
6,383,358 | 6,384,275 | Callbacks from C++ back to Java | I have coded the following for numerical integration in C++:
// integrate.h:
#ifdef BUILDING_DLL
#define DLL_MACRO __declspec(dllexport)
#else
#define DLL_MACRO __declspec(dllimport)
#endif
extern "C" {
typedef double (*Function1VariablePtr)(double x);
double DLL_MACRO integrate(Function1VariablePtr function, do... | One way that can be done is by using a pointer to member function and changing the signature of the integrate function.
See below the general idea:
functionwrapper.h
Declare a function wrapper class.
class FunctionWrapper
{
public:
typedef double (FunctionWrapper::*Function1VariablePtr)(double x);
FunctionWrap... |
6,383,364 | 6,383,928 | How do I make Qt graphs appear in the same window? | I am working in Qt in my program. I have a widget window and I have placed a button and a list box in it. Then I have made a class called myplot which graph plotting is done. Then in my button event handler I have called the object of myplot
myplot * p1 = new myplot(session,session ,24, "session"); // send arrays in a... | Apparently, myplot is a childclass of QWidget. So you can just define a layout on your main window (e.g. using QHBoxLayout), and add those two widgets to it. This will cause them to be drawn inside the mainwindow. Also make sure that you pass the main window as the QWidget parent of the plots.
For replacing the plots, ... |
6,383,605 | 6,383,731 | How to Implement a Garbage Collector in C++ |
Possible Duplicate:
How to implement garbage collection in C++
I was recently asked this question in an interview about how to implement a garbage collector in c++.
My answer was to have a pre allocated memory pool and construct object in that allocated space. Also to store the size of the memory allocated to an obj... | You can read about the shared_ptr struct.
It implements a simple reference-counting garbage collector.
If you want a real garbage collector, you can overload the new operator.
Create a struct similar to shared_ptr, call it Object.
This will wrap the new object created. Now with overloading its operators, you can contro... |
6,383,639 | 6,383,733 | Conditions for copy elision? | I wanted to verify the if the following optimizations work as expected:
RVO
Named RVO
Copy elision when passing an argument by value
So I wrote this little program:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>
struct Foo {
Foo(std::size_t length, char value) : data(length, value)... | The way you use the copy constructor it can not be elided, as the copied object still exists after the call.
If you try it this way, it might work better:
PassByValue(Foo(512, 'a'));
All optimizations are allowed but not required, so it is up to each compiler to decide what it can and will do.
|
6,383,880 | 6,384,077 | Getting Stringstream to read from character A to B in a String | Is there some way to get StringStream to read characters A through B of a string?
For example, something like (but not):
stringstream mystringstream;
mystringstream.read(char* s, streamsize n, **int firstcharacter**);
Thanks for your help.
EDIT: By A through B I mean, for example, the third through fifth characters.
E... | or, if you need a substring in position A through B, you can do
string s = mystring.substr(A, B-A+1); // the second parameter is the length
if this must be a stringstream, you can do
string s = mystringstream.str().substr(A, B-A+1);
|
6,383,882 | 6,411,813 | Unmanaged dll called by ASP.Net unable to create file under IIS6 | I have an ASP.Net Framework 4 web application making an interop call to a 3rd party unmanaged dll written in C++.
The dll is stored in the bin directory of the web application and creates a file in another directory of the same web application.
The call works fine using Visual Studio 2010 (typically), but the individu... | The 3rd Party confirmed that the problem was due to a problem in their memory allocation. The amount allocated on the stack not being sufficient.
The dll was suffering a stack overflow as a result and brought down w3wp.exe temporarily while IIS brought another process back up automatically.
|
6,383,907 | 6,383,965 | Can system() return before piped command is finished | I am having trouble using system() from libc on Linux. My code is this:
system( "tar zxvOf some.tar.gz fileToExtract | sed 's/some text to remove//' > output" );
std::string line;
int count = 0;
std::ifstream inputFile( "output" );
while( std::getline( input, line != NULL ) )
++count;
I run this snippet repeatedl... | According to the documentation
The system() function shall not return until the child process has terminated.
Perhaps capture the output of "output" when it fails and see what it is? In addition, checking the return value of system would be a good idea. One scenario is that the shell command you are running is fail... |
6,383,999 | 6,384,042 | Static methods vs singletons |
Possible Duplicate:
Why choose a static class over a singleton implementation?
Static methods vs singletons.
Could it be determined choice here?
What are conditions in which one of these approaches is definetely more suitable then other?
| Static methods follow the "low coupling and high coherence"-rule more than singletons do. (As long as their implementations don't rely on static member variables.)
|
6,384,118 | 6,384,151 | What does the 'L' in front a string mean in C++? | this->textBox1->Name = L"textBox1";
Although it seems to work without the L, what is the purpose of the prefix? The way it is used doesn't even make sense to a hardcore C programmer.
| It's a wchar_t literal, for extended character set. Wikipedia has a little discussion on this topic, and c++ examples.
|
6,384,255 | 6,384,330 | A simple Linked List implementation in C++ | I am trying to implement a simple linked list using c++. I am probably making a silly mistake somewhere.Through this i want to learn classes and pointers in C++.
For the code
#include <iostream>
using namespace std;
class node
{
public:
node* next;
int data;
node(int d);
void append(int d);
};
node... | There might be other errors, but this is extremely dangerous: You are creating a local variable to represent the new node: node nw = node(d);, and then you make the last node in the list point to nw. However, since nw is a local variable, it will cease to exist when the function returns. So the next pointer of the last... |
6,384,292 | 6,384,432 | Differences between method pointer casting rules in g++ and Visual Studio | struct Test
{
typedef unsigned (Test::*MethodPtr)();
unsigned testMethod() {}
};
typedef void (*ThreadPtr)(void *);
ThreadPtr threadPtr = reinterpret_cast<ThreadPtr>(&Test::testMethod);
I want to launch a thread into a class method of a particular object. I use a method pointer as the thread entry point and pa... | Okay, do this:
void threadMethod(void* ptr) {
static_cast<Test*>(ptr)->testMethod();
}
ThreadPtr threadPtr = &threadMethod;
That way, you're dealing with a real function, not a PMF.
|
6,384,860 | 6,384,968 | C++ Decorate basic_iostream classes | I want to do something like the following code shows:
class foo
{
private:
std::fstream* m_stream;
public:
foo(std::fstream* stream) : m_stream(stream) { }
foo& write(char const* s, std::streamsize count)
{
if (/*condition*/)
{
m_stream->write(s, count);
}
e... | Many of the formatted output operators (operator<<) write directly to the underlying stream buffer. What you need to do in order to accomplish this in a general fashion is derive a class from std::basic_streambuf that forwards all data to another std::basic_streambuf, and then optionally create a minimal std::basic_ost... |
6,385,221 | 6,385,905 | unexpected result using boost mpl inserter iterator | I had expected the following to give the same result:
namespace mpl = boost::mpl;
template<int from, int to>
struct
make_vector1
: mpl::copy<
mpl::range_c<int,from,to>,
mpl::inserter<
mpl::vector<>,
mpl::push_back<mpl::placeholders::_1,
mpl::placeholders::_2 // <- Copy int_ typ... | You get a 2 because ::value on _2 is defined to be 2 (the placeholder index). MPL don't define :: on placeholders for obvious reason so you can not directly do this.
Now, accessing an element in a mpl::range_c already gives you an mpl::int_ as you noticed so there is no need to try to extract the numerical value to put... |
6,385,688 | 6,857,506 | Valgrind error - cannot execute binary file | For some reason I can't make valgrind work with my Cocoa apllication on OS X 10.6, compiled with Apple GCC 4.2.1... After googling this error I found out that valgrind doesn't work with 64-bit executables, however my application and all the frameworks it uses is being compiled with the -m32 flag and file commmand says ... | I downloaded latest valgrind v3.6.1 from valgrind.org and compiled it under OS X and it works without any issue.
|
6,385,854 | 6,385,921 | Is `template<>` optional when specializing a class template using another class template? | I was trying to specialize a class template with another, as in the example below, and I noticed that this compiles and runs (at least on ideone, which is: gcc 4.3.4) whether the commented out line is commented out or not.
#include <iostream>
template <typename F>
struct foo{
typedef F value_type;
};
template <typen... | That line should not be there.
When doing full specialization, there is template<> and it's mandatory. When doing partial specialization, you put the parameters of the partial specialization to those angle brackets and there is no additional template keyword.
So full specialization is:
template <>
struct bar<qyzzy>
an... |
6,386,329 | 6,386,377 | C++ Initialize array pointer | How do I initialize a pointer to a literal array?
I want *grid to point to the new allocated int array {1, 2, 3}.
int *grid = new int[3];
*grid = {1, 2, 3};
thank you.
| You can't initialize a dynamically allocated array that way. Neither you can assign to an array(dynamic or static) in that manner. That syntax is only valid when you initialize a static array, i.e.
int a[4] = {2, 5, 6, 4};
What I mean is that even the following is illegal:
int a[4];
a = {1, 2, 3, 4}; //Error
In your ... |
6,386,404 | 6,386,453 | Find the list of member variables of a class and their types? | I haven't ever heard it's possible, but asking with the hope that it might.
For a class with many more member variables than this:
class A
{
public:
SomeOtherClass* s;
int i;
int j;
A() {}
A(const A& soc): s(soc.s->Clone()), i(soc.i), j(soc.j) {}
};
I always have to remember that if I add another variable i... | There is no reflection in C++, so you'll need an external library to do this. The creators of C++ didn't implement this feature because it implies a performance penalty, and performance is one of C++'s main goals.
|
6,386,500 | 6,386,600 | Newbie: Performance Analysis through the command line | I am looking for a performance analysis tool with the following properties:
Free.
Runs on Windows.
Does not require using the GUI
(i.e. can be run from command line or by using some library in any programming language).
Runs on some x86-based architecture (preferably Intel).
Can measure the running time of my C++, min... | Mingw should already have a gprof tool. To use it you just need to compile with correct flags set. I think it was -g -pg.
|
6,386,601 | 6,386,734 | Given that b is always non-zero, why `b ? --b : ++b` works, but `--b` does not? | I was trying to multiply two integers using recursion, and wrote this code, accidently:
//the original version
int multiply(int a, int b)
{
if ( !b )
return 0;
else
return a + multiply(a, b ? --b : ++b ); //accident
}
I said, I wrote this accidently, because I intended to write :
b > 0 ? --b : ++b inste... | TL;DR version: The reason b? --b: ++b prints a result and --b fails with SIGXCPU is that ideone sets a time limit on submitted code. One version gets optimized better, and completes in the time allowed. The other version gives the exact same answer, but you won't see that with ideone because it runs too slowly and ge... |
6,386,856 | 7,571,799 | Process-crash with the message "RPC server is unavailable" on opening a save file dialog? | On Windows 7 64-bit, I use Qt 4.5.3 to call QFileDialog::getSaveFileName. Immediately on calling this function, my process crashes with the message "The RPC server is unavailable".
I found this, but it doesn't solve my problem:
"The RPC server is unavailable"
Any ideas?
| I'm having exactly the same problem, but with Qt 4.7.0. Windows 7, 64-bit.
Calling QFileDialog::getOpenFileName or QFileDialog::getSaveFileName crash my process with the following message: "First-chance exception at 0x7486b9bc in SoundManager.exe: 0x000006BA: The RPC server is unavailable."
The RPC Server is running i... |
6,386,874 | 6,387,716 | Use non-virtual dispatch in a template | I want to call a member function which is virtual (inheritance is used in most places to keep things simple), but I want to force calling it using non-virtual dispatch sometimes, in performance critical places, and in such places the exact type is known compile time. I do this for performance reasons, on a platform whe... | If you know the exact type you can do it as:
template <typename StaticType>
void DoIt(Interface &func)
{
static_cast<StaticType&>(func).StaticType::Do();
};
Where you need to manually downcast to the type you need (static_cast is fine if you do know the type). Then you need to qualify the method call, do disable dyn... |
6,386,918 | 6,387,860 | problems with this singleton (Not class) | I am sure this could have been answered but I couldn't actually find a consolidated answer.
what are the problems with the following singleton that is just a function and guaranteed to have initialization and assuming T supports operator!, needed constructors, functions etc? (I am not looking for thread safety). More ... | There are some mistakes in your code -- the template type is being used instead of the variable.
For what you need (don't care about thread safety & need it for the entire duration of your application), it might be exactly what you need. You might wish to start from this though:
template<typename T> T* getInstance()
{
... |
6,387,029 | 6,387,218 | Can I have static data members in an abstract class? | I designed a series of related classes, and in order to be able to manage them I made them derive from a single abstract class.
These classes all need access to a series of shared resources, and I found myself creating a vector of pointers in each, all of them identical (they necessarily must be). It seems like making ... | The better solution would be to just make an object with the vectors in and then only instantiate it once and give the other classes a pointer or reference to it. Static data should be absolutely avoided unless necessary and this just isn't necessary.
|
6,387,433 | 6,388,599 | QWebView elements load progress | I want to log every element that is loaded by request (images, javascripts, styles, etc). I load page via QWebView. But there is only basic signals like start loading, progress, finished loading. And can't find how can I record each step of what webview is doing. Or it's impossible?
| The simplest thing you can do here is listen to QNetworkAccessManager's finished() signal.
To get the AccessManager
QNetworkAccessManager mgr = webView->page()->networkAccessManager();
in the slot that catches the finished signal
myclass::slot(QNetworkReply* reply)
{
...
reply->request()->url(); //gives you the res... |
6,388,031 | 6,388,186 | Multithreading vs multiprocessing | I am new to this kind of programming and need your point of view.
I have to build an application but I can't get it to compute fast enough. I have already tried Intel TBB, and it is easy to use, but I have never used other libraries.
In multiprocessor programming, I am reading about OpenMP and Boost for the multithread... | Multithreading means exactly that, running multiple threads. This can be done on a uni-processor system, or on a multi-processor system.
On a single-processor system, when running multiple threads, the actual observation of the computer doing multiple things at the same time (i.e., multi-tasking) is an illusion, becau... |
6,388,041 | 6,536,065 | Many structs in one header file for this client/server situation (C++) | I'm trying to decide if this is not very nice, or not.
Basically, I am writing a client server system. To make it easier and less error prone, I decided all requests/responses/etc. between client and server should be defined as structs in a shared library that is used by both the client and server, and then have a ser... |
Does putting these structs in a single header like this give you convulsions?
No.
Assuming that your server and your client both use most (if not all) of the requests (and hence the *Params objects are used on both sides), the only thing that would make me consider putting them into separate files is the type of thei... |
6,388,360 | 6,572,337 | Template factory giving linker error and ignoring reference type | I am creating a template factory for my project, everything was working fine until I need to add an extra parameter to the object creation process.
The factory has two main templates:
template <typename T>
class GenericFactory_c: boost::noncopyable
{
public:
typedef typename T::ObjectType_t ObjectType_t;
... | If this function
Entity_c::CreateCompXYZ()
{
EntityComponentFactory_c &factory = EntityComponentFactory_c::GetInstance();
EntityComponentPtr_t xyz = factory.Create("XYZ", "myXYZInstance", *this);
}
is actually calling this template for a 3 parameter Create
//"advanced" creation using an additional Y parameter... |
6,388,591 | 6,388,617 | Need a recommendation for a C++ GUI library | I want to make remote administration tool. I want to take the first step by implementing the GUI or part of it (since it will be fun while being my first real experience with C++).
I need the following features in the GUI library:-
1) Modern easy-to-work-with paradigm
2) Modern kool features.
3) OS-independent. i.e. wo... | Use Qt ... it offers pretty much everything you need.
|
6,388,698 | 6,388,750 | C++: Return std::string reference from stack memory | I will start by saying I've read this topic: C++ Return reference / stack memory. But there, the question was with an std::vector<int> as object-type. But I though the behavior of std::string was different. Wasn't this class especially made for using strings without having to worry about memory-leaks and wrong usage of... | You are really close to making those functions work:
std::string function()
{
string s = "Faz";
s += "Far";
s += "Boo";
return s;
}
Simply make them return a copy instead of a reference and you're set. This is what you want, a copy of the stack-based string.
It gets better too, because the return valu... |
6,388,766 | 6,388,990 | Any tips on Linux programming for Windows programmer (C/C++)? |
Possible Duplicate:
shifting from windows to *nix programming platform
Does anyone know a good, compact resource that would allow me to migrate from Windows programming to Linux programming?
I managed to get simple apps running, checked daemon architecture, but somehow I don't know where to begin to get a better und... | As far as details on the *nix API goes, this is a good set of material:
http://www.hiraeth.com/alan/tutorials/courses/unixprog.html
And somebody has pulled together a nice list of links to many resources here
While it's good to learn the target platform, I strongly recommend using Boost libraries wherever possible as w... |
6,388,844 | 6,388,888 | using a template class without a template argument | I have a Visual Studio 2008 C++ project with a template class that takes the templated value in the constructor like this:
template< typename A >
struct Foo
{
const A& a_;
Foo( const A& a ) : a_( a ) { };
};
Therefore, I have to construct this class like this:
int myval = 0;
Foo< int > foo( myval );
It seems ... | If you name the type at all, it has to be the complete type (i.e., Foo<int> and not just Foo).
A class can have multiple constructors or may have no constructors that have a parameter of the class template's type parameter, so there's no way to make this work for all class templates (in my opinion it would be confusi... |
6,389,179 | 6,390,986 | Parsing C++ to make some changes in the code | I would like to write a small tool that takes a C++ program (a single .cpp file), finds the "main" function and adds 2 function calls to it, one in the beginning and one in the end.
How can this be done? Can I use g++'s parsing mechanism (or any other parser)?
| As suggested by some commenters, let me put forward my idea as an answer:
So basically, the idea is:
... original .cpp file ...
#include <yourHeader>
namespace {
SpecialClass specialClassInstance;
}
Where SpecialClass is something like:
class SpecialClass {
public:
SpecialClass() {
firstFunction();... |
6,389,401 | 6,389,440 | Simple question: Why does the string library function std::string::find always return std::string::npos? | Please see the code fragment below, specifically the first 'else if' statement. I want the user to have the ability to do this:
load filename
so I want to check that "load " is in the string and attempt to open whatever is after "load ". However, string::npos seems to always be returned (string::npos just means there... | cin >> choice stops reading before the first whitespace. You want getline(std::cin, choice) here.
|
6,389,485 | 6,389,712 | Using same name for kind of variable commonly re-occurring in a nested scope | I often write stuff like:
const auto end = some_container.end();
for( auto it = some_container.begin(); it != end; ++it )
{
const auto &item_container = *it;
const auto end = item_container.end()
for( auto it = item_container.begin(); it != end; ++it )
{
do_awesome_stuff_with_the_iterator();
... | Since you have this tagged c++0x, why don't you simply use std::foreach() with a lambda function?
I don't have a lambda-aware compiler handy, but something like this should do:
// Beware, brain-compiled code ahead!
std::foreach( some_container.begin()
, some_container.end()
, [](some_element& ... |
6,389,521 | 6,389,628 | using a char array to hold an array of arbitrarily sized objects, alignment issues? | I want to pass in an array of parameters to SQLBindParameters, and have this array held in a char array(since I don't know the type beforehand) (I want all the elements in the 'array' to be the same).
I'll have a pointer to a sample parameter type, and the size of the parameter.
void *buffer = getBuffer();
int bufferLe... | Assuming that you're using vector with an allocator that uses operator new under the hood, then the C++ standard guarantees that an array of char allocated with new will be aligned suitably for use with any data type.
EDIT: Yes, new char[] is guaranteed to be aligned for use with any type.
EDIT2: Do note that a local (... |
6,389,529 | 6,390,118 | Is it possible to ignore an Error 487 (ERROR_INVALID_ADDRESS) for UnMapViewOFFile()? | Good afternoon, We are trying to build a prototype of Memory Mapped File Caching program for use by Windows and Linux 32 bit applications. Every time we run the prototype we get an Error 487(Error Invalid Address) when we try call UnMapViewOfFile to unmap a a cached memory mapped file region. We think this is happening... |
we trying a unmap a previouslu unmapped region
That is a bug, period. You "ignore" the error by fixing the bug.
Alternately, just ignore it with an if test. The Win32 function is telling you there's a bug to fix, but if you want to ignore what it's telling you of course nobody is going to prevent you from doing so.
|
6,389,544 | 6,389,644 | C++ network multi application protocols | I am programming a Client/Server application for my project in C++. The whole application protocol was given or discussed by the working group. The main idea is that we have 3 protocols.
Text-protocol: send and receive some information in string format between client and server.
Binary-protocol: client sends continio... | You should decouple your socket class from the 3 protocol handlers - don't have methods for both text and binary data handling on the Socket or you unintentionally encourage people to mix and match data types over the same socket, which is clearly not what you want.
Your socket should provide simple connect/disconnec... |
6,389,636 | 6,391,701 | How do I create objects in a specific container in my Qt Creator MainWindow? | Hopefully this question is an easy one. I need to generate a few buttons at run-time in a specific area of my GUI. The objects I want to create are checkboxes. Here is the part of the code that creates these checkboxes:
void MainWindow::on_generateBoxes_clicked()
{
int x_dim = ui->xDim->value();
int y_dim = ui-... | Troubadour is basically right, that you need to set the right widget as parent. Though QScrollArea has by default no widget, you need to create it like this:
checkBoxArea = new QScrollArea(this); // this is the MainWindow or other parent
background = new QWidget;
checkBoxArea->setGeometry(0, 0, 200, 200);
checkBoxArea-... |
6,389,640 | 7,929,045 | How to use Emacs and CEDET with SCons? | How to integrate SCons and emacs + cedet without breaking semantic and auto-complete?
| I don't think there exists SCons integration for cedet.
However, it is easy to set up an EDE project manually.
An lisp-snippet for a C++-project is given below.
(ede-cpp-root-project "myProject"
:name "myProject"
:file "my_project.txt"
:include-path '("myproject/include")
:s... |
6,389,822 | 6,390,725 | Convert C++ Syntax to Objective C | My background experience is C/C++/C#.
I am using a C++ library in an xcode project (to be specific the library is PJSIP). To use the library i have to wire couple of callbacks to my code like this:
SipTest.m
#include < pjsua-lib/pjsua.h >
static void on_reg_state(pjsua_acc_id acc_id)
{
// Do work
}
static void I... | First of all, there's absolutely no need to convert anything at all. It is perfectly fine to call C++ libraries from Objective-C.
Secondly, whats causing the compiler error is that you're trying to stick a method in a place where there should be a function pointer. You can't make a function pointer out of an Objective-... |
6,389,891 | 6,390,110 | Which cast style is better and why? | Imagine in C++ two classes one named derived and another named base that is a base class of the first. If I had the following code, which is preferred:
base *b = init_value_here;
const derived *d = static_cast<derived *>(b);
or
base *b = init_value_here;
const derived *d = static_cast<const derived *>(b);
In other w... | I strive to do the least number of explicit casts possible, and everything else implicit, if possible.
So I would use the former (i.e not including const in the cast).
But this is only my opinion. You may be of the opinion to write the const there too, as it fits your taste.
|
6,390,123 | 6,390,184 | C++ Sharing elements in a boost::ptr_container? | Please consider the following piece of code:
int main()
{
typedef boost::ptr_vector<int> ptr_vector;
ptr_vector vec0;
vec0.push_back(new int(1));
vec0.push_back(new int(2));
vec0.push_back(new int(3));
vec0.push_back(new int(4));
vec0.push_back(new int(5));
ptr_vector::iterator last =... | Yes, you should use a vector<shared_ptr<int>>.
Since you're only working with ranges, you could put together a custom solution that keeps track of the ranges and their intersections (for implementing unique.) Then, you could store everything in vector and have the ranges index into that. This would probably be faster... |
6,390,133 | 6,390,218 | How increase a sprites speed without ending up spiraling instead of circling | Hey so i have a sprite class, and i am making it turn 360 degrees a second, while increasing speed at the same time. However I end up spiraling and not staying on the original circle formed by the continuous turning of 360 degrees per second.
How can i fix this? The sprite needs to go faster and stay on the same path.... | If you want to make a sprite go in a circle, put that in the code. For example,
float time = Window.GetFrameTime();
angle += speed * (time - lastTime);
lastTime = time;
float x = sinf(angle), y = cosf(angle);
box.SetPos(50*x + center.x, 50*y + center.y);
box.Turn(angle + QUARTER_TURN);
|
6,390,331 | 6,390,357 | Why use array size 1 instead of pointer? | In one C++ open source project, I see this.
struct SomeClass {
...
size_t data_length;
char data[1];
...
}
What are the advantages of doing so rather than using a pointer?
struct SomeClass {
...
size_t data_length;
char* data;
...
}
The only thing I can think of is with the size 1 array version, user... | With this, you don't have to allocate the memory elsewhere and make the pointer point to that.
No extra memory management
Accesses to the memory will hit the memory cache (much) more likely
The trick is to allocate more memory than sizeof (SomeClass), and make a SomeClass* point to it. Then the initial memory will b... |
6,390,459 | 6,391,833 | Good ways of parsing in C++ | I'm writing a Program in C++ that is going to use the same input files as an existing Prolog program already uses.
The files will look like these :
expr1(t,[f,g]).
expr1(q,[]).
expr1(r,[e]).
expr2(a).
expr2(b).
expr2(e).
expr2(a,r).
expr2(b,d).
expr2(e,z).
What are some ways of parsing such files? I've read about ... | What is wrong with Flex and Bison? This does have the benefit of the generated code being independent of libraries which you may or may not have. It is used for things as simple as parsing config files to things like a Javascript parser for Webkit.You might even find a Prolog grammar that you can use.
|
6,390,532 | 6,390,569 | Debugging GCC compile times | I'm creating a fairly large library in C++0x using GCC 4.6 in Linux. My library relies heavily on template classes, resulting in long compile times for applications which use the library. I would like to start speeding things up by providing explicit instantiations of the worst offending types/methods.
Is there a way t... | g++ some_file.cc -ftime-report will give you a rough estimate of time spent in different compiler phases. The most important ones in your case are name lookup and parsing.
There isn’t any way to get a per class/function compile time alas.
Steven Watanabe has proposed a template profiler, available in the Boost sandbox ... |
6,390,705 | 6,503,213 | v8 Cannot access properties from script compiled in new context | I've created a simple 'require' mechanism (https://gist.github.com/1031869), in which the included script is compiled and run in a new context. However, when I call a function in the included script and pass it this, the included script doesn't see any properties in it.
//required.js - compiled and run in new context
e... | The problem was that V8 doesn't allow a Context to access the global variables of another Context. Hence, logger.logThis(this) wasn't printing anything.
This was solved, by setting the security token on the new context:
moduleContext->SetSecurityToken(context->GetSecurityToken());
where context is the 'main' context a... |
6,390,756 | 6,390,927 | std::string — small string optimization and swap | From N3290, [container.requirements.general]:
The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, copy, or swap operations on the individual container elements.
How do this interact with small string optimizati... | (Reposting from comment)
std::string is not a container – the fact that basic_string is not described in the Containers library chapter (§23) of the FDIS is a good clue. ;-]
|
6,390,954 | 6,391,045 | Best way to use RAII conditionally | I have a nice resource managing class. For concreteness, lets have it be a File class for managing a FILE* (handling the open and close operations)
What is the usual approach when there are cases where the resource doesn't need to be managed by me, and is someone else's responsibility?
For ilustrative purposes, I curre... | Your RAII class is already keeping enough state to know when to destroy the resource it is controlling. It can also contain a flag that tells it if the resource should be destroyed, or you can use a special value on the counter to indicate that the resource is controlled outside the class.
Then all you need is a way to... |
6,391,057 | 6,391,202 | Realloc- in Standard allocator | For the Standard allocator interface for use in, say, std::vector, is re-allocation supported? I have a rather specific use-case in which being able to realloc directly would be much more efficient than allocating, moving, and freeing.
Edit: Sorry- I have absolutely no intention of calling the actual realloc, I meant a... | We tried but failed:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1953.html
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2045.html
Edit: I know what you meant. ;-)
|
6,391,423 | 6,392,383 | Anti-aliasing in allegro 5 | How do I make allegro 5 use anti-aliasing when drawing? I need diagonal lines to appear smooth. Currently, they are only lines of shaded pixels, and the edges look hard.
| To enable anti aliasing for the primitives:
// before creating the display:
al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
al_set_new_display_option(ALLEGRO_SAMPLES, 8, ALLEGRO_SUGGEST);
display = al_create_display(640, 480);
Note that anti-aliasing will only work for primitives drawn directly... |
6,391,458 | 6,391,619 | Please help me to understand the difference between streambuf, stringbuf and stringstream? | Please someone help me to undersatnd the difference between " streambuf, stringbuf and stringstream".
void f1(std::string const& text)
{
std::stringstream inStream(text);
cout<<inStream.str()<<endl;
}
or if I write
void f2(std::string const& text)
{
std::stringbuf inStream(text);
... | A stringbuf is used by a stringstream, it provides the buffer for the stream. A streambuf is just the base class for a stringbuf. What you want is a stringstream if you need formatted input/output into/out of the stream (like putting numbers in a string), otherwise you want to continue using a simple string. You should... |
6,391,511 | 6,391,562 | How to exit (go to next element of parent loop) a for loop inside a for loop | for (int i = 0; i<10; i++)
{
//do some validation for record length
//if it is not valid
continue; // goes to the next iteration in for loop for 'i'
for (int j = 0; j<5; j+=2)
{
//do some more validation for individual record
//if it is not valid
Here it should go to the next i if i use c... | You need to specifically test for a flag in the outer loop if there is something after the inner loop:
for(some_outer_vars){
bool should_skip = false;
// ...
for(some_inner_vars){
// ...
if(your_condition){
should_skip = true;
break;
}
}
if(should_skip)
continue;
// ...
}
|
6,391,533 | 6,391,554 | c++ virtual function problem |
Possible Duplicate:
Overriding a Base's Overloaded Function in C++
I have a class like this one:
class Object {
public:
int alignment() const;
virtual void alignment(int i);
};
that I try to subclass like this:
class Sub : public Object {
public:
virtual void alignment(int i);
};
then:
Sub *sub = new S... | Yes. Doing it like this hides the function overload in the base class. Add the following to your Sub class to fix this:
using Object::alignment;
|
6,391,612 | 6,391,836 | c++ GUI Events/Messaging Design | So, I'm making a simple game using DirectX 9 and C++. I looked at the SDK's GUI, but I think I can implement something simpler.
All I want are windows, labels, buttons, textboxes, and checkboxes.
I've created a base class GUIObject, that all inherit from. It includes basics like size and focus and whatnot. Then the der... | You might want to look into using a signaling library such as boost::signals to allow you the flexibility of defining the interface between your GUI objects and the underlying events that each callback will trigger. It can also come in handy for the reverse relationship where you need GUI elements such as status indic... |
6,391,633 | 6,392,121 | Best Way to Send Data from C++ program to Rails Server | I have a C++ program that is constantly generating a large amount of data that needs to be sent to a Rails server. Both the program and the server are on the same machine running Suse Linux.
What is the most efficient and simple solution for this?
| Sockets are the way to go. If you want some good asynchronous and cross-platform sockets in C++ your best bet, probably, will be boost::asio.
|
6,391,844 | 6,391,866 | C++ boost lexical_cast with template? | I'm trying to build a class that stores program settings as a std::map. Since all the program settings are stored as strings I'd like an accessor method that can return the program setting casted to the relevant type. I'm new to templating in C++ and this is my first attempt:
class Settings
{
public:
Settings(voi... | CString does not have any operator<<
Consider using std::string
|
6,391,938 | 6,392,006 | pass by reference and pass by value in c++ and java |
Possible Duplicates:
What's the difference between passing by reference vs. passing by value?
Java and C++ pass by value and pass by reference
Java is "pass by value" or "pass by reference"?
and what about c++ and c?
is c++ and c "passed by value" or "passed by reference"?
and what is the difference between "pass b... | Java is pass by value, but the value you pass may be a reference.
In C++, you choose whether to pass by value or by reference. In C, you always pass by value, and there is no such thing as a reference; you have to pass a pointer to do something similar.
If you pass by value, the function gets a copy of the variable you... |
6,392,178 | 6,392,225 | How to specify possible data types for a template function | I'm trying to make a function that takes two data types, each of which I know will be a descendent of a drawable class, meaning my function depends on some of drawable's functions. However because it is a template function I can't do this.
How can I make it so I can use these descendant class functions? Or make it so ... | A CheckCollision() function shall require the client to pass an object that provides GetPosition() methods. That's what you do when calling obj1->GetPositionX() inside your template. There's no reason to force it to pass a drawable object.
|
6,392,185 | 6,392,382 | Tools to create HTML-Based Windows UI in C++ | I'm looking for suggestions on technologies to design a windows UI that's powered by HTML. I've run across HTMLayout which seems pretty good if not perhaps a bit limited. Are there any other technologies that would provide a good platform for creating an application UI based on HTML?
| You could use chromiumembedded. You get the power of Google's Chrome in your application.
Evernote used CEF (Chromium Embedded Framework) when they moved from C# back to C++.
Unlike HTMLayout, CEF has a permissive license, which allows usage in commercial applications without paying royalties. The drawback would be the... |
6,392,195 | 6,392,637 | conditional display in gdb | I'm using gdb to debug some c++ code. At the moment the code I'm looking at iterates through an array of pointers, which are either a pointer to some object or a NULL pointer.
If I just display list[index]->member it'll complain when list[index] is null. Is there anyway to display the member only if list[index] is not ... | Since display accepts arbitrary expressions, you can try something like the following display command:
display (list[index]) ? list[index]->member : "null"
I'm not sure if that cleans things up well enough for what you want - you'll still get a display, but it won't be a complaint.
|
6,392,635 | 6,393,224 | Fastest way to convert an unsigned char image to a float image on iPhone | I need to convert an unsigned char image (640x480x1) or smaller to a float image for processing. I can't do fixed-point computation in this case due to the problem complexity. I currently use the neon unit in a two-step process. The neon can convert an integer to an float fairly fast, but not an unsigned char to float.... |
If you're going to use a LUT anyway, just fill it with the necessary floats.
If you don't mind a requirement of iOS 4, see vDSP_vflt8()
EDIT: "unsigned char to int conversion" merely involves adding some zero bytes at the right places. The obvious way is to perform the necessary shifts, then VDUP to clear a vector, a... |
6,392,740 | 6,392,802 | How to receive an iterator of strings on STL algorithm | I need to develop an algorithm for a library that receives a "list of strings".
Of course I want to pass an "abstract" iterator to decouple the internal representation of that list (a vector, a linked list, a map...) to the access to it from my function.
This is my approach:
template <typename ForwardIterator>
void myA... | Use a static assertion along with std::iterator_traits<>:
template<typename ForwardIterator>
void myAlgorithm(ForwardIterator itBegin, ForwardIterator itEnd) {
typedef typename std::iterator_traits<ForwardIterator>::value_type value_t;
BOOST_STATIC_ASSERT((
boost::is_same<value_t, std::string>::value ||... |
6,392,843 | 6,392,959 | beginner question about arrays in structs in C++ | I would like to create a struct and use it inside an other struct as an array. My problem is that I don't know how big array I would like to allocate, I will only know once I am in a function. I mean I would like to use [] instead of a pre-determined constant, like 10000.
I think if you look at my code it would be self... | If it suits your purpose, an STL container (std::vector) is easily one of the best options - the less memory management you have to worry about, the better.
In any case, look at the struct definition Nawaz posted above - that's exactly how it should be. Dynamic arrays in C++ are simply pointers. You have, however, allo... |
6,392,918 | 6,392,956 | New Object variations | This is a very newbie question, but something completely new to me. In my code, and everywhere I have seen it before, new objects are created as such...
MyClass x = new MyClass(factory);
However, I just saw some example code that looks like this...
MyClass x(factory);
Does that do the same thing?
| Not at all.
The first example uses dynamic memory allocation, i.e., you are allocating an instance of MyClass on the heap (as opposed to the stack). You would need to call delete on that pointer manually or you end up with a memory leak. Also, operator new returns a pointer, not the object itself, so your code woul... |
6,392,999 | 6,393,019 | How do |= and &= work? | I want to make an enum in such a way that I can & parameters after |ing them in.
Can I simply do:
enum Things
{
Something,
SomethingElse
};
Or must I be careful to give them specific numbers for this to work?
Also if a value, like say, 3, has already been |='d in, would |= it in again cause this to malfunction (as ... | Then define your enum as:
enum Things
{
Something = 1 //0000 0001
SomethingElse = 2; //0000 0010
SomethingX = 4; //0000 0100
SomethingY = 8; //0000 1000
SomethingZ = 16; //0001 0000
};
The idea is, only one bit in the binary representation should be 1, others should be 0, as shown in ... |
6,393,034 | 6,393,199 | Why does Visual Studio's intellisense show private members and functions? | When working with native c++ in Visual Studio, intellisense shows private members and functions even when outside the scope of the containing class. This makes it hard to create clean APIs for the classes I write.
Is there a reason for this? Can this be prevented?
| Well, why shouldn't it show the private ones as well? They are members, after all, they exist and they are perfectly accessible from certain contexts, just like any other members.
It would be very difficult for the IntelliSense to determine whether the members are accessible or not from this specific context, especial... |
6,393,060 | 6,415,416 | Reading raw data file, getting different values in Matlab and C++ | I'm converting some code from Matlab (which I'm not familiar with) to C++. Part of the code reads in a raw data file and inputs every 8 bits into an element of a matrix.
MATLAB:
header=fread(fid, 512, '*uint8');
Similarly, in C++ I have:
fread(&q1[0][0], sizeof(uint8_t), 512, filepath);
These are both reading the sa... | Turns out, Matlab was pre-processing the raw file that I was sending in, which changed the headers. Although the files were "copies" (as far as windows was concerned), their headers were different giving me different values when printing out the beginning of the raw data.
|
6,393,123 | 6,393,762 | UDP broadcasting for LAN computer discovery & server setup | I'm working on a small, networked game prototype which will be played on LANs using UDP. For the discovery of other computers on the network, I've been investigating broadcasting. However, I'm still unsure about a few details regarding UDP socket setup/usage (networking newbie). I found a good library to use after t... |
Yes, you can send broadcasts, send unicasts and receive packets (either broadcast or unicast) all from a single socket. This is VERY useful for making "reply to sender" work.
Not every socket needs to use bind. If you don't, a port will be chosen for you automatically. But someone has to bind a pre-shared port numb... |
6,393,412 | 6,393,444 | Sending/receiving packets on networked computers with different UDP ports | If I have two or more computers on a LAN communicating via UDP, do they all have to be using the same port to be able to receive messages from one another? For example, say my desktop is using port 1550 to send a message and my notebook, which is also on the LAN, is using port 3746 to listen for and receive messages. ... | For a UDP or TCP endpoint an address and port must be set. The initiator must know what address-port to send to. The receiver can use the getpeername() call to determine the address-port combination of the sender and then use this information to build up the address structure for a reply message. The two do not need... |
6,393,458 | 6,393,516 | Choosing a computer on a LAN to act as a server | I'm working on a small networked game (LAN only) with one computer acting as a server and all others (including the actual game running on the same computer) acting as clients. Essentially, the server is transparent to users, but exists to simplify state management for me. The basic concept I have now is that each pl... | To be honest with you, I would make the decision a little more complicated than that. I would be inclined to do some basic information gathering to determine which computer has the most power and elect that one to be the sever (power is intentionally a vague term because the most powerful computer will depend on the r... |
6,393,467 | 6,393,513 | dynamic cast Entities A good design? | For my game,
Everything inherits from Entity, then other things like Player, PhysicsObject, etc, inherit from Entity. The physics engine sends collision callbacks which has an Entity* to the B that A collided on. Then, lets say A is a Bullet, A tries to cast the entity as a player, if it succeeds, it reduces the playe... | I believe that messaging system is somehow better suits your "world".
Entity* target = ...;
bool handled = target->send(M_COLLIDE, ...);
In this case you will not need neither dynamic casts nor to check result of dynamic cast.
Update, here is an example:
target->send(M_COLLECT, pMushroom);
...
Person::handle(uint... |
6,393,678 | 6,393,708 | Should a message system use enum, string, or #define? | In terms of a message system for a game, or in general, in C++, which of these three is better? An enum feels best but I think it would mean newer classes could not really contribute. Strings seem nice for scripting advantages but I'm worried about the overhead. Integer defines feel a bit Cish.
Thanks
| It all depends on what you are trying to do, what kind of data is in the messages (variable vs fixed-length), frequency of messaging, size of messages, etc. For example, I have seen messaging systems that use struct and union to package low level messages.
There is no one right way to do it, at least not without more ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.