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,959,476 | 2,964,279 | C++ Adding 2 arrays together quickly | Given the arrays:
int canvas[10][10];
int addon[10][10];
Where all the values range from 0 - 100, what is the fastest way in C++ to add those two arrays so each cell in canvas equals itself plus the corresponding cell value in addon?
IE, I want to achieve something like:
canvas += another;
So if canvas[0][0] =3 and addon[0][0] = 2 then canvas[0][0] = 5
Speed is essential here as I am writing a very simple program to brute force a knapsack type problem and there will be tens of millions of combinations.
And as a small extra question (thanks if you can help!) what would be the fastest way of checking if any of the values in canvas exceed 100? Loops are slow!
| Here is an SSE4 implementation that should perform pretty well on Nehalem (Core i7):
#include <limits.h>
#include <emmintrin.h>
#include <smmintrin.h>
static inline int canvas_add(int canvas[10][10], int addon[10][10])
{
__m128i * cp = (__m128i *)&canvas[0][0];
const __m128i * ap = (__m128i *)&addon[0][0];
const __m128i vlimit = _mm_set1_epi32(100);
__m128i vmax = _mm_set1_epi32(INT_MIN);
__m128i vcmp;
int cmp;
int i;
for (i = 0; i < 10 * 10; i += 4)
{
__m128i vc = _mm_loadu_si128(cp);
__m128i va = _mm_loadu_si128(ap);
vc = _mm_add_epi32(vc, va);
vmax = _mm_max_epi32(vmax, vc); // SSE4 *
_mm_storeu_si128(cp, vc);
cp++;
ap++;
}
vcmp = _mm_cmpgt_epi32(vmax, vlimit); // SSE4 *
cmp = _mm_testz_si128(vcmp, vcmp); // SSE4 *
return cmp == 0;
}
Compile with gcc -msse4.1 ... or equivalent for your particular development environment.
For older CPUs without SSE4 (and with much more expensive misaligned loads/stores) you'll need to (a) use a suitable combination of SSE2/SSE3 intrinsics to replace the SSE4 operations (marked with an * above) and ideally (b) make sure your data is 16-byte aligned and use aligned loads/stores (_mm_load_si128/_mm_store_si128) in place of _mm_loadu_si128/_mm_storeu_si128.
|
2,959,502 | 2,960,065 | Linking Error Building 64bit Qt app on 32bit XP machine | I'm trying to build a 64 bit version of my application (and yes I really do need the memory) on my 32bit xp dev box for production testing on our Vista64 server.
Previously, I have built w/o any errors the Qt 4.6.2 DLL's in 64 bit mode. That step went vary smooth.
Just to get started in building production, I'm trying to rebuild Qt's Star Delegate demo in 64bit mode. I converted the 32bit to 64bit app by changing the application configuration and adjusting the library's to the 64bit venisons. Now, when I go to link, I'm getting the following error when I link
1>------ Build started: Project: stardelegate, Configuration: Release x64 ------
1>Linking...
1>MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external symbol WinMain
1>release64\stardelegate.exe : fatal error LNK1120: 1 unresolved externals
Suggestions?
edit - After some more searching, discovered if I link as a console app it will work and run. But not as a windows app. And I don't have this problem in 32 bit mode.
| qt application 64 bit windows
Edit: Nevermind, you found it. You need to link against qtmain if you are not using CMake or qmake as stated here: http://doc.qt.io/archives/4.6/modules.html.
You don't need to accept this as I didn't find it, but just so future people see the answer and don't get confused.
|
2,959,535 | 2,959,838 | c++ Function pointer inlining | I know I can pass a function pointer as a template parameter and get a call to it inlined but I wondered if any compilers these days can inline an 'obvious' inline-able function like:
inline static void Print()
{
std::cout << "Hello\n";
}
....
void (*func)() = Print;
func();
Under Visual Studio 2008 its clever enough to get it down to a direct call instruction so it seems a shame it can't take it a step further?
| GNU's g++ 4.5 inlines it for me starting at optimization level -O1
main:
subq $8, %rsp
movl $6, %edx
movl $.LC0, %esi
movl $_ZSt4cout, %edi
call _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_E
movl $0, %eax
addq $8, %rsp
ret
where .LC0 is the .string "Hello\n".
To compare, with no optimization, g++ -O0, it did not inline:
main:
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movq $_ZL5Printv, -8(%rbp)
movq -8(%rbp), %rax
call *%rax
movl $0, %eax
leave
ret
|
2,959,631 | 2,959,846 | Can an out-of-process COM object determine its parent process? | From an out-of-process COM object (LocalServer32) can I determine the client process that requested the creation of the object? - to be specific I need to get hold of the client processes command line.
This question arrises because (due to poor standardisation, implementation and support) the potential 3rd party clients of the object have a variety of idiosyncracies which the object needs to workaround.
To do this the object needs to be able to identify its current client.
Extending the interface of the COM object so that the client can identify itself is unfortunately not possible ... or to be more precise the interface can be extended but I won't be able to get the clients to call the extension.
| Having looked into this further I suspect the answer is going to be "NO", but by all means tell me I'm wrong.
Using Process Explorer I can see that the parent process for my COM object is an instance of "svchost.exe", and not the client application.
|
2,960,176 | 2,960,383 | MFC: Best way to get text from a CRichEdit? | I've got a CRichEdit that I need to get the text from. What is the best way to do that? GETTEXTEX? StreamOut? If I go the StreamOut approach, what would my callback look like?
| It's inherited from CWnd so you should just be able to use GetWindowText().
CString returnText;
yourRichEdit.GetWindowText(returnText);
|
2,960,193 | 2,960,216 | What is the difference between NULL in C++ and null in Java? | I've been trying to figure out why C++ is making me crazy typing NULL. Suddenly it hits me the other day; I've been typing null (lower case) in Java for years. Now suddenly I'm programming in C++ and that little chunk of muscle memory is making me crazy.
Wikiperipatetic defines C++ NULL as part of the stddef:
A macro that expands to a null pointer
constant. It may be defined as
((void*)0), 0 or 0L depending on the
compiler and the language.
Sun's docs tells me this about Java's "null literal":
The null type has one value, the null
reference, represented by the literal
null, which is formed from ASCII
characters. A null literal is always
of the null type.
So this is all very nice. I know what a null pointer reference is, and thank you for the compiler notes. Now I'm a little fuzzy on the idea of a literal in Java so I read on...
A literal is the source code
representation of a fixed value;
literals are represented directly in
your code without requiring
computation.
There's also a special null literal
that can be used as a value for any
reference type. null may be assigned
to any variable, except variables of
primitive types. There's little you
can do with a null value beyond
testing for its presence. Therefore,
null is often used in programs as a
marker to indicate that some object is
unavailable.
Ok, so I think I get it now. In C++ NULL is a macro that, when compiled, evaluates to the null pointer constant. In Java, null is a fixed value that any non-primitive can be assigned too; great for testing in a handy if statement.
Java does not have pointers, so I can see why they kept null a simple value rather than anything fancy. But why did java decide to change the all caps NULL to null?
Furthermore, am I missing anything here?
| Java's null is more like C++0x's nullptr. NULL in C++ is just 0 and can end up resolving to int rather than a pointer like you'd want. Consider:
void f(int);
void f(char*);
...
f(NULL); // which f()?
C++0x has nullptr, which fixes that problem but it's still not going to be totally equivalent to Java's null. They're just different languages.
Oh, and another diff is that Java has no pointers (or so it says). In Java you can legitimately assign null to a reference, in C++ you can't do that without having already used an ill-formed construct. Admittedly, Java would be next to useless without this ability but it's definitely another important difference.
|
2,960,434 | 2,960,540 | C Population Count of unsigned 64-bit integer with a maximum value of 15 | I use a population count (hamming weight) function intensively in a windows c application and have to optimize it as much as possible in order to boost performance. More than half the cases where I use the function I only need to know the value to a maximum of 15. The software will run on a wide range of processors, both old and new. I already make use of the POPCNT instruction when Intel's SSE4.2 or AMD's SSE4a is present, but would like to optimize the software implementation (used as a fall back if no SSE4 is present) as much as possible.
Currently I have the following software implementation of the function for 64bit (platform) mode:
int population_count64(unsigned __int64 w) {
w -= (w >> 1) & 0x5555555555555555ULL;
w = (w & 0x3333333333333333ULL) + ((w >> 2) & 0x3333333333333333ULL);
w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
return int((w * 0x0101010101010101ULL) >> 56);
}
So to summarize:
(1) I would like to know if it is possible to optimize this for the case when I only want to know the value to a maximum of 15.
(2) Is there a faster software implementation (for both Intel and AMD CPU's) than the function above (for unsigned 64bit integers)?
| It is indeed possible to optimise your function for the "maximum 15" case. The following shaves off a few operations:
inline int population_count64_max15(unsigned __int64 w)
{
w -= (w >> 1) & 0x5555555555555555ULL;
w = (w & 0x3333333333333333ULL) + ((w >> 2) & 0x3333333333333333ULL);
return int((w * 0x1111111111111111ULL) >> 60);
}
Inlining the function (using the inline keyword as above) should also increase performance.
|
2,960,496 | 2,960,543 | Why is NULL/0 an illegal memory location for an object? | I understand the purpose of the NULL constant in C/C++, and I understand that it needs to be represented some way internally.
My question is: Is there some fundamental reason why the 0-address would be an invalid memory-location for an object in C/C++? Or are we in theory "wasting" one byte of memory due to this reservation?
| The null pointer does not actually have to be 0. It's guaranteed in the C spec that when a constant 0 value is given in the context of a pointer it is treated as null by the compiler, however if you do
char *foo = (void *)1;
--foo;
// do something with foo
You will access the 0-address, not necessarily the null pointer. In most cases this happens to actually be the case, but it's not necessary, so we don't really have to waste that byte. Although, in the larger picture, if it isn't 0, it has to be something, so a byte is being wasted somewhere
Edit: Edited out the use of NULL due to the confusion in the comments. Also, the main message here is "null pointer != 0, and here's some C/pseudo code that shows the point I'm trying to make." Please don't actually try to compile this or worry about whether the types are proper; the meaning is clear.
|
2,960,554 | 2,960,580 | correct way to store an exception in a variable | I have an API which internally has some exceptions for error reporting. The basic structure is that it has a root exception object which inherits from std::exception, then it will throw some subclass of that.
Since catching an exception thrown in one library or thread and catching it in another can lead to undefined behavior (at least Qt complains about it and disallows it in many contexts). I would like to wrap the library calls in functions which will return a status code, and if an exception occurred, a copy of the exception object.
What is the best way to store an exception (with it's polymorphic behavior) for later use? I believe that the c++0x future API makes use of something like this. So what is the best approach?
The best I can think of is to have a clone() method in each exception class which will return a pointer to an exception of the same type. But that's not very generic and doesn't deal with standard exceptions at all.
Any thoughts?
EDIT: It seems that c++0x will have a mechanism for this. It is described as "library magic". Does that mean that is doesn't require any of the language features of c++0x? if not, are there any implementations which are compatible with c++03?
EDIT: Looks like boost has an implementation of exception copying. I'll keep the question open for any non boost::copy_exception answers.
EDIT: To address j_random_hacker's concerns about the root cause of the exception being an out of memory error. For this particular library and set of exceptions, this is not the case. All exceptions derived from the root exception object represent different types of parsing errors caused by invalid user input. Memory related exceptions will simply cause a std::bad_alloc to be thrown which is addressed separately.
| You have what would be what I think is your best, only answer. You can't keep a reference to the original exception because it's going to leave scope. You simply have to make a copy of it and the only generic way to do that is with a prototype function like clone().
Sorry.
|
2,960,682 | 2,960,701 | Explicit type conversion | I have read in a book that specifies this :
//: C03:SimpleCast.cpp
int main() {
int b = 200;
unsigned long a = (unsigned long int)b;
} ///:~
"Casting is powerful, but it can cause headaches because in some
situations it forces the compiler to treat data as if it were (for
instance) larger than it really is, so it will occupy more space in
memory; this can trample over other data. This usually occurs
when casting pointers, not when making simple casts like the one
shown above."
Now can You please provide an example where casting pointer can trample other data?
| int main(void)
{
short int a = 5;
short int b = 7;
*(long int*)&a = 0;
}
Assuming sizeof(long) > sizeof(short), and assuming the compiler puts a on the stack before b, b will be trashed.
|
2,960,775 | 2,960,817 | Proper way to handle issue when porting 32 to 64 bit. Conversion from DT1 to DT2 of greater size | So I am trying to port 32 bit to 64 bit.
I have turned on the VS2008 flag for detecting problems with 64 bit.
I am trying following:
char * pList = (char *)uiTmp);
warning C4312: 'type cast' : conversion from 'unsigned int' to 'char *' of greater size
Disregard the code itself. This is also true for any pointer, because 64 bit pointer is greater than 32 bit unsigned int or int for that purpose.
Given that you have to cast smaller type to greater how would you go about doing it so it correctly on both 32/64 bit systems
| This is not a warning you can ignore, it will bomb in 64-bit code. An unsigned int cannot store a pointer. There's no magic cast that will make this work.
Review your code and rethink storing pointer values in an unsigned int. It should probably be a void*. If you #include <windows.h> then you can use UINT_PTR.
|
2,960,869 | 3,010,570 | DUMP in unhandled C++ exception | In MSVC, how can I make any unhandled C++ exception (std::runtime_error, for instance) crash my release-compiled program so that it generates a dump with the full stack from the exception throw location?
I have installed NTSD in the AeDebug registry and can generate good dumps for things like memory access violation, so the matter here comes down to crashing the program correctly, I suppose.
Thanks in advance.
| I finally cracked it down.
Use the set_terminate() function to register a handler for every thread
In you main function(), make it impossible for external DLLs (event Windows') to successfully call SetUnhandledExceptionFilter(). A great article on how to do that here: http://www.debuginfo.com/articles/debugfilters.html#overwrite .
As for the handle itself, it is quite straightforward:
void Terminate()
{
OutputDebugStringA("Terminate\r\n");
RaiseException(0xE0000010, EXCEPTION_NONCONTINUABLE, 0, 0);
}
Calling RaiseException() like the above example is enough to make the process crash and produce my mush desired dump.
Just so you know, the problem I was having was:
The IPHelper Windows API loads dynamically another Windows DLL
This DLL uses Windows own version of the C runtime (MSVCRT instead of MSVCRT90)
The new C++ runtime calls SetUnhandledExceptionFilter() on startup to catch C++ exceptions. Since the latest filter for C++ exceptions is the one who gets to call the handle set by set_terminate(), my handle wasn't called.
|
2,961,115 | 2,961,249 | How to populate wxListCtrl? | I'm trying to populate a wxListCtrl but after trying various methods can't seem to be able to populate it with items.
Basically, I want a list control that would have three columns with headings and will show values in rows. But I've tried InsertItem, SetItem, or InsertColumn methods but am only able to show the column headings but not the row data. Any help will be greatly appreciated! Thanks in advance!
| You can add columns like this:
int column_width = 90;
my_list_ctrl->InsertColumn(0, L"ColumnText", wxLIST_FORMAT_LEFT, column_width);
You can add items like this:
int image_index = 0;
long list_index = my_list_ctrl->InsertItem(0, L"My Item text", image_index);
You can set the text of the subitems like this:
int column_index = 1;
my_list_ctrl->SetItem(list_index, column_index, L"Text");
You can setup an image list for your list like this:
my_list_ctrl->SetImageList(&img_list, wxIMAGE_LIST_SMALL);
|
2,961,127 | 2,961,434 | Casting a byte array to a struct pointer depends on endianness or memory alignment? | Suppose this code:
unsigned char list[3] = { 1, 2, 3 };
struct _struct{
unsigned char a;
unsigned char b;
unsigned char c;
} *s;
s = ( _struct * ) list;
Can I assume that always s->a == 1, s->b == 2, s->c == 3 ?
Or it will depend on the system's endianness or memory alignment?
| Let's dissect this.
In all cases, sizeof(char) == 1, and the list array will have its three members at memory locations list, list + 1, and list + 2.
The situation with the struct is not quite as clear. The Standard guarantees that the members will be allocated in increasing memory locations, but not that they will be contiguous. The compiler is free to introduce padding between members, and padding at the end.
Therefore, s->a == 1 will always be true. If the implementation puts the unsigned chars in the struct adjacent (and most will), then the other equalities will necessarily be true.
By the way, calling a struct _struct may cause problems. A name beginning with an underscore in the global namespace is reserved for the implementation.
|
2,961,207 | 2,961,258 | And now for a complete change of direction from C++ function pointers | I am building a part of a simulator. We are building off of a legacy simulator, but going in different direction, incorporating live bits along side of the simulated bits. The piece I am working on has to, effectively route commands from the central controller to the various bits.
In the legacy code, there is a const array populated with an enumerated type. A command comes in, it is looked up in the table, then shipped off to a switch statement keyed by the enumerated type.
The type enumeration has a choice VALID_BUT_NOT_SIMULATED, which is effectively a no-op from the point of the sim. I need to turn those no-ops into commands to actual other things [new simulated bits| live bits]. The new stuff and the live stuff have different interfaces than the old stuff [which makes me laugh about the shill job that it took to make it all happen, but that is a topic for a different discussion].
I like the array because it is a very apt description of the live thing this chunk is simulating [latching circuits by row and column]. I thought that I would try to replace the enumerated types in the array with pointers to functions and call them directly. This would be in lieu of the lookup+switch.
| Can't be done. However, you could do something sort of like it with a functor. I'd put example code but as I was writing it I realized such a construct would necessarily be quite complicated. You might look at boost::bind for some ideas.
|
2,961,407 | 2,961,446 | Can you explicitly set a structure layout/alignment in C++ as you can in C#? | In C# you have nice alignment attributes such as this:
[StructLayout(LayoutKind.Explicit)]
public struct Message
{
[FieldOffset(0)]
public int a;
[FieldOffset(4)]
public short b;
[FieldOffset(6)]
public int c;
[FieldOffset(22)] //Leave some empty space just for the heck of it.
public DateTime dt;
}
Which gives you fine control on how you need your structure to be layed out in memory. Is there such a thing in standard C++?
| Compilers typically support that via a #pragma but it's not something that is included in the C++ standard and, thus, is not portable.
For an example with the Microsoft compiler, see: http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx
|
2,961,431 | 2,961,464 | Which design pattern is most appropriate? | I want to create a class that can use one of four algorithms (and the algorithm to use is only known at run-time). I was thinking that the Strategy design pattern sounds appropriate, but my problem is that each algorithm requires slightly different parameters. Would it be a bad design to use strategy, but pass in the relevant parameters into the constructor?.
Here is an example (for simplicity, let's say there are only two possible algorithms) ...
class Foo
{
private:
// At run-time the correct algorithm is used, e.g. a = new Algorithm1(1);
AlgorithmInterface* a;
};
class AlgorithmInterface
{
public:
virtual void DoSomething() = 0;
};
class Algorithm1 : public AlgorithmInterface
{
public:
Algorithm1( int i ) : value(i) {}
virtual void DoSomething(){ // Does something with int value };
int value;
};
class Algorithm2 : public AlgorithmInterface
{
public:
Algorithm2( bool b ) : value(b) {}
virtual void DoSomething(){ // Do something with bool value };
bool value;
};
| It would be a valid design because the Strategy pattern asks for an interface to be defined and any class that implements it is a valid candidate to run the strategy code, regardless how it is constructed.
|
2,961,488 | 2,961,514 | Can I use a switch to hold a function? | I have a 3 file program, basically teaching myself c++. I have an issue. I made a switch to use the math function. I need and put it in a variable, but for some reason I get a zero as a result.
Also another issue, when I select 4 (divide) it crashes... Is there a reason?
Main file:
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
int opersel;
int c;
int a;
int b;
string test;
int main(){
cout << "Welcome to Math-matrix v.34"<< endl;
cout << "Shall we begin?" <<endl;
//ASK USER IF THEY ARE READY TO BEGIN
string answer;
cin >> answer;
if(answer == "yes" || answer == "YES" || answer == "Yes")
{
cout << "excellent lets begin..." << endl;
cout << "please select a operator..." << endl << endl;
cout << "(1) + " << endl;
cout << "(2) - " << endl;
cout << "(3) * " << endl;
cout << "(4) / " << endl;
cin >> opersel;
switch(opersel){
case 1:
c = add(a,b);
break;
case 2:
c = sub(a,b);
break;
case 3:
c = multi(a,b);
break;
case 4:
c = divide(a,b);
break;
default:
cout << "error... retry" << endl;
}// end retry
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
cout << c;
cin >> test;
}else if (answer == "no" || answer == "NO" || answer == "No"){
}//GAME ENDS
}// end of int main
Here is my math.h file
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
int sub(int a, int b);
int multi(int a, int b);
int divide(int a, int b);
#endif
Here is my math.cpp:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int multi(int a, int b)
{
return a * b;
}
int divide(int a, int b)
{
return a / b;
}
}// end of int main
| You're calling your functions with a and b before you get the data from the user. Try saving the math function that they selected when they enter it, and move your switch to after you have asked them for a and b.
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
int opersel;
int c;
int a;
int b;
string test;
int main(){
cout << "Welcome to Math-matrix v.34"<< endl;
cout << "Shall we begin?" <<endl;
//ASK USER IF THEY ARE READY TO BEGIN
string answer;
cin >> answer;
if(answer == "yes" || answer == "YES" || answer == "Yes")
{
cout << "excellent lets begin..." << endl;
cout << "please select a operator..." << endl << endl;
cout << "(1) + " << endl;
cout << "(2) - " << endl;
cout << "(3) * " << endl;
cout << "(4) / " << endl;
cin >> opersel;
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
switch(opersel){
case 1:
c = add(a,b);
break;
case 2:
c = sub(a,b);
break;
case 3:
c = multi(a,b);
break;
case 4:
c = divide(a,b);
break;
default:
cout << "error... retry" << endl;
}// end retry
cout << c;
cin >> test;
}else if (answer == "no" || answer == "NO" || answer == "No"){
}//GAME ENDS
}// end of int main
|
2,961,504 | 2,961,764 | Help with Assembly/SSE Multiplication | I've been trying to figure out how to gain some improvement in my code at a very crucial couple lines:
float x = a*b;
float y = c*d;
float z = e*f;
float w = g*h;
all a, b, c... are floats.
I decided to look into using SSE, but can't seem to find any improvement, in fact it turns out to be twice as slow. My SSE code is:
Vector4 abcd, efgh, result;
abcd = [float a, float b, float c, float d];
efgh = [float e, float f, float g, float h];
_asm {
movups xmm1, abcd
movups xmm2, efgh
mulps xmm1, xmm2
movups result, xmm1
}
I also attempted using standard inline assembly, but it doesn't appear that I can pack the register with the four floating points like I can with SSE.
Any comments, or help would be greatly appreciated, I mainly need to understand why my calculations using SSE are slower than the serial C++ code?
I'm compiling in Visual Studio 2005, on a Windows XP, using a Pentium 4 with HT if that provides any additional information to assit.
Thanks in advance!
| As you've found out, just replacing a couple of instructions with SSE is not going to work because you need to shuffle the data around in memory in order to load the SSE registers correctly, and this moving data around in memory (the bit that constructs the arrays) is going to kill your performance as memory is very slow (hard disk aside, memory is invariably the bottleneck these days).
Also, there is no way to move data between the SSE and the FPU/ALU without using a write to RAM followed by a read. Modern IA32 chips cope well with this particular pattern (write then read) but will still invalidate some cache which will have a knock on effect.
To get the best out of SSE you need to look at the whole algorithm and the data the algorithm uses. The values of a,b,c and d and e, f, g and h need to permanently in those arrays so that there is no shifting data around in memory prior to loading the SSE registers. It is not straightforward and may require a lot of reworking of your code and data (you may need to store the data differently on disk).
It might also be worth pointing out the SSE is only 32bit (or 64bit if you use doubles) whereas the FPU is 80bit (regardless of float or double) so you will get slightly different results when using SSE compared to using the FPU. Only you know if this will be an issue.
|
2,961,725 | 2,961,776 | How to debug properly and find causes for crashes? | I dont know what to do anymore... its hopeless. I'm getting tired of guessing whats causing the crashes. Recently i noticed some opengl calls crashes programs randomly on some gfx cards. so i am getting really paranoid what can cause crashes now. The bad thing on this crash is that it crashes only after a long time of using the program, so i can only guess what is the problem.
I cant remember what changes i made to the program that may cause the crashes, its been so long time. But luckily the previous version doesnt crash, so i could just copypaste some code and waste 10 hours to see at which point it starts crashing... i dont think i want to do that yet.
The program crashes after i make it to process the same files about 5 times in a row, each time it uses about 200 megabytes of memory in the process. It crashes at random times while and after the reading process.
I have createn a "safe" free() function, it checks the pointer if its not NULL, and then frees the memory, and then sets the pointer to NULL. Isn't this how it should be done?
I watched the task manager memory usage, and just before it crashed it started to eat 2 times more memory than usual. Also the program loading became exponentially slower every time i loaded the files; first few loads didnt seem much slower from each other, but then it started rapidly doubling the load speeds. What should this tell me about the crash?
Also, do i have to manually free the c++ vectors by using clear() ? Or are they freed after usage automatically, for example if i allocate vector inside a function, will it be freed every time the function has ended ? I am not storing pointers in the vector.
--
Shortly: i want to learn to catch the damn bugs as fast as possible, how do i do that? Using Visual Studio 2008.
| A "random" crash that occurs sometime after a complex operation is almost certainly the result of heap corruption. Heap corruption bugs are a bitch, since they usually manifest themselves very far away from the place that actually caused the bug. My suggestion, since you're on Windows, is to use Application Verifier, which can be freely downloaded from MS.
Launch AV, configure it to watch your program, and turn on all of the memory-related options. Then run your program under a debugger. (These two things will make your program run extremely slow.) The extra checks that AV does will hopefully cause your program to crash at a different place than you've been seeing so far, but it will be the location that's the real cause of the bug.
|
2,961,765 | 2,963,172 | C++ code parser/processor library | is there any library that parse a source code of C++ to produce lets say, call graph, class inheritance tree, flow control, class member list or anything as a ready to use graph or structure in code (not in diagram image).
to make it more clear, suppose to generate call graph image, there will be a process like this:
`
C++ source -> parser -> intermediate structure -> renderer -> call graph image
^
|
[i need this]
`
| It depends on how precise you want the parsing to be. If you want it to be absolutely accurate (i.e. shouldn't miss a class because of some overcomplicated macro or template metaprogramming that it couldn't handle), then you need a proper C++ front end for this, and I'm not aware of any that are both free and easily reusable.
If you're willing to pay, then there are at least two options:
Semantic Design frontend
Edison Design Group frontend
EDG is used to drive IntelliSense in VC++2010, which is pretty impressive, and seems to be very accurate - in my experience, it handled completion on polymorphic Boost.Lambda properly (not surprising, given that it also drives EDG C++ compiler, which obviously have to get correct input).
I don't know much about Semantic Design frontend or its users, but Ira Baxter from there is on StackOverflow, so I'll leave it to him to provide more extensive information about their product.
If you want free but imperfect, then perhaps GCC_XML is good enough for you.
|
2,961,980 | 2,962,013 | C++ for small, individual projects (i.e. hobby programming) | I recently started C++. I am using PHP right now and decided to take a look at C++. Web programming had me working with a couple of languages, with a couple of people. I wanted to do programming where I only had to bother with one language and create small utility apps (mostly not web-based). I wanted a compiled, strongly-type language without memorizing a tome of classes. Basically I wanted to learn C++ for the following:
mobile programming (I don't ever want to go touching Java, and I don't have a Mac for Objective C or IPhone SDK)
small desktop apps like DTRs, POSs
creating small desktop-based games
creating small Air-like applications that can access the web for additional content
I heard that C++ is not beginner-friendly and is mostly used for huge projects with lots of calculations and fine details (like 3D games). Is it practical or even possible for me to use C++ for the above cases? (Sorry, I haven't delved on C++ that much yet, so aside from "huge, monolithic project", I don't know any other uses for it)
| You can certainly use C++ in all the areas you mention, though whether it is best of breed for any of them is open to debate. C++ is very large and complex language, and requires a fair bit of effort to get up to speed on. If I were you, I would pick one of the areas you mention that you are most interested in, and then find out which language(s) are best suited for that area and learn that.
If you are set on learning C++ you will need to read at least one book on it - you cannot learn it from internet resources alone. See this question The Definitive C++ Book Guide and List for a book list.
|
2,962,085 | 2,962,105 | how to do trig functions to data in Windows textboxes | must you convert from strings to double? if so. how?
Are there functions for trig that will accept textbox string data as is?
Is there a way to pull the data from the textbox as a numeric value, not as a string?
|
must you convert from strings to double?
Yes.
if so. how?
The C++ way is to use the string streams; in particular, you'll probably want to use istringstream. A viable alternative is to follow the C way, i.e. use sscanf with the appropriate format specifier ("%f").
Another C++ option is to use the boost lexical_cast, but starting to use boost just for lexical_cast is a bit overkill in my opinion.
Example with istringstream:
#include <sstream>
// ...
std::istringstream strParser(yourString);
double yourDouble;
strParser>>yourDouble;
if(strParser.fail())
{
// the string couldn't be converted to a double
}
else if(!strParser.eof())
{
// the string hasn't been fully consumed; this may or may not be a problem, depending on your needs
}
Are there functions for trig that will accept textbox string data as is?
AFAIK no, there's no need of them (although you can write them quite easily).
Is there a way to pull the data from the textbox as a numeric value, not as a string?
The WinAPIs provide a handful of such "convenience functions" for use in dialogs, but the only one I can recall that provides such help is GetDlgItemInt, which, as the name may suggest, works only for integers.
Addendum
I see now that you are using C++/CLI (you mentioned System::String): well, you should have said that, this changes the options quite a bit.
In the managed world, your best option is to use the Double::Parse method; to catch bad-formatted strings, you should either catch the exceptions thrown by Double::Parse or call Double::TryParse before calling Double::Parse.
Addendum bis
Uh, I forgot, since you're using the .NET Framework probably it should be better to use the .NET trigonometric functions (class System.Math).
|
2,962,153 | 2,962,169 | How can I find if an arbitrary process is running under wow64? | I need a tool which will discover whether an arbitrary process is running in x86 or x64 mode on a machine. I need to do this programatically from C++, based on a process ID.
There has to be some way to do this (as you can clearly see it from the task manager). Does anyone know of a windows api that will tell you, given a process ID, whether the application is running under wow64?
Another approach would be to figure out, based on the process id, the executable name/path that is running and try to read the PE headers out of the file. Does anyone have a code snippet that would accomplish that?
| There is a WinAPI function, IsWow64Process.
|
2,962,210 | 3,093,154 | Compile JavaScript to Native Code with V8 | Is it really possible, with Google's V8 Engine, to compile JavaScript into Native Code, save it as a binary file, and execute it whenever I want through my software envorinment, on any machine?
| You can use the V8 snapshot functionality to precompile the code. This still means that you have to have a full version of V8 running to load the snapshot (i.e., you don't get stand-alone native code, it needs to run inside the V8 VM), so all you save is the compilation time.
Also, the quality of snapshot code isn't necessarily as good as JIT'ed code because JIT code can use, e.g., SSE2/SSE3 if it's available, which snapshots can't assume.
|
2,962,223 | 2,962,298 | How do you hook a C++ compiled dll function to a sql database? | I want to do something like:
lastName SIMILARTO(lastName, 'Schwarseneger', 2)
where lastName is the field in the database, 'Schwarseneger' is the value that lastName field is being compared to and 2 is the maximum number of characters (edit distance) that can differ between the lastName field, and the entered value.
I can implement the SIMILARTO function in C++ using the Levenshtein distance (http://en.wikipedia.org/wiki/Levenshtein_distance), but how do hook the function in a dll to a mySQL implementation?
| See MySQL 5.1 Reference Manual :: 22.3.2 Adding a New User-Defined Function
This blog post also have detailed instructions for building User Defined Function DLLs on Windows.
|
2,962,233 | 2,962,465 | how can we avoid allocation done by Marshal::StringToHGlobalAnsi? | My wrapper from managed to unmanaged is handling a lot of data and this function Marshal::StringToHGlobalAnsi would call new for each of them, which is a big hit for me. So my question is:
Can I allocate a chunk of unmanaged memory and use it to convert the managed data types to unmanaged by hand?
| Assuming all of the characters in the System::String are in the ASCII range, the most basic implementation would be something like:
void ConvertAndCopy(System::String^ ms, char* us)
{
for (int i(0); i < ms->Length; ++i)
us[i] = static_cast<char>(ms[i]);
us[ms->Length] = '\0';
}
// usage example:
System::String^ ms = "Hello world";
char us[12] = "";
ConvertAndCopy(ms, us);
Note that this performs no bounds-checking on the destination array and does not do any character set conversion.
Whether this performs any better than StringToHGlobalAnsi or whether any performance gains are worth the significant increase in complexity (namely, managing your own memory and handling character set conversions), I have no idea.
|
2,962,287 | 2,962,310 | How would I instruct extconf.rb to use additional g++ optimization flags, and which are advisable? | I'm using Rice to write a C++ extension for a Ruby gem. The extension is in the form of a shared object (.so) file.
This requires 'mkmf-rice' instead of 'mkmf', but the two (AFAIK) are pretty similar.
By default, the compiler uses the flags -g -O2. Personally, I find this kind of silly, since it's hard to debug with any optimization enabled. I've resorted to editing the Makefile to take out the flags I don't like (e.g., removing -fPIC -shared when I need to debug using main() instead of Ruby's hooks).
But I figure there's got to be a better way. I know I can just do
$CPPFLAGS += " -DRICE"
to add additional flags. But how do I remove things without editing the Makefile directly?
A secondary question: what optimizations are safe for shared objects loaded by Ruby? Can I do things like -funroll-loops? What do you all recommend?
It's a scientific computing project, so the faster the better. Memory is not much of an issue.
| The quick and dirty way is to append -O0 to CXXFLAGS, which will turn off optimization. Later options will override earlier ones.
As far as safety for a plugin, you should be able to do anything that doesn't affect the ABI. Without testing, I don't see why -funroll would. Of course, safe does not imply better. As noted by the man page, "-funroll-loops makes code larger, and may or may not make it run faster."
|
2,962,553 | 2,962,570 | Real World strtod(); for use with WINAPI textbox | ResultBox1->Text = (sin(TextBox1->Text)) * TextBox2->Text
That is what i would like to work, but im dealing with Strings
I cant seem to convert the strings, do the trig, and convert back to string for displaying properly... anyone with an example?
| System::Convert::ToDouble(TextBox1->Text)
You said you're trying to convert a System::String^ so this should work for you.
|
2,962,589 | 2,963,843 | What do I name this class whose sole purpose is to report failure? | In our system, we have a number of classes whose construction must happen asynchronously. We wrap the construction process in another class that derives from an IConstructor class:
class IConstructor {
public:
virtual void Update() = 0;
virtual Status GetStatus() = 0;
virtual int GetLastError() = 0;
};
There's an issue with the design of the current system - the functions that create the IConstructor-derived classes are often doing additional work which can also fail. At that point, instead of getting a constructor which can be queried for an error, a NULL pointer is returned.
Restructuring the code to avoid this is possible, but time-consuming. In the meantime, I decided to create a constructor class which we create and return in case of error, instead of a NULL pointer:
class FailedConstructor : public IConstructor
public:
virtual void Update() {}
virtual Status GetStatus() { return STATUS_ERROR; }
virtual int GetLastError() { return m_errorCode; }
private: int m_errorCode;
};
All of the above this the setup for a mundane question: what do I name the FailedConstructor class? In our current system, FailedConstructor would indicate "a class which constructs an instance of Failed", not "a class which represents a failed attempt to construct another class".
I feel like it should be named for one of the design patterns, like Proxy or Adapter, but I'm not sure which.
EDIT: I should make it clear that I'm looking for an answer that adheres to, ideally, one of the GoF design patterns, or some other well-established naming convention for things of this nature.
| I'd name it NullConstructor in line with the null object pattern, which is the pattern you're using. See http://en.wikipedia.org/wiki/Null_Object_pattern
|
2,962,767 | 2,962,801 | When did C++ get nested classes? | Somehow I never noticed until today that C++ supports nested classes. This surprised me because when I was learning C++ back in the '90s, I specifically remember nested classes being something that Object Pascal and Java had, but which C++ did not. I asked an old programmer friend about it and he concurred that he recalls C++ not having nested classes.
Is my recollection of C++ not having nested classes mistaken, or were they actually added to the standard at some point in the past fifteen years? I tried searching Google for information on this topic and I haven't come up with anything helpful yet.
It could also be that I'm thinking of nested functions, which Pascal certainly supports but C does not.
| Nested classes were added in CFront 3.0, released in 1993.
EDIT It goes back even earlier, as you can see in the table of contents to The Annotated C++ Reference Manual (1990).
|
2,962,852 | 2,962,861 | debug error : max must have union class struct types | this is my code:
#include <iostream>
using namespace std;
class Sp
{
private :
int a;
int b;
public:
Sp(int x = 0,int y = 0) : a(x), b(y) { };
int max(int x,int y);
};
int Sp::max(int a,int b) { return (a > b ? a : b); };
int main()
{
int q,q1;
cin >> q >>q1;
Sp *mm = new Sp(q,q1);
cout << mm.max(q,q1);
return 0;
}
| Instead of: mm.max(q,q1);
you need to use: mm->max(q,q1);
mm is a pointer and needs to be addressed as such.
Alternately, you could just say:
Sp mm(q,q1);
cout<< mm.max(q,q1);
and avoid pointers all together.
|
2,962,959 | 2,962,997 | understanding the anatomy of file formats and image formats | I am trying to do some research on file formats especially image formats. Information such as header layouts for particular types of image formats and how to parse them using C++. If anyone can point me in the right direction of some good tutorials or books. that would be helpful. thanks
[edit]
If there are any resources on the general layout of a file format and what and what not to look out for in formats that will be beneficial as well
| An indispensible source of information in this regard http://www.wotsit.org .
You can also find some good info at the Amiga File Formats page (don't get misled by the "Amiga" in the title -- many of those formats are still used, and it's a great source of information).
Also, a good source of information is magicdb.org, where you might especially be interested in the designing a new file format page. However, before you do that, be sure to check out the general purpose formats like AIFF, TIFF, IFF and RIFF -- one might suit your need, and there's no need to reinvent the wheel.
|
2,963,283 | 2,963,308 | sigwait in Linux (Fedora 13) vs OS X | So I'm trying to create a signal handler using pthreads which works on both OS X and Linux. The code below works on OS X but doesn't work on Fedora 13.
The application is fairly simple. It spawns a pthread, registers SIGHUP and waits for a signal. After spawning the signal handler I block SIGHUP in the main thread so the signal should only be sent to the signal_handler thread.
On OS X this works fine, if I compile, run and send SIGHUP to the process it prints "Got SIGHUP". On Linux it just kills the process (and prints Hangup). If I comment out the signal_handler pthread_create the application doesn't die.
I know the application gets to the sigwait and blocks but instead of return the signal code it just kills the application.
I ran the test using the following commands:
g++ test.cc -lpthread -o test
./test &
PID="$!"
sleep 1
kill -1 "$PID"
test.cc
#include <pthread.h>
#include <signal.h>
#include <iostream>
using namespace std;
void *signal_handler(void *arg) {
int sig;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
while (true) {
cout << "Wait for signal" << endl;
sigwait(&set, &sig);
if (sig == SIGHUP) {
cout << "Got SIGHUP" << endl;
}
}
}
int main() {
pthread_t handler;
sigset_t set;
// Create signal handler
pthread_create(&handler, NULL, signal_handler, NULL);
// Ignore SIGHUP in main thread
sigfillset(&set);
sigaddset(&set, SIGHUP);
pthread_sigmask(SIG_BLOCK, &set, NULL);
for (int i = 1; i < 5; i++) {
cout << "Sleeping..." << endl;
sleep(1);
}
pthread_join(handler, NULL);
return 0;
}
| The POSIX spec for sigwait() says:
The signals defined by set shall have
been blocked at the time of the call
to sigwait(); otherwise, the behavior
is undefined.
You're not doing this. If you add:
pthread_sigmask(SIG_BLOCK, &set, NULL);
to your signal_handler() function immediately after the sigaddset(), then it works correctly.
|
2,963,356 | 2,963,381 | C++ forward declaration problem | I have a header file that has some forward declarations but when I include the header file in the implementation file it gets included after the includes for the previous forward declarations and this results in an error like this.
error: using typedef-name ‘std::ifstream’ after ‘class’
/usr/include/c++/4.2.1/iosfwd:145: error: ‘std::ifstream’ has a previous declaration.
class ifstream;
class A
{
ifstream *inStream;
}
// End of A.h
#include <ifstream>
using std::ifstream;
#include "A.h"
// etc
Whats the norm for working around this?
Thanks in advance.
| Don't forward declare std:ifstream - just import <iosfwd> instead.
ifstream is a typedef.
See here for further details: http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/group__s27__2__iosfwd.html
|
2,963,396 | 2,963,451 | GCC doesn't like C++ style casts with spaces | I am porting some C++ code to GCC, and apperantly it isn't happy with C++ style casting when sapces are involved, as in unsigned int(-1), long long(ShortVar) etc... It gives an error: expected primary-expression before 'long'.
Is there any way to make peace with GCC without going over each one of those and rewrite in c-style?
| GCC is correctly crying -- unsigned int(-1) is a notation that is not conformant with the C++03 standard (5.4.2):
An explicit type conversion can be expressed using functional notation (5.2.3), a type conversion operator (dynamic_cast, static_cast, reinterpret_cast, const_cast), or the cast notation:
cast-expression:
unary-expression
( type-id ) cast-expression
Ergo, you can either correct the cast with the parenthesis, follow the excellent suggestions proposed by GMan :) -- and I'd truly recommend the latter.
Edit: the functional notation requires a simple-type-specifier:
5.2.3 - A simple-type-specifier (7.1.5) followed by a parenthesized expression-list constructs a value of the specified type given the expression list.
Simple type specifiers do not include the composite ones (the ones with spaces).
|
2,963,539 | 2,963,554 | Guidelines to an Iterator Class | I have a Red Black tree implemented in c++. It supports the functionality of a STL map. Tree nodes contain keys and the values mapped. I want to write an iterator class for this, but I'm stuck with how to do it. Should I make it an inner class of the Tree class? Can anyone give me some guidelines on how to write it + some resources??
Thank You!!
| Sure, read this nice article on writing STL iterators, it might give you the needed overview:
http://www.drdobbs.com/184401417
In general, yes, an inner class is good, because the iterator needs access to your implementation specific tree nodes:
struct container { ...
public:
struct iterator {
// these typedefs are needed if you want to be STL compatible
typedef std::forward_iterator_tag iterator_category;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
// the element points to your implementation node
iterator( element* init = 0 ) : current(init) {}
T& operator*() { return current->data; } // dereference
const T& operator*() const { return current->data; }
iterator& operator++() { // prefix
if ( current ) current = current->next;
return *this;
}
iterator operator++(int) { // postfix
iterator temp = *this;
++*this;
return temp;
}
bool operator==(const iterator& x) const { return current == x.current; }
bool operator!=(const iterator& x) const { return current != x.current; }
private:
// the element points to your implementation node
element* current;
}
...
The good thing here is that while the iterator is public, the element can still stay private :). And yes, the code above is STL compilant too!
|
2,963,842 | 2,963,869 | Friends, templates, overloading << | I'm trying to use friend functions to overload << and templates to get familiar with templates. I do not know what these compile errors are:
Point.cpp:11: error: shadows template parm 'class T'
Point.cpp:12: error: declaration of 'const Point<T>& T'
for this file
#include "Point.h"
template <class T>
Point<T>::Point() : xCoordinate(0), yCoordinate(0)
{}
template <class T>
Point<T>::Point(T xCoordinate, T yCoordinate) : xCoordinate(xCoordinate), yCoordinate(yCoordinate)
{}
template <class T>
std::ostream &operator<<(std::ostream &out, const Point<T> &T)
{
std::cout << "(" << T.xCoordinate << ", " << T.yCoordinate << ")";
return out;
}
My header looks like:
#ifndef POINT_H
#define POINT_H
#include <iostream>
template <class T>
class Point
{
public:
Point();
Point(T xCoordinate, T yCoordinate);
friend std::ostream &operator<<(std::ostream &out, const Point<T> &T);
private:
T xCoordinate;
T yCoordinate;
};
#endif
My header also gives the warning:
Point.h:12: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Point<T>&)' declares a non-template function
Which I was also unsure why. Any thoughts? Thanks.
| Both the template parameter and the function parameter have the same name. Change it to something like:
template <class T>
std::ostream &operator<<(std::ostream &out, const Point<T> &point)
{
std::cout << "(" << point.xCoordinate << ", " << point.yCoordinate << ")";
return out;
}
The declaration of the friend function in the header should be changed too:
template <class G>
friend std::ostream &operator<<(std::ostream &out, const Point<G> &point);
|
2,963,965 | 2,964,003 | Why is 'virtual' optional for overridden methods in derived classes? | When a method is declared as virtual in a class, its overrides in derived classes are automatically considered virtual as well, and the C++ language makes this keyword virtual optional in this case:
class Base {
virtual void f();
};
class Derived : public Base {
void f(); // 'virtual' is optional but implied.
};
My question is: What is the rationale for making virtual optional?
I know that it is not absolutely necessary for the compiler to be told that, but I would think that developers would benefit if such a constraint was enforced by the compiler.
E.g., sometimes when I read others' code I wonder if a method is virtual and I have to track down its superclasses to determine that. And some coding standards (Google) make it a 'must' to put the virtual keyword in all subclasses.
| Yeah, it would really be nicer to make the compiler enforce the virtual in this case, and I agree that this is a error in design that is maintained for backwards compatibility.
However there's one trick that would be impossible without it:
class NonVirtualBase {
void func() {};
};
class VirtualBase {
virtual void func() = 0;
};
template<typename VirtualChoice>
class CompileTimeVirtualityChoice : public VirtualChoice {
void func() {}
};
With the above we have compile time choice wether we want virtuality of func or not:
CompileTimeVirtualityChoice<VirtualBase> -- func is virtual
CompileTimeVirtualityChoice<NonVirtualBase> -- func is not virtual
... but agreed, it's a minor benefit for the cost of seeking a function's virtuality, and myself, I always try to type virtual everywhere where applicable.
|
2,964,266 | 2,964,371 | display 25 randomnumbers from an array | I have in C++ an array of 100 elements, so v[1], ... ,v[100] contains numbers. How can i display, 25 random numbers from this array? So i wanna select 25 random positions from this array and display the values.. How can i do this in C++?
Thanks!
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int aleator(int n)
{
return (rand()%n)+1;
}
int main()
{
int r;
int indexes[100]={0};
// const int size=100;
//int a[size];
std::vector<int>v;
srand(time(0));
for (int i=0;i<25;i++)
{
int index = aleator(100);
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ;
}
cout<<" "<<endl;
system("pause");
return 0;
}
The idea is that i have this code, and i generate 100 random numbers. What i want is an array with random 25 elements from those 100 generated.. But i don't know how to do that
Regards
| I modified the version of Mehdi a little in order to make it choose differnet indexes
NOTE: This makes the algorithm not deterministic - it relies on the RNG.
int indexes[100]={0};
srand ( time (0) );
for (int i=0;i<25;i++)
{
int index = rand() % 100;
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ; cout << endl;
}
|
2,964,391 | 2,970,128 | Preventing multiple process instances on Linux | What is the best way on Linux platform for the process (C++ application) to check its instance is not already running?
| The standard way to do this is to create a pidfile somewhere, typically containing the pid of your program.
You don't need to put the pid in there, you could just put an exclusive lock on it. If you open it for reading/writing and flock it with LOCK_EX | LOCK_NB, it will fail if the file is already locked. This is race-condition free, and the lock will be automatically released if the program crashes.
Normally you'd want to do it per-user, so the user's home directory is a good place to put the file.
If it's a daemon, somewhere like /var/run is better.
|
2,964,516 | 2,964,777 | Using pointers, references, handles to generic datatypes, as generic and flexible as possible | In my application I have lots of different data types, e.g. Car, Bicycle, Person, ... (they're actually other data types, but this is just for the example).
Since I also have quite some 'generic' code in my application, and the application was originally written in C, pointers to Car, Bicycle, Person, ... are often passed as void-pointers to these generic modules, together with an identification of the type, like this:
Car myCar;
ShowNiceDialog ((void *)&myCar, DATATYPE_CAR);
The 'ShowNiceDialog' method now uses meta-information (functions that map DATATYPE_CAR to interfaces to get the actual data out of Car) to get information of the car, based on the given data type. That way, the generic logic only has to be written once, and not every time again for every new data type.
Of course, in C++ you could make this much easier by using a common root class, like this
class RootClass
{
public:
string getName() const = 0;
};
class Car : public RootClass
{
...
};
void ShowNiceDialog (RootClass *root);
The problem is that in some cases, we don't want to store the data type in a class, but in a totally different format to save memory.
In some cases we have hundreds of millions of instances that we need to manage in the application, and we don't want to make a full class for every instance.
Suppose we have a data type with 2 characteristics:
A quantity (double, 8 bytes)
A boolean (1 byte)
Although we only need 9 bytes to store this information, putting it in a class means that we need at least 16 bytes (because of the padding), and with the v-pointer we possibly even need 24 bytes.
For hundreds of millions of instances, every byte counts (I have a 64-bit variant of the application and in some cases it needs 6 GB of memory).
The void-pointer approach has the advantage that we can almost encode anything in a void-pointer and decide how to use it if we want information from it (use it as a real pointer, as an index, ...), but at the cost of type-safety.
Templated solutions don't help since the generic logic forms quite a big part of the application, and we don't want to templatize all this. Additionally, the data model can be extended at run time, which also means that templates won't help.
Are there better (and type-safer) ways to handle this than a void-pointer?
Any references to frameworks, whitepapers, research material regarding this?
| If you don't want a full class, you should read up on FlyWeight pattern. It's designed to save up memory.
EDIT: sorry, lunch-time pause ;)
The typical FlyWeight approach is to separate properties that are common to a great number of objects from properties that are typical of a given instance.
Generally, it means:
struct Light
{
kind_type mKind;
specific1 m1;
specific2 m2;
};
The kind_type is often a pointer, however it is not necessary. In your case it would be a real waste because the pointer itself would be 4 times as big as the "useful" information.
Here I think we could exploit padding to store the id. After all, as you said it's going to be expanded to 16 bits even though we only use 9 of them, so let's not waste the other 7!
struct Object
{
double quantity;
bool flag;
unsigned char const id;
};
Note that the order of elements is important:
0x00 0x01 0x02 0x03
[ ][ ][ ][ ]
quantity flag id
0x00 0x01 0x02 0x03
[ ][ ][ ][ ]
id flag quantity
0x00 0x02 0x04
[ ][ ][ ][ ][ ][ ]
id -- quantity flag --
I don't understand the "extended at runtime" bit. Seems scary. Is this some sort of self-modifying code ?
Template allow to create a very interesting form of FlyWeight: Boost.Variant.
typedef boost::variant<Car,Dog,Cycle, ...> types_t;
The variant can hold any of the types cited here. It can be manipulated by "normal" functions:
void doSomething(types_t const& t);
Can be stored in containers:
typedef std::vector<types_t> vector_t;
And finally, the way to operate over it:
struct DoSomething: boost::static_visitor<>
{
void operator()(Dog const& dog) const;
void operator()(Car const& car) const;
void operator()(Cycle const& cycle) const;
void operator()(GenericVehicle const& vehicle) const;
template <class T>
void operator()(T const&) {}
};
It's very interesting to note the behavior here. Normal function overload resolution occurs, therefore:
If you have a Car or a Cycle you'll use those, every other child of GenericVehicle will us the 4th version
It's possible to specify a template version as a catch them all, and specify it appropriately.
I shall note that non-template methods can perfectly be defined in a .cpp file.
In order to apply this visitor, you use the boost::apply_visitor method:
types_t t;
boost::apply_visitor(DoSomething(), t);
// or
boost::apply_visitor(DoSomething())(t);
The second way seems odd, but it means you can use it in a most interesting fashion, as predicate:
vector_t vec = /**/;
std::foreach(vec.begin(), vec.end(), boost::apply_visitor(DoSomething()));
Read up on variant, it's most interesting.
Compile time check: you missed one operator() ? the compiler throws up
No necessity of RTTI: no virtual pointer, no dynamic type --> as fast as using a union, but with increased safety
You can of course segment your code, by defining multiple variants. If some sections of the code only deal with 4/5 types, then use a specific variant for it :)
|
2,964,654 | 3,549,297 | Member is inaccessible from friend class | I have a declaration like this
#include "Output/PtPathWriter.h"
// class PtPathWriter // I've also tried forward declaring the friend class
// leg data is a class designed to hold data for a single leg.
class PtPathLeg
{
friend class PtPathWriter; // doesn't work
//friend void PTPathWriter::writeToFile(string fileName, PtPath* path); // works
protected:
vector<map<int, shared_ptr<BoardingStopAlternative>>> m_boarding_stop_alternatives;
// some other stuff
}
However I get an error from PtPathWriter saying
PtPathWriter.cpp(44): error #308: member "PtPathLeg::m_boarding_stop_alternatives" (declared at line 79 of "../include/Paths/PtPathLeg.h") is inaccessible
1> path->m_leg_data.at(legnr).m_boarding_stop_alternatives.at(stopId);
Interestingly, if I use the alternate friend declaration (which specifies the method explicitly) it does work? Any thoughts on why they are different?
Using Intel C++ Compiler 11.1.065 btw.
| Your little t should be a capital T in P**t**PathWriter.
|
2,964,702 | 2,964,723 | C++ program crashes at runtime | I have this simple c++ program
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int aleator(int n)
{
return (rand()%n)+1;
}
int main()
{
int r;
int indexes[100]={0};
// const int size=100;
//int a[size];
std::vector<int>v;
srand(time(0));
for (int i=0;i<25;i++)
{
int index = aleator(100);
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ;
}
cout<<" "<<endl;
system("pause");
return 0;
}
But at runtime it crashes, so i got that error with 'Send error report' and 'Don't send'. What i'm doing wrong? Thanks!
| aleator() returns a number between 1 and n, inclusive. However, this means it may return 100, which is outside the bounds of indexes[].
So get rid of the +1 in aleator().
Also, your vector v is of size zero. You can't ask for v[index] unless v[index] exists...
|
2,965,010 | 2,965,031 | What does static linking against a library actually do? | Say I had a library called libfoo which contained a class, a few static variables, possibly something with 'C' linkage, and a few other functions.
Now I have a main program which looks like this:
int main() {
return 5+5;
}
When I compile and link this, I link against libfoo.
Will this have any effect? Will my executable increase in size? If so, why? Do the static variables or their addresses get copied into my executable?
Apologies if there is a similar question to this or if I'm being particularly stupid in any way.
| It won't do anything in a modern linker, because it knows the executable doesn't actually use libfoo's symbols. With gcc 4.4.1 and ld 2.20 on my system:
g++ linker_test.cpp -static -liberty -lm -lz -lXp -lXpm -o linker_test_unnecessary
g++ linker_test.cpp -static -o linker_test_none
ls -l linker_test_unnecessary linker_test_none
They are both 626094 bytes. Note this also applies to dynamic linking, though the size they both are is much lower.
|
2,965,011 | 2,965,082 | Using static variable in function vs passing variable from caller | I have a function which spawns various types of threads, one of the thread types needs to be spawned every x seconds. I currently have it like this:
bool isTime( Time t )
{
return t >= now();
}
void spawner()
{
Time t = now();
while( 1 )
{
if( isTime( t ) )//is time is called in more than one place in the real function
{
//launchthread and recalculation of t only happens once in real function
launchthread()
t = now() + offset;
}
}
}
but I'm thinking of changing it to:
bool isTime()
{
static Time t = now();
if( t >= now() )
{
t = now() + offset;
return true;
}
return false;
}
void spawner()
{
while( 1 )
{
if( isTime() )
launchthread();
}
}
I think the second way is neater but I generally avoid statics in much the same way I avoid global data; anyone have any thoughts on the different styles?
| Apart from the problem I cited in the comments to the question, you should avoid clever tricks like the plague. The first form (after fixing the bug) is cleaner and easier to understand. The second form, OTOH, confuses the reader by giving the impression that the assignment to t and the test t >= now() happen immediately after each other, who, on realising that its static, then has to try to grok the algorithm a second time.
Also, you can never reset the second function or use it from multiple threads.
|
2,965,018 | 2,965,071 | C++ Add this pointer to a container by calling it in base class constructor | class Base
{
public:
Base (int a, int b);
private:
int a,b;
};
class Derived1
{
public:
Derived1():base(1,2){}
};
similarly Derived2, Derived 3 which doesnt contain any data members on its own
Now i need to contain these derived objects in a singleton, so i was thinking to call this in base constructor like
Base::Base(int a, int b)
{
CBaseMgr::GetInstance()->AddtoVector(this);
}
so now if i construct
Derived d1, d2, d3 etc. will the Singleton's container contain all derived objects?
My doubt is can i do this adding of objects to container in base ctor or should i do in derived ctor.?
| If all the derived class call this base class constructor, yes, you should be fine.
Just beware of the copy constructor which, if not overloaded, will not add this to your global vector.
I suppose you want as well remove the instances that were destroyed, from the global vector ?
If so, don't forget to declare Base::~Base to be virtual, so that he gets called by derived classes.
|
2,965,487 | 3,024,500 | How can I hash a password and store it for later verification with another digest? | I am using gsoap's wsseapi plugin and would like to store hashed sha1 passwords rather than plain text. I have spent a ridiculous amount of time experimenting with various methods of hashing the plain text password for storage.
Can anyone suggest a way to hash a password so it can be later verified against a username token digest sent by the client?
I can't seem to get the client password to authenticate against my stored hash.
| Seems that the plain text password is required at both sides. This is so that on the server, the password stored is hashed using the nonce created at the client side and then the password hashes are compared.
I thought there may have been a way for the client to enter a normal alphanumeric password and for the server to retrieve a pre-stored hashed up version of the same password for comparison. Seems this isn't possible because of the nonce, timestamp etc
|
2,965,495 | 2,965,546 | Constructor is being invoked twice | In code:
//file main.cpp
LINT a = "12";
LINT b = 3;
a = "3";//WHY THIS LINE INVOKES CTOR?
std::string t = "1";
//LINT a = t;//Err NO SUITABLE CONV FROM STRING TO LINT. Shouldn't ctor do it?
//file LINT.h
#pragma once
#include "LINT_rep.h"
class LINT
{
private:
typedef LINT_rep value_type;
const value_type* my_data_;
template<class T>
void init_(const T&);
public:
LINT(const char* = 0);
LINT(const std::string&);
LINT(const LINT&);
LINT(const long_long&);
LINT& operator=(const LINT&);
virtual ~LINT(void);
LINT operator+()const; //DONE
LINT operator+(const LINT&)const;//DONE
LINT operator-()const; //DONE
LINT operator-(const LINT&)const;//DONE
LINT operator*(const LINT&)const;//DONE
LINT operator/(const LINT&)const;///WAITS FOR APPROVAL
LINT& operator+=(const LINT&);//DONE
LINT& operator-=(const LINT&);//DONE
LINT& operator*=(const LINT&);//DONE
LINT operator/=(const LINT&);///WAITS FOR APPROVAL
};
in line number 3 instead of assignment optor ctor is invoked. Why? I'm willing to uppload entire solution on some server otherwise it's hard to put everything in here. I can also upload video file. Another thing is that when I implement this assignment optor I'm getting an error that this optor is already in obj file? What's going on?
| You don't have an = operator which takes a RHS of std::string (or char*), so, the literal '3' is being constructed to a LINT, and then assigned using your = operator.
EDIT: As for the 2nd question in your code, you need to call c_str() on the std::string to get the char* buffer of the string, then the same thing will happen as with your literal 3.
|
2,965,555 | 2,965,745 | Equivalence of boolean expressions | I have a problem that consist in comparing boolean expressions ( OR is +, AND is * ). To be more precise here is an example:
I have the following expression: "A+B+C" and I want to compare it with "B+A+C". Comparing it like string is not a solution - it will tell me that the expressions don't match which is of course false. Any ideas on how to compare those expressions?
Any ideas about how can I tackle this problem? I accept any kind of suggestions but (as a note) the final code in my application will be written in C++ (C accepted of course).
An normal expression could contain also parenthesis:
(A * B * C) + D or A+B*(C+D)+X*Y
Thanks in advance,
Iulian
| I think the competing approach to exhaustive (and possibly exhausting) creation of truth tables would be to reduce all your expressions to a canonical form and compare those. For example, rewrite everything into conjunctive normal form with some rule about the ordering of symbols (eg alphabetical order within terms) and terms (eg alphabetical by first symbol in term). This of course, requires that symbol A in one expression is the same as symbol A in another.
How easy it is to write (or grab from the net) a C or C++ function for rewriting your expressions into CNF I don't know. However, there's been a lot of AI work done in C and C++ so you'll probably find something when you Google.
I'm also a little unsure about the comparative computational complexity of this approach and the truth-table approach. I strongly suspect that it's the same.
Whether you use truth tables or a canonical representation you can of course keep down the work to be done by splitting your input forms into groups based on the number of different symbols that they contain.
EDIT: On reading the other answers, in particular the suggestion to generate all truth tables and compare them, I think that @Iulian has severely underestimated the number of possible truth tables.
Suppose that we settle on RPN to write the expressions, this will avoid having to deal with brackets, and that there are 10 symbols, which means 9 (binary) operators. There will be 10! different orderings of the symbols, and 2^9 different orderings of the operators. There will therefore be 10! x 2^9 == 1,857,945,600 rows in the truth table for this expression. This does include some duplicates, any expression containing only 'and' and 'or' for instance will be the same regardless of the order of symbols. But I'm not sure I can figure this any further ...
Or am I making a big mistake ?
|
2,965,684 | 2,965,711 | C++ - Error: expected unqualified-id before ‘using’ | I have a C++ program and when I try to compile it it gives an error:
calor.h|6|error: expected unqualified-id before ‘using’|
Here's the header file for the calor class:
#ifndef _CALOR_
#define _CALOR_
#include "gradiente.h"
using namespace std;
class Calor : public Gradiente
{
public:
Calor();
Calor(int a);
~Calor();
int getTemp();
int getMinTemp();
void setTemp(int a);
void setMinTemp(int a);
void mostraSensor();
};
#endif
Why does this happen?
This class inherits from gradiente:
#ifndef _GRADIENTE_
#define _GRADIENTE_
#include "sensor.h"
using namespace std;
class Gradiente : public Sensor
{
protected:
int vActual, vMin;
public:
Gradiente();
~Gradiente();
}
#endif
Which in turn inherits from sensor
#ifndef _SENSOR_
#define _SENSOR_
#include <iostream>
#include <fstream>
#include <string>
#include "definicoes.h"
using namespace std;
class Sensor
{
protected:
int tipo;
int IDsensor;
bool estadoAlerta;
bool estadoActivo;
static int numSensores;
public:
Sensor(/*PARAMETROS*/);
Sensor(ifstream &);
~Sensor();
int getIDsensor();
bool getEstadoAlerta();
bool getEstadoActivo();
void setEstadoAlerta(int a);
void setEstadoActivo(int a);
virtual void guardaSensor(ofstream &);
virtual void mostraSensor();
// FUNÇÃO COMUM
/* virtual int funcaoComum() = 0;
virtual int funcaoComum(){return 0;};*/
};
#endif
For completeness' sake, here's definicoes.h
#ifndef _DEFINICOES_
#define _DEFINICOES_
const unsigned int SENSOR_MOVIMENTO = 0;
const unsigned int SENSOR_SOM = 1;
const unsigned int SENSOR_PRESSAO = 2;
const unsigned int SENSOR_CALOR = 3;
const unsigned int SENSOR_CONTACTO = 4;
const unsigned int MIN_MOVIMENTO = 10;
const unsigned int MIN_SOM = 10;
const unsigned int MIN_PRESSAO = 10;
const unsigned int MIN_CALOR = 35;
#endif
What am I doing wrong?
| There is a semicolon missing at the end of this class:
class Gradiente : public Sensor
{
protected:
int vActual, vMin;
public:
Gradiente();
~Gradiente();
} // <-- semicolon needed after the right curly brace.
Also, the names of your include guards are illegal. Names that begin with an underscore and an uppercase letter are reserved for the C++ implementation (as are names containing a double underscore) - you are not allowed to create such names in your own code. And you should never use:
using namespace std;
in a header file. And lastly, the destructor in your Sensor base class should almost certainly be made virtual.
|
2,965,819 | 2,965,833 | can i add .h and .cpp files in a c# project? | I want to add some .h and .cpp files to a C# project to get the C++ functionality in C#. I want to use the code directly without making a dll.
Can i do so? How?
| No you cannot. If the amount of code is small, you can write a C# class and paste pieces of the C++ code into it so that you essentially ported that class into C#. Obviously this won't work if you're using a language feature or library function that is not in C#. Alternatively you need to compile your C++ code into something executable (either a native DLL, ideally C-style flat functions, or a managed assembly) so that you can call it from your C# code.
|
2,965,864 | 3,584,680 | What is your favorite/recommended project structure and file structure for Unit Testing using Boost? | I have not used Unit Testing so far, and I intend to adopt this procedure. I was impressed by TDD and certainly want to give it a try - I'm almost sure it's the way to go.
Boost looks like a good choice, mainly because it's being maintained. With that said, how should I go about implementing a working and elegant file-structure and project-structure ? I am using VS 2005 in Win XP. I have been googling about this and was more confused than enlightened.
| Our Boost based Testing structure looks like this:
ProjectRoot/
Library1/
lib1.vcproj
lib1.cpp
classX.cpp
...
Library2/
lib2.vcproj
lib2.cpp
toolB.cpp
classY.cpp
...
MainExecutable/
main.cpp
toolA.cpp
toolB.cpp
classZ.cpp
...
Tests/
unittests.sln
ut_lib1/
ut_lib1.vcproj (referencing the lib1 project)
ut_lib1.cpp (with BOOST_AUTO_TEST_CASE) - testing public interface of lib1
ut_classX.cpp - testing of a class or other entity might be split
into a separate test file for size reasons or if the entity
is not part of the public interface of the library
...
ut_lib2/
ut_lib2.vcproj (referencing the lib2 project)
ut_lib2.cpp (with BOOST_AUTO_TEST_CASE) - testing public interface of lib2
...
ut_toolA/
ut_toolA.vcproj (referencing the toolA.cpp file)
ut_toolA.cpp - testing functions of toolA
ut_toolB/
ut_toolB.vcproj (referencing the toolB.cpp file)
ut_toolB.cpp - testing functions of toolB
ut_main/
ut_main.vcproj (referencing all required cpp files from the main project)
ut_classZ.cpp - testing classZ
...
This structure was chosen for a legacy project, where we had to decide on a case-by-case basis on what tests to add and how to group test-projects for existing modules of sourcecode.
Things to note:
Unit Testing code is always compiled separately from production code.
Production projects do not reference the unit testing code.
Unit Testing projects include source-files directly or only reference libraries, depending on what makes sense given the use of a certain code-file.
Running the unit tests is done via a post-build step in each ut_*.vcproj
All our production builds automatically also run the unit tests. (In our build scripts.)
In our real (C++) world you have to make tradeoffs btw. legacy issues, developer convenience, compile times, etc. I think our project structure is a good tradeoff. :-)
|
2,965,927 | 2,965,986 | C++ new & delete and functions | This is a bit unclear to me... So, if I have a function:
char *test(int ran){
char *ret = new char[ran];
// process...
return ret;
}
and then call it multiple times:
for(int i = 0; i < 100000000; i++){
char *str = test(rand()%10000000+10000000);
// process...
// delete[] str; // do i have to delete it here?
}
So the question is, do I have to use delete[] for each new[] call?
| You don't have to. But if you don't delete memory you reserved with 'new' you will start running out of memory eventually (memory leak).
|
2,966,207 | 2,966,304 | C++ macro definition unclear | Is this a macro defintion for a class or what exactly is it?
#define EXCEPTIONCLASS_IMPLEMENTATION(name, base, string) : public base \
{ \
public: \
name() : base(string) {} \
name(const x::wrap_exc& next) : base(string,next) {}; \
name(const x::wrap_exc& prev, const x::wrap_exc& next) : \
base(prev, next) {}; \
}
| It is a macro definition for an exception class.
It looks somebody wants you to write code like this:
class my_exception EXCEPTIONCLASS_IMPLEMENTATION(my_exception, std::exception, "What a mess!")
The pre-processor will spit out:
class my_exception : public std::exception { public: my_exception() : std::exception("What a mess!") {} my_exception(const x::wrap_exc& next) : std::exception("What a mess!",next) {}; my_exception(const x::wrap_exc& prev, const x::wrap_exc& next) : std::exception(prev, next) {}; }
What exactly is it?
It is an abomination!
|
2,966,323 | 2,968,774 | boost::asio and socket ownership | I've two classes (Negotiator, Client), both has their own boost::asio::ip::tcp::socket. Is there a way to transfer socket object to Client after negotiation is finished. I'm looking forward to do something like that:
boost::asio::ip::tcp::socket sock1(io);
//...
boost::asio::ip::tcp::socket sock2;
sock2.assign(sock1);
This operation must guarantee that the connection won't be closed when sock1 is destroyed.
| I think that you could:
obtain sock1's native handle with the native() member function
dup() (or WSADuplicateSocket()) sock1's native handle
pass the dup()-ed handle to sock2 with the assing() member function
However:
I'm not sure as I never tried that
If you want to transfer (instead of sharing) the socket from Negotiator to Client, Dan's suggestion of using dynamic allocation is probably simpler, using unique_ptr (or auto_ptr)
|
2,966,413 | 2,966,484 | Windows/C++: detect when focus has changed between windows (globally) | I'm trying to find a way to detect when focus is changed to another window (without having to poll every X ms).
I've already figured out a way to detect when focus is switched between applications using WH_SHELL and HSHELL_ACTIVATESHELLWINDOW.
The problem is I want to detect when focus is switched between dialog/windows within the same app.
ie. In Notepad, I can determine when the app switches to Notepad, but I cannot detect when the "Open" or "Save" dialogs appear because the focus is still within the same application.
| You can use SetWindowsHookEx with a WH_CBT hook type. If you just want to detect focus changes within an application, pass GetCurrentThreadId() as the last parameter, otherwise the hook will be for all threads on the current desktop.
Note that using windows hooks can have an adverse effect on system performance, so the hook should only be installed when necessary and you should do a minimum amount of work in the hook procedure.
|
2,966,493 | 2,966,522 | C++ new & delete and string & functions | Okay the previous question was answered clearly, but i found out another problem.
What if I do:
char *test(int ran){
char *ret = new char[ran];
// process...
return ret;
}
And then run it:
for(int i = 0; i < 100000000; i++){
string str = test(rand()%10000000+10000000);
// process...
// no need to delete str anymore? string destructor does it for me here?
}
So after converting the char* to string, I don't have to worry about the deleting anymore?
Edit: As answered, I have to delete[] each new[] call, but on my case its not possible since the pointer got lost, so the question is: how do I convert char to string properly?
| Here you are not converting the char* to a [std::]string, but copying the char* to a [std::]string.
As a rule of thumb, for every new there should be a delete.
In this case, you'll need to store a copy of the pointer and delete it when you're done:
char* temp = test(rand()%10000000+10000000);
string str = temp;
delete[] temp;
|
2,966,510 | 2,968,497 | How to install and run the examples of QtOpenCl, i.e. Qt in OpenCl? | The thing is I have to run the OpenCl examples, as given here:http://labs.trolltech.com/blogs/2010/04/07/using-opencl-with-qt/.
The problem is that I have no clue where to start. I downloaded the source for QtOpenCl but it needs a valid OpenCl installation. I have Qt installed already.
How do I install OpenCl? I don't have a GPU at home unfortunately, and need to implement it on my CPU for now. I have to later give a presentation where I will be supplied a system with a GPU. How do I go about installing OpenCl?
| The ATI Stream SDK contains a CPU OpenCL implementation that you can use:
http://ati.amd.com/technology/streamcomputing/sdkdwnld.html
Installing it will give you a working OpenCL CPU Implementation.
|
2,966,764 | 2,967,501 | Porting a project to OpenGL3 | I'm working on a C++ cross-platform OpenGL application (Windows, Linux and MacOS) and I am wondering if some of you could share some advices on porting a large application to OpenGL 3. The reason I am looking into OpenGL 3 is because I think we could benefit a lot from using the new "Sync objects". Nvidia has supported such an extension since the Geforce 256 days (gl_nv_fences) but there seems to be no equivalent functionality on ATI hardware before OpenGL 3.0+...
Our code makes quite heavy use of glut/freeglut, glu functions, OpenGL 2 extensions and CUDA (on supported hardware). The problem I am now facing is that "gl3.h" and "gl.h" are mutually incompatible (as stated in gl3.h). Do you guys know if there is a GL3 glut equivalent ? Also, looking at the CUDA-toolkit header files, it seems that GL-CUDA interoperability is only available when using older versions of OpenGL... (cuda_gl_interop.h includes gl.h...). Am I missing something ?
Thanks a lot for your help.
| The last update to glut was version 3.7, roughly 10 years ago. Taking that into account, I doubt that it'll ever support OpenGL 3.x (or 4.x).
The people working on OpenGlut seem to be considering the possibility of OpenGL 3.x support, but haven't done anything with it yet.
FLTK has a (partial) glut simulation, but it's partial enough that a program that "makes heavy use of glut" may not work with it in the first place. Since FLTK is in active development, I'd guess it'll eventually support OpenGL 3.x (or 4.x), but I don't believe it's provided yet, and it may be open to question how soon it will be either.
Edit: As far as CUDA goes, the obvious (though certainly non-trivial) answer would be to use OpenCL instead. This is considerably more compatible both with hardware (e.g., with ATI/AMD boards) and with newer versions of OpenGL.
That leaves glu. Frankly, I don't think there is a clear or obvious answer to this. OpenGL is moving away from supporting things like glu, and instead dropping support for even more of the vaguely glu-like functionality that used to be part of the core OpenGL spec (e.g., all the matrix manipulation primitives). Personally, I think this is a mistake, but whether it's good or bad, it's how things are. Unfortunately, glu is a bit like glut -- the last update to the spec was in 1998, and corresponds to OpenGL 1.2. That doesn't make an update seem at all likely. Unfortunately, I don't know of any really direct replacements for it either. There are clearly other graphics libraries that provide (at least some) similar capabilities, but all of them I can think of would require substantial rewriting.
|
2,966,952 | 2,966,964 | How to set QWidget width? | How to set QWidget width? I know setGeometry(QRect& rect) function to do that, but in that case I should use geometry() function to get former parameters of my QWidget, then I should increment the width and use setGeometry(..). Is there any direct way to that, say:
QWidget aa;
aa.setWidth(165); //something like this?
| resize() might be better to use.
Example usage:
widget->resize(165, widget->height());
|
2,966,992 | 2,978,894 | Where is iTunes SDK/API documentation? | I downloaded a zipped archive from Apple that consists of a C++ header file and source. Included in this was a help file. For some reason this help file opens but I cannot read the content. Is there any other documentation outside of a help file for this? For c++ or c#?
| Solved.. The problem was a Windows Security feature was blocking the compiled help file from opening. I found the solution here:
http://weblog.helpware.net/?p=36
|
2,966,993 | 2,967,255 | Why does my Application not run using the x64 Version of Windows Server 2008? | I have a Win32 C++ Application using a handful of third-Party DLLs that is installed at some hundred costumer machines. I recently tested the x86 Version of the installation successfully on Windows XP, Windows Vista x64, Windows 7 x86 as well as Windows Server 2008 x86. No Problems. The Installer (nullsoft) installs the redistributable files for VC 2005 and VC 2008 as both are required by different DLLs we use.
But with Windows Server 2008 x64 both, the x86 and the x64 Versions refuse to start.
When i start the x86 Version of the program a Dialog appears:
<myApp> has stopped Working.
The EventLog contains a message:
Faulting application myapp.exe, version 1.0.0.0, time stamp 0x4bcb37ca,
faulting module MSVCR80.dll, version 8.0.50727.4053, time stamp 0x4a594c79,
exception code 0xc000000d, fault offset 0x0001ce0b, process id 0x29c,
application start time 0x01cb0329976cfc68.
\Windows\winsxs contains a directory
x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4053_none_d08d7da0442a985d
Using sxstrace (first trace, then parse) a log file of 3 Bytes length is created containing non readable characters. Behavior of the x64 Version is similar. Also all demo programms from the 3rd Party Dlls are working properly. Any hint ?
| It doesn't look like a side-by-side error. The exception code is STATUS_INVALID_PARAMETER, "An invalid parameter was passed to a service or function." That doesn't help. You'll need a debugger, probably with the Windows debugging symbols. Make it stop on the first-chance exception.
|
2,966,997 | 2,967,011 | C equivalent of C++ delete[] (char *) | What is the C equivalent of C++
delete[] (char *) foo->bar;
Edit: I'm converting some C++ code to ANSI C. And it had:
typedef struct keyvalue
{
char *key;
void *value;
struct keyvalue *next;
} keyvalue_rec;
// ...
for (
ptr = this->_properties->next, last = this->_properties;
ptr!=NULL;
last = ptr, ptr = ptr->next)
{
delete[] last->key;
delete[] (char *) last->value;
delete last;
}
Would this do it for C?
free(last->key);
free(last->value);
free(last)
| In C, you don't have new; you just have malloc(); to free memory obtained by a call to malloc(), free() is called.
That said, why would you cast a pointer to (char*) before passing it to delete? That's almost certainly wrong: the pointer passed to delete must be of the same type as created with new (or, if it has class type, then of a base class with a virtual destructor).
|
2,967,015 | 2,967,070 | Set a C++ bitset from a binary input steam | I have an input stream from a binary file. I want to create a bitset for the first 5 bits of the stream. Here is the code I have so far:
ifstream is;
is.open ("bin_file.out", ios::binary );
bitset<5> first_five_bits;
is >> first_five_bits; // always is set to default 00000
| char c;
if( ! cin.get(c) ) throw ROFL(); // return error, flip bit, call mom
bitset<5> first_five_bits(c >> (CHAR_BIT-5)); // CHAR_BIT in <climits>
|
2,967,062 | 2,967,089 | c++ try catch practices | Is this considered good programming practice in C++:
try {
// some code
}
catch(someException) {
// do something
}
catch (...)
{
// left empty <-- Good Practice???
}
| No! That is a terrible practice!
Just about the only time you should catch (...) and not rethrow the exception would be in main() to catch any otherwise unhandled exceptions and to display or log an error before exiting.
If you catch (...), you have absolutely no idea what exception was thrown, and thus you can't know whether it is safe to continue running.
|
2,967,128 | 2,979,380 | Seeking suggestions on redesigning the interface | As a part of maintaining large piece of legacy code, we need to change part of the design mainly to make it more testable (unit testing). One of the issues we need to resolve is the existing interface between components. The interface between two components is a class that contains static methods only.
Simplified example:
class ABInterface {
static methodA();
static methodB();
...
static methodZ();
};
The interface is used by component A so that different methods can use ABInterface::methodA() in order to prepare some input data and then invoke appropriate functions within component B.
Now we are trying to redesign this interface for various reasons:
Extending our unit test coverage - we need to resolve this dependency between the components and stubs/mocks are to be introduced
The interface between these components diverged from the original design (ie. a lots of newer functions, used for the inter-component i/f are created outside this interface class).
The code is old, changed a lot over the time and needs to be refactored.
The change should not be disruptive for the rest of the system. We try to limit leaving many test-required artifacts in the production code. Performance is very important and should be no (or very minimal) degradation after the redesign. Code is OO in C++.
I am looking for some ideas what approach to take. Any suggestions on how to do this efficiently?
| The simplest answer is to wrap the old library that has the static interface in a facade, then refactor the code to call the new facade instead of the old library. This new wedge should permit substitution of the library for unit testing purposes. Test it out on a single method first, just to see how to implement it.
What really bothers me is when a question is tainted with "performance concerns". We've all written performance critical code, and nobody ever deliberately suggests writing poorly performant code. I find these "concerns" usually come from the naysayers who decry every change, and really don't have a clue as to why a certain change would or wouldn't perform well. Remember, the only valid proof of performance comes from testing. Run your performance test and establish a baseline. Make your changes. Run your performance tests again in the new code. Demonstrate the actual impact. Only then can you make a decision as to the actual impact of a change. You should never allow quibbles over cycles to dominate your designs until demonstrated otherwise.
It sounds like someone important on your project is an old C programmer* who long ago heard some loudmouth say something like "the only way to make C++ run fast is to use static methods." The problem is that he still believes it. 20 years ago the loudmouth may have been right, but compilers and optimizers have vastly improved over those 2 decades. So give your change a try.
The chances are good that if you're using a modern compiler the optimizer is going to remove the extra dereferences in the object code anyway, meaning you'll have added no run-time impact at all.
And if performance is all-critical yet you don't have performance tests, or if you're not using a modern compiler, or if you don't have all the release-build optimizations tweaked (using Profile Guided Optimization, for example) then you have much bigger engineering problems that you need to take care of long before worrying about the performance of an extra layer of abstraction.
Note: I am also an old C programmer who also used to say stupid things like that 20 years ago. The difference is that I have learned that some optimizations are far more critical than others, and that the new compilers are amazingly good at figuring most stuff out on their own. My attempts to "optimize" things prematurely usually ended in expensive-to-maintain code that usually doesn't outperform the stock compiler settings anyway.
|
2,967,818 | 2,967,846 | Can C++ memory leaks negatively affect CPU usage? | I have a C++ program that has a pretty terrible memory leak, about 4MB / second. I know where it's coming from and can fix it, but that's not my main problem. My program is taking up a very large amount of CPU usage and it isn't running as fast as I want it to. I have two different threads in the program. One by itself takes ~50% CPU, which is fine, and the other by itself takes ~15% CPU, which is fine. Together however CPU usage is 100% and the program cannot run as fast as it needs to.
Can a memory leak by itself cause a problem like this? I know the program will eventually crash due to the leaked memory, but does a memory leak immediately lead to a slower program? By immediately I mean the program is too slow at the very start, not just when the memory footprint is huge.
Thanks!
| Regardless of whether or not your memory leak is causing the problem it needs to be fixed. Once you fix the memory leak see if you're still having the problem. You should be able to answer your own question at that point.
|
2,967,854 | 2,967,926 | Working on a cross platform library | What are the best practices on writing a cross platform library in C++?
My development environment is Eclipse CDT on Linux, but my library should have the possibility to compile natively on Windows either (from Visual C++ for example).
Thanks.
| To some extent, this is going to depend on exactly what your library is meant to accomplish.
If you were developing a GUI application, for instance, you would want to focus on using a well-tested cross-platform framework such as wxWidgets.
If your library depends primarily on File IO, you would want to make sure you use an existing well-tested cross-platform filesystem abstraction library such as Boost Filesystem.
If your library is none of the above (i.e. there are no existing well-tested cross-platform frameworks for you to use), your best bet is to make sure you adhere to standard C++ as much as possible (this means don't #include <linux.h> or <windows.h>, for instance). When that isn't possible (i.e. your library reads raw sound data from a microphone), you'll want to make sure the implementation details for a given platform are sufficiently abstracted away so that you minimize the work involved in porting your library to another platform.
|
2,968,067 | 2,968,203 | VS2008 Link Error Using SafeInt3.hpp in 64bit mode | I have the below code that links and runs fine in 32bit mode -
#include "safeint3.hpp"
typedef SafeInt<SIZE_T> SAFE_SIZE_T;
SAFE_SIZE_T sizeOfCache;
SAFE_SIZE_T _allocateAmt;
Where safeint3.hpp is current version that can be found on Codeplex SafeInt. For those who are unaware of it, safeint is a template class that makes working with different integer types and sizes "safe". To quote channel 9 video on software - "it writes the code that you should".
Which is my case. I have a class that is managing a large in-memory cache of objects (>6gb) and I am very concerned about making sure that I don't have overflow/underflow issues on my pointers/sizes/other integer variables. In this use, it solves many problems.
My problem is coming when moving from 32bit dev mode to 64bit production mode. When I build the app in this mode, I'm getting the following linker warnings -
1>cachecontrol.obj : warning LNK4006: "bool __cdecl IntrinsicMultiplyUint64(unsigned __int64 const &,unsigned __int64 const &,unsigned __int64 *)" (?IntrinsicMultiplyUint64@@YA_NAEB_K0PEA_K@Z) already defined in ImageInRamCache.obj; second definition ignored
1>cachecontrol.obj : warning LNK4006: "bool __cdecl IntrinsicMultiplyInt64(__int64 const &,__int64 const &,__int64 *)" (?IntrinsicMultiplyInt64@@YA_NAEB_J0PEA_J@Z) already defined in ImageInRamCache.obj; second definition ignored
While I understand I can ignore the error, I would like either (a) prevent the warning from occurring or (b) make it disappear so that my QA department doesn't flag it as a problem. And after spending some time researching it, I cannot find a way to do either.
| The problem is that inside safeint3.hpp, the code looks like this:
bool IntrinsicMultiplyUint64( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet )
{
....
}
This means every translation unit that includes safeint3.hpp will get a definition of IntrinsicMultiplyUint64. If you are willing to modify that file, you can make those functions inline:
inline bool IntrinsicMultiplyUint64( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet )
{
....
}
|
2,968,158 | 2,968,413 | How to check value of defined symbols (Eclipse->Paths & Symbols) in a makefile? | We have a project that used to be an Eclipse-managed CDT project. However, I am trying to change it to a standard makefile project.
One of them has a couple of symbols defined in
Project Properties->C/C++ General->Paths & Symbols->Symbols.
The makefiles generated by Eclipse used to automatically get the value when it was managed. The symbols need to be sent to the compiler. How do I get the value in my own makefile? Is there a way?
Thanks, and sorry, I know the questions sounds convoluted.
Edit:
By symbols I mean the -D symbols for the compiler. What we have is a COMPILE_FOR_A & COMPILE_FOR_B and the values are either 1 or 0. If COMPILE_FOR_A=1, it will use particular values, and if COMPILE_FOR_B=1 it will use some other values.
| Use environment variables and conditionals to tell your options to make. Something like:
DEFINES = -DFOO
ifeq ($(COMPILE_FOR_A),1)
DEFINES += -DBAR
else
DEFINES += -DBAZ
endif
Then invoke make with/without the variable in the environment:
~$ COMPILE_FOR_A=1 make
|
2,968,172 | 2,968,271 | How to share an array in Python with a C++ Program? | I two programs running, one in Python and one in C++, and I need to share a two-dimensional array (just of decimal numbers) between them. I am currently looking into serialization, but pickle is python-specific, unfortunately. What is the best way to do this?
Thanks
Edit: It is likely that the array will only have 50 elements or so, but the transfer of data will need to occur very frequently: 60x per second or more.
| I suggest Google's protobuf
|
2,968,336 | 3,022,562 | Qt - Password field, warn about Caps-Lock | Is there any Qt-built-in method to warn user (with pop-up window) that CapsLock is switched on while password field is active?
I am currently using QLineEdit (is it good?) with setEchoMode(QLineEdit::Password).
| I have soved this problem already. I have used QToolTip QT - How to apply a QToolTip on a QLineEdit as a way to inform
user about caps lock stat, and used, of course, a function that gets current state ( GetKeyState(VK_CAPITAL)). Disadvantage: this works on Windows only.
|
2,968,365 | 3,007,880 | Qt - Disabling QDialog's "?" button | I create an instance of QDialog and on the left of 'x' (close) button i have also '?' button. How I can disable that '?' ?
| Change the window flags, for example in the constructor:
this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
|
2,968,380 | 2,968,654 | Simplest way to provide template specialization for derived classes | I have the following scenario:
class my_base { ... }
class my_derived : public my_base { ... };
template<typename X>
struct my_traits;
I want to specialize my_traits for all classes derived from my_base including, e.g.:
template<typename Y> // Y is derived form my_base.
struct my_traits { ... };
I have no problems with adding tags, members to my_base to make it simpler. I've seen some tricks but I still feel lost.
How can this be done in a simple and short way?
| Well, you don't need to write your own isbaseof. You can use boost's or c++0x's.
#include <boost/utility/enable_if.hpp>
struct base {};
struct derived : base {};
template < typename T, typename Enable = void >
struct traits;
template < typename T >
struct traits< T, typename boost::enable_if<std::is_base_of<base, T>>::type >
{
enum { value = 5 };
};
#include <iostream>
int main()
{
std::cout << traits<derived>::value << std::endl;
std::cin.get();
}
There are scaling issues but I don't believe they're any better or worse than the alternative in the other question.
|
2,968,814 | 2,968,838 | extend php with java/c++? | i only know php and i wonder if you can extend a php web application with c++ or java when needed? i dont want to convert my code with quercus, cause that is very error prone. is there another way to extend it?
cause from what i have read python can extend it with c++ without converting the python code and use java with jython?
| Most of PHP is written in modular C code. You can create your own PHP extensions in C. See http://php.net/internals, the PHP wiki and the book "Extending and Embedding PHP" by Sara Golemon.
|
2,968,915 | 2,968,954 | C++: How to use types that have not been defined? | C++ requires all types to be defined before they can be used, which makes it important to include header files in the right order. Fine. But what about my situation:
Bunny.h:
class Bunny
{
...
private:
Reference<Bunny> parent;
}
The compiler complains, because technically Bunny has not been completely defined at the point where I use it in its own class definition. because I did something stupid (unrelated).
Apart from re-writing my template class Reference so it takes a pointer type (in which case I can use the forward declaration of Bunny), I don't know how to solve this.
Any suggestions?
EDIT: My Reference class (XObject is a base class for data mode objects):
template <class T = XObject> class Reference
{
public:
Reference() : m_ptr (NULL) {}
Reference(T* p)
{
m_ptr = p;
if (p != NULL) ((XObject*)p)->ref();
}
~Reference()
{
if (m_ptr)
{
((XObject*)m_ptr)->deref();
}
}
// ... assignment, comparison, etc.
private:
T* m_ptr;
};
EDIT: This works fine, the problem was something else. Thanks so much for your help!
| The answer to your question depends on what Reference<> looks like. If it has an instance variable of type Bunny in it then of course it won't work (how would it, you have a recursive definition that never ends). If it has only references and pointers in it then it should work fine. The Bunny type in the template instantiation would not interfere with this.
Edit (post reference<> code edit):
I can't seem to recreate your problem. I've reimplemented code like what you're doing but it compiles fine for me:
struct base {
void fun() {}
};
template < typename T >
struct temp
{
T * t;
void f() { ((base*)t)->fun(); }
};
struct test
{
temp<test> t;
};
int main()
{
test t;
t.t.f();
}
It's obviously invalid code in that you're going to get undefined results but it does compile. Mainly the issue here is the reinterpret cast from type test* to type base*. If test really did inherit from base then the cast wouldn't even be necessary. Code like this will not function as expected but it should compile just fine. One recommendation I'd have is to lose all the c-style casts. That won't solve the problem you're having though, whatever it is...it's got to be somewhere in the code you're not pasting.
|
2,969,033 | 2,969,079 | Recursive breadth-first travel function in Java or C++? | Here is a java code for breadth-first travel:
void breadthFirstNonRecursive(){
Queue<Node> queue = new java.util.LinkedList<Node>();
queue.offer(root);
while(!queue.isEmpty()){
Node node = queue.poll();
visit(node);
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
}
Is it possible to write a recursive function to do the same?
At first, I thought this would be easy, so I came out with this:
void breadthFirstRecursive(){
Queue<Node> q = new LinkedList<Node>();
breadthFirst(root, q);
}
void breadthFirst(Node node, Queue<Node> q){
if (node == null) return;
q.offer(node);
Node n = q.poll();
visit(n);
if (n.left != null)
breadthFirst(n.left, q);
if (n.right != null)
breadthFirst(n.right, q);
}
Then I found it doesn't work. It is actually does the same thing as this:
void preOrder(Node node) {
if (node == null) return;
visit(node);
preOrder(node.left);
preOrder(node.right);
}
Has any one thought about this before?
| I can't imagine why you'd want to, when you have a perfectly good iterative solution, but here you go ;)
void breadth_first(Node root):
Queue q;
q.push(root);
breadth_first_recursive(q)
void breadth_first_recursive(Queue q):
if q.empty() return;
Node n = q.pop()
print "Node: ", n
if (n.left) q.push(n.left)
if (n.right) q.push(n.right)
breadth_first_recursive(q)
I should add that if you really want to traverse the nodes of the tree recursively, then you could do a DFS with a level parameter, and output nodes only at level, then recurse up. But that's just crazy talk, because you'd revisit nodes wayyyyy too many times... Just accept that BFS is an iterative algorithm. :)
|
2,969,034 | 2,998,222 | Best way to access nested data structures? | I would like to know what the best way (performance wise) to access a large data structure is.
There are about hundred ways to do it but what is the most accessible for the compiler to optimize?
One can access a value by
foo[someindex].bar[indexlist[i].subelement[j]].baz[0]
or create some pointer aliases like
sometype_t* tmpfoo = &foo[someindex];
tmpfoo->bar[indexlist[i].subelement[j]].baz[0]
or create reference aliases like
sometype_t &tmpfoo = foo[someindex];
tmpfoo.bar[indexlist[i].subelement[j]].baz[0]
and so forth...
| As a personal preference, I generally find it easier to read and understadn if there are fewer nested levels to traverse. Thus, I tend to use the ...
SomeType *pSomeType = &asManyLevelsAsItMakesSense[someIndex];
pSomeType->subSomeNestedLevels = ...;
I find this particularly useful when dealing with deep nested structures in loops. Identify the invariant nested parts and hoist it out of the loop.
SomeType *pSomeType = &...;
for (i = 0; i < N; i++)
pSomeType->field[i] = ...;
As always, it is worth your while to know your compiler and what it actually generates. Sometimes you may be stuck with a compiler for your project that does no optimization at all and so little things like this can make a difference (but don't assume that it will).
|
2,969,222 | 2,969,244 | Make GNU make use a different compiler | How can I make GNU Make use a different compiler without manually editing the makefile?
| You should be able to do something like this:
make CC=my_compiler
This is assuming whoever wrote the Makefile used the variable CC.
|
2,969,271 | 2,969,380 | Strange error: cannot convert from 'int' to 'ios_base::openmode' | I am using g++ to compile some code. I wrote the following snippet:
bool WriteAccess = true;
string Name = "my_file.txt";
ofstream File;
ios_base::open_mode Mode = std::ios_base::in | std::ios_base::binary;
if(WriteAccess)
Mode |= std::ios_base::out | std::ios_base::trunc;
File.open(Name.data(), Mode);
And I receive these errors... any idea why?
Error 1: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’
Error 2: initializing argument 2 of ‘std::basic_filebuf<_CharT, _Traits>* std::basic_filebuf<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits]’
As far as I could tell from a Google search, g++ is actually breaking the C++ standard here. Which I find quite astonishing, since they generally conform very strictly to the standard. Is this the case? Or am I doing something wrong.
My reference for the standard: http://www.cplusplus.com/reference/iostream/ofstream/open/
| openmode is the correct type, not open_mode.
|
2,969,312 | 2,970,663 | Create an instance from a static method | let's say I want my users to use only one class, say SpecialData.
Now, this data class would have many methods, and depending on the type of data, the methods do different things, internally, but return externally similar results. Therefore my wanting to have one "public" class and other "private", child classes that would change the behavior of methods, etc...
It would be amazingly more simple for some types of data that need to be built to do something like this:
SpecialData& sm = SpecialData::new_supermatrix();
and new_supermatrix() would return a SuperMatrix instance, which inherits from most behaviors of SpecialData.
my header:
static SpecialData& new_supermatrix();
my cpp:
SpecialData& SpecialData::new_supermatrix()(){
return SuperMatrix(MATRIX_DEFAULT_MAGNITUDE,1000,1239,FLOAT32,etc...);
}
The problem is, I get this error, which is probably logical due to the circumstances:
invalid initialization of non-const reference of type ‘SpecialData&’ from a temporary of type ‘SpecialData’
So, any ideas?
| Well, you've got three choices:
a) You want to have only one instance of SuperMatrix anyway. Then go for the static function member route as has already been suggested.
b) You want to create multiple instances. Then you have to return a pointer instead of references and create the objects with with new (i.e. return new SuperMatrix(...).
c) As an alternative to option b, you can also return merely an object, i.e.
SpecialData SpecialData::new_supermatrix()(){
return SuperMatrix(MATRIX_DEFAULT_MAGNITUDE,1000,1239,FLOAT32,etc...);
}
However, this requires a (deep-)copy operator (the default one won't suffice more often than not), and it means that the object is created on the stack, then copied and that copy is being returned. The good thing is, this won't leak memory if you don't actually receive the result into a variable. The bad thing is, if the object is very large, this can be very memory- and time-consuming.
Whatever you are going to do with it, these solutions are mutually exclusive, both technically and logically. ;)
|
2,969,383 | 2,969,432 | Virtual destructors for interfaces | Do interfaces need a virtual destructor, or is the auto-generated one fine? For example, which of the following two code snippets is best, and why? Please note that these are the WHOLE class. There are no other methods, variables, etc. In Java-speak, this is an "interface".
class Base
{
public:
virtual void foo() = 0;
virtual ~Base() {}
};
OR...
class Base
{
public:
virtual void foo() = 0;
~Base() {} // This line can be omitted, but included for clarity.
};
EDIT DUE TO "NOT WHAT I'M LOOKING FOR" ANSWERS:
Exactly what are the consequences of each route. Please don't give vague answers like "it won't be destructed properly". Please tell me exactly what will happen. I'm a bit of an assembly nerd.
Edit 2:
I am well aware that the "virtual" tag means that the destructor won't get called if deleted through a pointer to derived, but (I think) this question ultimately boils down to "is it safe to omit that destructor, for is it truly trivial?"
EDIT 3:
My second edit is just plain wrong and disinformation. Please read the comments by actual smart people for more info.
| Consider the following case:
Base *Var = new Derived();
delete Var;
You need the virtual destructor, otherwise when you delete Var, the derived class' destructor will never be called.
|
2,969,387 | 2,969,417 | Why operator= returns reference not const reference | The original question is related to overloading operator= and I like to share my findings as it was nontrivial for me to find them.
I cannot imagine reasonable example to use (a=b) as lvalue.
With the help of IRC and google I've found the next article:
http://msdn.microsoft.com/en-us/magazine/cc301415.aspx
it provides two examples.
(a=b)=c
f(T& );
f(a=b)
but both a bit not good, and I believe that it is bad practice.
The second one give me the same feeling.
Could you provide more good examples why it should be non constant?
| One good reason is that one of the requirements in the standard for a class X to be useable in the standard containers is that the expression a = b must have type X& (where a is an lvalue of type X and b is an rvalue of type X).
|
2,969,596 | 2,969,621 | Passing variables to functions | A quick question:
When i pass a variable to a function, does the program make a copy of that variable to use in the function?
If it does and I knew that the function would only read the variable and never write to it, is it possible to pass a variable to the function without creating a copy of that variable or should I just leave that up to the compiler optimizations to do that automatically for me?
| Yes, parameters passed by value are copied. However, you can also pass variables by reference. A reference is an alias, so this makes the parameter an alias to a variable, rather than a copy. For example:
void foo(int x) {}
void bar(int& x) {}
int i;
foo(i); // copies i, foo works with a copy
bar(i); // aliases i, bar works directly on i
If you mark it as const, you have a read-only alias:
void baz(const int&);
baz(i); // aliases i, baz reads-only i
In general, always pass by const-reference. When you need to modify the alias, remove the const. And lastly, when you need a copy, just pass by value.*
* And as a good rule of thumb, fundamental types (int, char*, etc.) and types with sizeof(T) < sizeof(void*) should be passed by value instead of const-reference, because their size is small enough that copying will be faster than aliasing.
|
2,969,616 | 2,969,704 | Writing a windows web service and not sure what language to use? | So I am required to write a fairly basic Windows service and have never done so before. Of C#, C++ (the Visual Studio suite), what is the best language to develop in? I am a student, and am most familiar with OO languages such as Java.
Additionally, if anyone can recommend any books, articles, or google searches that would be relevant to the project I would greatly appreciate it.
Thanks!
badPanda
| As others have stated, C# is a lot closer to java than C++.
With respect to Web services, which I take to be your focus based on the title and tags of your question, there are two options in .NET, ASMX or WCF.
ASMX web services are the older technology, basically ASP.NET intercepts and processes requests using the ASP.NET stack. These services can be added as a reference in other .NET apps, which generates proxy code to easily access the service. There are also IIS web server extensions that provide security and other functionality. ASMX services have been supplanted by WCF, but are still supported.
WCF is the newer service technology from Microsoft, you can easily configure it to listen on http and use SOAP for transport, and it has all the security and encryption functionality built in. This is a better solution if you potentially want to have your service called by non-.NET clients, or if you may want to reuse your service logic in other non-web applications. There's a little more learning curve, but a lot more power and flexibility.
You should be able to google for tutorials/walkthroughs for both asmx and WCF -- if it is an older tutorial and doesn't say "WCF", it's probably asmx. For WCF services, I have really liked the Service Factory from Microsoft patterns & practices, it gives a lot of good code generation and a designer surface to plan out your services and generates and configures projects to host them.
|
2,969,691 | 2,969,722 | How do I get the length of a VBO to render all vertices when using glDrawArrays()? | I create a VBO in a function and I only want to return the VBO id.
I use glDrawArrays in another function and I want it to draw all the vertices in the VBO without needing to also pass the number of vertices. The VBO also contains texture coordinate data.
Thank you.
| You need to return it, sorry. Data about the VBO might live somewhere far away from your CPU and be slow to access, so you need to keep locally whatever data you need.
|
2,969,709 | 2,969,751 | const object and const constructor | Is there any way to know if an object is a const object or regular object, for instance consider the following class
class String
{
String(const char* str);
};
if user create a const object from String then there is no reason to copy the passed native string and that because he will not make any manipulation on it, the only thing he will do is get string size, string search and other functions that will not change the string.
| There is a very good reason for copying - you can't know that the lifetime of the const char * is the same as that of the String object. And no, there is no way of knowing that you are constructing a const object.
|
2,969,843 | 2,977,559 | Validate Unicode String and Escape if Unicode is Invalid (C/C++) | I have a program that reads arbitrary data from a file system and outputs results in Unicode. The problem I am having is that sometimes filenames are valid Unicode and sometimes they aren't. So I want a function that can validate a string (in C or C++) and tell me if it is a valid UTF-8 encoding. If it is not, I want to have the invalid characters escaped so that it will be a valid UTF-8 encoding. This is different than escaping for XML --- I need to do that also. But first I need to be sure that the Unicode is right.
I've seen some code from which I could hack this, but I would rather use some working code if it exists.
| The following code is based on an IRI library I have been working on for awhile. Section 3.2 ("Converting URIs to IRIs") of RFC 3987 deals with converting invalid UTF-8 octets to valid UTF-8.
#define IS_IN_RANGE(c, f, l) (((c) >= (f)) && ((c) <= (l)))
int UTF8BufferToUTF32Buffer(char *Data, int DataLen, unsigned long *Buffer, int BufLen, int *Eaten)
{
if( Eaten )
{
*Eaten = 0;
}
int Result = 0;
unsigned char b, b2;
unsigned char *ptr = (unsigned char*) Data;
unsigned long uc;
int i = 0;
int seqlen;
while( i < DataLen )
{
if( (Buffer) && (!BufLen) )
break;
b = ptr[i];
if( (b & 0x80) == 0 )
{
uc = (unsigned long)(b & 0x7F);
seqlen = 1;
}
else if( (b & 0xE0) == 0xC0 )
{
uc = (unsigned long)(b & 0x1F);
seqlen = 2;
}
else if( (b & 0xF0) == 0xE0 )
{
uc = (unsigned long)(b & 0x0F);
seqlen = 3;
}
else if( (b & 0xF8) == 0xF0 )
{
uc = (unsigned long)(b & 0x07);
seqlen = 4;
}
else
{
uc = 0;
return -1;
}
if( (i+seqlen) > DataLen )
{
return -1;
}
for(int j = 1; j < seqlen; ++j)
{
b = ptr[i+j];
if( (b & 0xC0) != 0x80 )
{
return -1;
}
}
switch( seqlen )
{
case 2:
{
b = ptr[i];
if( !IS_IN_RANGE(b, 0xC2, 0xDF) )
{
return -1;
}
break;
}
case 3:
{
b = ptr[i];
b2 = ptr[i+1];
if( ((b == 0xE0) && !IS_IN_RANGE(b2, 0xA0, 0xBF)) ||
((b == 0xED) && !IS_IN_RANGE(b2, 0x80, 0x9F)) ||
(!IS_IN_RANGE(b, 0xE1, 0xEC) && !IS_IN_RANGE(b, 0xEE, 0xEF)) )
{
return -1;
}
break;
}
case 4:
{
b = ptr[i];
b2 = ptr[i+1];
if( ((b == 0xF0) && !IS_IN_RANGE(b2, 0x90, 0xBF)) ||
((b == 0xF4) && !IS_IN_RANGE(b2, 0x80, 0x8F)) ||
!IS_IN_RANGE(b, 0xF1, 0xF3) )
{
return -1;
}
break;
}
}
for(int j = 1; j < seqlen; ++j)
{
uc = ((uc << 6) | (unsigned long)(ptr[i+j] & 0x3F));
}
if( Buffer )
{
*Buffer++ = uc;
--BufLen;
}
++Result;
i += seqlen;
}
if( Eaten )
{
*Eaten = i;
}
return Result;
}
{
std::string filename = "...";
unsigned long ch;
int eaten;
std::string::size_type i = 0;
while( i < filename.length() )
{
if( UTF8BufferToUTF32Buffer(&filename[i], filename.length()-i, &ch, 1, &eaten) == 1 )
{
i += eaten;
}
else
{
// replace the character at filename[i] with your chosen
// escaping, and then increment i by the number of
// characters used...
}
}
}
In your case, all you have to do is decide what kind of escaping you want to use. URIs/IRIs uses percent-encoding ("%NN", where "NN" is the 2-digit hex value of an octet).
|
2,970,007 | 2,970,022 | Friends, templates, overloading << linker errors | I had some good insight to an earlier post regarding this, but I have no idea what these compile errors mean that I could use some assistant on. Templates, friends, and overloading are all new, so 3 in 1 is giving me some problems...
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Point<double>::Point<double>(double,double)" (??0?$Point@N@@QAE@NN@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Point<int>::Point<int>(int,int)" (??0?$Point@H@@QAE@HH@Z) referenced in function _main
1>C3_HW8.exe : fatal error LNK1120: 3 unresolved externals
Point.h
#ifndef POINT_H
#define POINT_H
#include <iostream>
template <class T>
class Point
{
public:
Point();
Point(T xCoordinate, T yCoordinate);
template <class G>
friend std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint);
private:
T xCoordinate;
T yCoordinate;
};
#endif
Point.cpp
#include "Point.h"
template <class T>
Point<T>::Point() : xCoordinate(0), yCoordinate(0)
{}
template <class T>
Point<T>::Point(T xCoordinate, T yCoordinate) : xCoordinate(xCoordinate), yCoordinate(yCoordinate)
{}
template <class G>
std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint)
{
std::cout << "(" << aPoint.xCoordinate << ", " << aPoint.yCoordinate << ")";
return out;
}
main.cpp
#include <iostream>
#include "Point.h"
int main()
{
Point<int> i(5, 4);
Point<double> *j = new Point<double> (5.2, 3.3);
std::cout << i << j;
}
| With most compilers, you need to put templates in headers, so they're visible to the compiler where they're used. If you really want to avoid that, you can use explicit instantiation of the template(s) over the necessary types, but putting them in a header is much more common.
|
2,970,170 | 2,975,877 | Network time out when trying to connect ipod touch to my server | I have an ipod touch program that should receive messages from a server program on my mac. To make sure that the touch can receive messages from a computer other than a mac, I programmed the server in C++. If I run both the server and the ipod app on the same computer (the app running on the simulator), the connection is fine and everything is dandy. However, when I try to connect to the server from my device, the connection times out. Can anyone spot the problem? I'm not too good with networking, and the iPhone OS in general.
server.cpp:
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
cout << "ERROR opening socket";
return;
}
memset((char *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
cout << "ERROR on binding";
return;
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, (socklen_t*)&clilen);
if (newsockfd < 0) {
cout << "ERROR on accept.";
return;
}
The server gets stuck at the accept(), waiting for the app...
client.m:
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)hostName, portNum, &readStream, &writeStream);
if (readStream && writeStream) {
NSLog(@"Starting streams");
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
inputStream = (NSInputStream *)readStream;
[inputStream retain];
[inputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
outputStream = (NSOutputStream *)writeStream;
[outputStream retain];
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
}
if (readStream)
CFRelease(readStream);
if (writeStream)
CFRelease(writeStream);
As far as I can tell, neither server nor client reports any errors (I'm checking through errno and NSError) other than timing out.
If anyone can help me with this, much thanks!
| The iPod was connected to a different network than my Mac, and that's why it got blocked. When I connected to the same network, it works perfectly fine.
|
2,970,209 | 2,970,230 | Do dll's ever turn into machine code? | Just curious, I was told that with dll files, you can make modifications to the dll without recompiling the whole application that uses it. On the other hand .lib files need to be compiled so the code can linked to the application as one.
So I know that the .lib files are turned into machine code. but what about the dll's ?? Are they turned into machine code upon the execution of the application ??
This could probably lead to easy hacking if not used right.
| The dlls are still machine code. They're just dynamically linked in at run time (hence then name) so (if you don't change the function signatures) you don't have to recompile your main program to use a dll after it's been changed. A static library is physically part of your executable, that's why changes there require a recompile (or really, a relink).
|
2,970,253 | 2,970,261 | Confused with implicit and explicit template declarations | I'm getting confused with implicit and explicit declarations. I don't know why you need to explicitly say or at certain times. For example,
In my main.cpp
#include <iostream>
#include "Point.h"
int main()
{
Point<int> i(5, 4);
Point<double> *j = new Point<double> (5.2, 3.3);
std::cout << i << *j;
Point<int> k;
std::cin >> k;
std::cout << k;
}
for Point<int> k. Why do I have to use the explicit declaration? I get compile errors otherwise. Or do I have it coded incorrectly in my Point.h file?
Point.h:
#ifndef POINT_H
#define POINT_H
#include <iostream>
template <class T>
class Point
{
public:
Point();
Point(T xCoordinate, T yCoordinate);
template <class G>
friend std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint);
template <class G>
friend std::istream &operator>>(std::istream &in, const Point<G> &aPoint);
private:
T xCoordinate;
T yCoordinate;
};
template <class T>
Point<T>::Point() : xCoordinate(0), yCoordinate(0)
{}
template <class T>
Point<T>::Point(T xCoordinate, T yCoordinate) : xCoordinate(xCoordinate), yCoordinate(yCoordinate)
{}
template <class G>
std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint)
{
std::cout << "(" << aPoint.xCoordinate << ", " << aPoint.yCoordinate << ")";
return out;
}
template <class G>
std::istream &operator>>(std::istream &in, const Point<G> &aPoint)
{
int x, y;
std::cout << "Enter x coordinate: ";
in >> x;
std::cout << "Enter y coordinate: ";
in >> y;
Point<G>(x, y);
return in;
}
#endif
| For a class template, the template arguments must be specified explicitly.
For a function template, the template arguments can be inferred implicitly.
Point is a class, so explicit declaration is required.
|
2,970,436 | 2,970,528 | How to determine the name of the DLL (string) that loaded my DLL? | I'm writing a device driver that is loaded by a 3rd-party driver. I need a way to determine the name of the 3rd-party driver that is loading my device driver (for debug purposes).
For example, GetModuleFileName will provide me the name of the executable. I'd like instead to be able to get the DLL names.
The stack trace may be one of the following:
(a)
app0.exe
abc.dll <- detect "abc"
common.dll
my.dll
(b)
app1.exe
xyz.dll <- detect "xyz"
common.dll
my.dll
(c)
app2.exe
common.dll
my.dll
p.s. - I only need a method for C++ \ Windows
| I assume you've got a process handle, or id of the process your my.dll is loaded in.
See an MSDN example at http://msdn.microsoft.com/en-us/library/ms686701(v=VS.85).aspx which will take a snapshot of a process and give all information.
The interesting method is at BOOL ListProcessModules( DWORD dwPID ):
MODULEENTRY32 has a field called szModule which contains the name of the module. See http://msdn.microsoft.com/en-us/library/ms684225(VS.85).aspx
All module entries can be retrieved from a process using CreateToolhelp32Snapshot, which requires the process id (th32ProcessID of PROCESSENTRY32).
Then you'll iterate on all modules of the snapshot using Module32First and Module32Next. Also, do not forget to close the handle given by CreateToolhelp32Snapshot.
(Note: these methods are available from kernel32.dll)
This is called Module Walking, more on here: http://msdn.microsoft.com/en-us/library/ms684236(v=VS.85).aspx (described what is in this answer already)
|
2,970,455 | 2,970,483 | What would be the best way to implement a constant object? | First of all I should probably say that the term 'constant object' is probably not quite right and might already mean something completely different from what I am thinking of, but it is the best term I can think of to describe what I am talking about.
So basically I am designing an application and I have come across something that seems like there is probably an existing design pattern for but I don't know what it is or what to search for, so I am going to describe what it is I am trying to do and I am looking for suggestions as to the best way to implement it.
Lets say you have a class:
public class MyClass {
private String name;
private String description;
private int value;
public MyClass(String name, String description, int value) {
this.name = name;
this.description = description;
this.value = value;
}
// And I guess some getters and setters here.
}
Now lets say that you know in advance that there will only ever be say 3 instances of this class, and the data is also known in advance (or at least will be read from a file at runtime, and the exact filename is known in advance). Basically what I am getting at is that the data is not going to be changed during runtime (once it has been set).
At first I thought that I should declare some static constants somewhere, e.g.
public static final String INSTANCE_1_DATA_FILE = "path/to/instance1/file";
public static final String INSTANCE_2_DATA_FILE = "path/to/instance2/file";
public static final String INSTANCE_3_DATA_FILE = "path/to/instance3/file";
public static final MyClass INSTANCE_1 = new MyClass(getNameFromFile(INSTANCE_1_DATA_FILE), getDescriptionFromFile(INSTANCE_1_DATA_FILE), getValueFromFile(INSTANCE_1_DATA_FILE));
public static final MyClass INSTANCE_2 = new MyClass(getNameFromFile(INSTANCE_2_DATA_FILE), getDescriptionFromFile(INSTANCE_2_DATA_FILE), getValueFromFile(INSTANCE_2_DATA_FILE));
public static final MyClass INSTANCE_3 = new MyClass(getNameFromFile(INSTANCE_3_DATA_FILE), getDescriptionFromFile(INSTANCE_3_DATA_FILE), getValueFromFile(INSTANCE_3_DATA_FILE));
Obvisouly now, whenever I want to use one of the 3 instances I can just refer directly to the constants.
But I started thinking that there might be a cleaner way to handle this and the next thing I thought about was doing something like:
public MyClassInstance1 extends MyClass {
private static final String FILE_NAME = "path/to/instance1/file";
public String getName() {
if (name == null) {
name = getNameFromFile(FILE_NAME);
}
return name;
}
// etc.
}
Now whenever I want to use the instances of MyClass I can just use the one I want e.g.
private MyClass myInstance = new MyClassInstance2();
Or probably even better would be to make them singletons and just do:
private MyClass myInstance = MyClassInstance3.getInstance();
But I can't help but think that this is also not the right way to handle this situation. Am I overthinking the problem? Should I just have a switch statement somewhere e.g.
public class MyClass {
public enum Instance { ONE, TWO, THREE }
public static String getName(Instance instance) {
switch(instance) {
case ONE:
return getNameFromFile(INSTANCE_1_DATA_FILE);
break;
case TWO:
etc.
}
}
}
Can anyone tell me the best way to implement this? Note that I have written the sample code in Java because that is my strongest language, but I will probably be implementing the application in C++, so at the moment I am more looking for language independent design patterns (or just for someone to tell me to go with one of the simple solutions I have already mentioned).
| If you want the values to be constant, then you will not need setters, otherwise code can simply change the values in your constants, making them not very constant. In C++, you can just declare the instances const, although I'd still get rid of the setters, since someone could always cast away the const.
The pattern looks ok, although the fact that you are creating a new instance each time one is requested, is not usual for constants.
In java, you can create enums that are "smart" e.g.
public enum MyClass {
ONE(INSTANCE_1_DATA_FILE),
TWO(INSTANCE_2_DATA_FILE),
//etc...
private MyClass(String dataFile)
{
this(getNameFromDataFile(dataFile), other values...)
}
private MyClass(String name, String data, etc...)
{
this.name = name;
// etc..
}
public String getName()
{
return name;
}
}
In C++, you would create your MyClass, with a private constructor that takes the filename and whatever else it needs to initialize, and create static const members in MyClass for each instance, with the values assigned a new instance of MyClass created using the private constructor.
EDIT: But now I see the scenario I don't think this is a good idea having static values. If the types of ActivityLevel are fundamental to your application, then you can enumerate the different type of activity level as constants, e.g. a java or string enum, but they are just placeholders. The actual ActivityDescription instances should come from a data access layer or provider of some kind.
e.g.
enum ActivityLevel { LOW, MED, HIGH }
class ActivityDescription
{
String name;
String otherDetails;
String description; // etc..
// perhaps also
// ActivityLevel activityLevel;
// constructor and getters
// this is an immutable value object
}
interface ActivityDescriptionProvider
{
ActivityDescription getDescription(ActivityLevel activityLevel);
}
You can implement the provider using statics if you want, or an enum of ActivityDescription instnaces, or better still a Map of ActivityLevel to ActivityDescription that you load from a file, fetch from spring config etc. The main point is that using an interface to fetch the actual description for a given ActivityLevel decouples your application code from the mechanics of how those descriptions are produced in the system. It also makes it possible to mock the implementation of the interface when testing the UI. You can stress the UI with a mock implementation in ways that is not possible with a fixed static data set.
|
2,970,490 | 3,013,794 | Most Lite-Weight XML Parser with XPath and Wide-char Support | I want a lite-weight C++ XML parser/DOM that:
Can take UTF-8 as input, and parse into UTF-16. Maybe it does this directly (ideal!), or perhaps it provides a hook for the conversion (such as taking a custom stream object that does the conversion before parsing).
Offers some XPath support.
I've been looking at RapidXML, the Kranf xmlParser, and pugiXML. The first two of those might permit requirement #1 by way of a hook. The third, pugiXML, supports the #2 requirement. But none of those three fulfill both requirements.
What is the smallest (free) library that can handle both requirements?
| pugixml has an UNICODE branch. I guess UNICODE will be officially supported in the next version (0.6)
|
2,970,607 | 2,970,611 | isdigit() c++, probably simple question, but stuck | I'm having trouble with isdigit. I read the documentation, but when I cout << isdigit(9), I get a 0. Shouldn't I get a 1?
#include <iostream>
#include <cctype>
#include "Point.h"
int main()
{
std::cout << isdigit(9) << isdigit(1.2) << isdigit('c');
// create <int>i and <double>j Points
Point<int> i(5, 4);
Point<double> *j = new Point<double> (5.2, 3.3);
// display i and j
std::cout << "Point i (5, 4): " << i << '\n';
std::cout << "Point j (5.2, 3.3): " << *j << '\n';
// Note: need to use explicit declaration for classes
Point<int> k;
std::cout << "Enter Point data (e.g. number, enter, number, enter): " << '\n'
<< "If data is valid for point, will print out new point. If not, will not "
<< "print out anything.";
std::cin >> k;
std::cout << k;
delete j;
}
| isdigit() is for testing whether a character is a digit character.
If you called it as isdigit('9'), it would return nonzero.
In the ASCII character set (which you are likely using), 9 represents the horizontal tab, which is not a digit.
Since you are using the I/O streams for input, you don't need to use isdigit() to validate the input. The extraction (i.e., the std::cin >> k) will fail if the data read from the stream is not valid, so if you are expecting to read an int and the user enters "asdf" then the extraction will fail.
If the extraction fails, then the fail bit on the stream will be set. You can test for this and handle the error:
std::cin >> k;
if (std::cin)
{
// extraction succeeded; use the k
}
else
{
// extraction failed; do error handling
}
Note that the extraction itself also returns the stream, so you can shorten the first two lines to be simply:
if (std::cin >> k)
and the result will be the same.
|
2,971,040 | 2,971,049 | Global - Local difference in the init of an array in c | Why this dont work:
int size = 2;
int array[size];
int main() {
return 0;
}
It says the error: array bound is not an integer constant
And this work:
int size = 2;
int main() {
int array[size];
return 0;
}
Anyone knows the reason?
thanks
| In C++ or C89/90 neither works. These languages require that array size is an Integral Constant Expression (ICE). In your examples size is not an ICE. If your C++ or C89/90 compiler allows it, it is nothing else than a non-standard compiler extension.
In C99 the second works because this is how Variable Array Length (VLA) specification is defined. VLA can only be defined in local scope.
|
2,971,103 | 2,971,116 | Can't push vector of vector of GlDouble? | I have a vector which accepts vectors of GlDouble vectors. But when I try to push one it says:
Error 1 error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'const std::vector<_Ty> &' c:\Users\Josh\Documents\Visual Studio 2008\Projects\Vectorizer Project\Vectorizer Project\Vectorizer Project.cpp 324
Why isn't it letting me push this? It's saying it wants a contant but I never specified that....
Thanks
the struct:
struct SHAPECONTOUR{
std::vector<USERFPOINT> UserPoints;
std::vector<std::vector<GLdouble>> DrawingPoints;
};
std::vector<std::vector<GLdouble>> shape_verts;
SHAPECONTOUR c;
c.DrawingPoints.push_back(shape_verts);
| Edit: After new additions, the problem is not const - the problem is that you're trying to push the wrong type.
std::vector<std::vector<GLdouble> > v;
v.push_back(std::vector<GLdouble>()); // works; pushing contained type
v.push_back(std::vector<std::vector<GLdouble> >()); // <-- error: trying to push type of container.
Think about if you just had a vector of doubles; you push_back a double into the vector, you don't push_back another vector.
|
2,971,254 | 2,971,274 | c++, sleep, and loops | Ok, this is just out of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop?
for(int i = 0; i < 5; i++) {
cout << i << endl;
sleep(2);
}
| cout is buffered, meaning its contents aren't always written to the console right away. Try adding cout.flush() right before sleep(2);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.