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
|
|---|---|---|---|---|
994,253
| 994,262
|
Two classes that refer to each other
|
I'm new to C++, so this question may be basic:
I have two classes that need to refer to each other. Each is in its own header file, and #include's the other's header file. When I try to compile I get the error "ISO C++ forbids declaration of ‘Foo’ with no type" for one of the classes. If I switch things so the opposite header gets parsed first I get the same error with the other class.
Is it possible in C++ to have two classes that need references to each other?
For more detail: I have an "App" class and a "Window" class. App needs to refer to Window to make the window. Window has a button that calls back to App, so it needs a reference to App. If I can't have two classes refer to each other, is there a better way to implement this?
|
You can use forward declarations in the header files to get around the circular dependencies as long as you don't have implementation dependencies in the headers. In Window.h, add this line:
class App;
In App.h, add this line:
class Window;
Add these lines before the class definitions.
Then in the source files, you include the headers for the actual class definitions.
If your class definitions reference members of the other class (for example, in inlines), then they need to be moved to the source file (no longer inline).
|
994,288
| 994,357
|
size_t vs int in C++ and/or C
|
Why is it that in C++ containers, it returns a size_type rather than an int? If we're creating our own structures, should we also be encouraged to use size_type?
|
In general, size_t should be used whenever you are measuring the size of something. It is really strange that size_t is only required to represent between 0 and SIZE_MAX bytes and SIZE_MAX is only required to be 65,535...
The other interesting constraints from the C++ and C Standards are:
the return type of sizeof() is size_t and it is an unsigned integer
operator new() takes the number of bytes to allocate as a size_t parameter
size_t is defined in <cstddef>
SIZE_MAX is defined in <limits.h> in C99 but not mentioned in C++98?!
size_t is not included in the list of fundamental integer types so I have always assumed that size_t is a type alias for one of the fundamental types: char, short int, int, and long int.
If you are counting bytes, then you should definitely be using size_t. If you are counting the number of elements, then you should probably use size_t since this seems to be what C++ has been using. In any case, you don't want to use int - at the very least use unsigned long or unsigned long long if you are using TR1. Or... even better... typedef whatever you end up using to size_type or just include <cstddef> and use std::size_t.
|
994,353
| 994,428
|
Static variable inside template function
|
In C++, if you define this function in header.hpp
void incAndShow()
{
static int myStaticVar = 0;
std::cout << ++myStaticVar << " " << std::endl;
}
and you include header.hpp in at least two .cpp files. Then you will have multiple definition of incAndShow(). Which is expected. However, if you add a template to the function
template <class T>
void incAndShow()
{
static int myStaticVar = 0;
std::cout << ++myStaticVar << " " << std::endl;
}
then you won't have any multiple definition of error. Likewise, two different .cpp calling the function with the same template (e.g. incAndShow<int>()), will share myStaticVar. Is this normal? I'm asking this question, because I do rely on this "feature" (sharing the static variable) and I want to be sure that it is not only my implementation that is doing this.
|
You can rely on this. The ODR (One Definition Rule) says at 3.2/5 in the Standard, where D stands for the non-static function template (cursive font by me)
If D is a template, and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.
Of the last four requirements, the two most important are roughly
each definition of D shall consist of the same sequence of tokens
names in each definition shall refer to the same things ("entities")
Edit
I figure that this alone is not sufficient to guarantee that your static variables in the different instantiations are all the same. The above only guarantees that the multiple definitions of the template is valid. It doesn't say something about the specializations generated from it.
This is where linkage kicks in. If the name of a function template specialization (which is a function) has external linkage (3.5/4), then a name that refers to such a specialization refers to the same function. For a template that was declared static, functions instantiated from it have internal linkage, because of
Entities generated from a template with internal linkage are distinct from all entities generated in other translation units. -- 14/4
A name having namespace scope (3.3.6) has internal linkage if it is the name of [...] an object, reference, function or function template that is explicitly declared static -- 3.5/3
If the function template wasn't declared with static, then it has extern linkage (that, by the way, is also the reason that we have to follow the ODR at all. Otherwise, D would not be multiply defined at all!). This can be derived from 14/4 (together with 3.5/3)
A non-member function template can have internal linkage; any other template name shall have external linkage. -- 14/4.
Finally, we come to the conclusion that a function template specialization generated from a function template with external linkage has itself external linkage by 3.5/4:
A name having namespace scope has external linkage if it is the name of [...] a function, unless it has internal linkage -- 3.5/4
And when it has internal linkage was explained by 3.5/3 for functions provided by explicit specializations, and 14/4 for generated specializations (template instantiations). Since your template name has external linkage, all your specializations have external linkage: If you use their name (incAndShow<T>) from different translation units, they will refer to the same functions, which means your static objects will be the same in each occasion.
|
994,518
| 994,523
|
Header file for functions inside of a namespace?
|
In C++ I have a file A.cpp that has the following in it:
namespace Foo {
bool Bar()
{
return true;
}
}
How would I declare this function in A.h? How do I handle the namespace?
|
namespace Foo {
bool Bar();
}
|
994,593
| 994,623
|
How to do an integer log2() in C++?
|
In the C++ standard libraries I found only a floating point log method. Now I use log to find the level of an index in a binary tree ( floor(2log(index)) ).
Code (C++):
int targetlevel = int(log(index)/log(2));
I am afraid that for some of the edge elements (the elements with value 2^n) log will return n-1.999999999999 instead of n.0. Is this fear correct? How can I modify my statement so that it always will return a correct answer?
|
You can use this method instead:
int targetlevel = 0;
while (index >>= 1) ++targetlevel;
Note: this will modify index. If you need it unchanged, create another temporary int.
The corner case is when index is 0. You probably should check it separately and throw an exception or return an error if index == 0.
|
994,764
| 994,779
|
Rounding doubles - .5 - sprintf
|
I'm using the following code for rounding to 2dp:
sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double
It successfully rounds 6.666 to 6.67, but it doesn't work properly when rounding
5.555. It returns 5.55, whereas it should (at least in my opinion) return 5.56.
How can I get it to round up when the next digit is 5? i.e. return 5.56.
edit: I now realise that this is happening because when I enter 5.555 with cin it gets
saved as 5.554999997.
I'm going to try rounding in two stages- first to 3dp and then to 2dp. any other
(more elegant) ideas?
|
It seems you have to use math round function for correct rounding.
printf("%.2f %.2f\n", 5.555, round(5.555 * 100.)/100.);
This gives the following output on my machine:
5.55 5.56
|
994,905
| 994,937
|
Is there ever a need for a "do {...} while ( )" loop?
|
Bjarne Stroustrup (C++ creator) once said that he avoids "do/while" loops, and prefers to write the code in terms of a "while" loop instead. [See quote below.]
Since hearing this, I have found this to be true. What are your thoughts? Is there an example where a "do/while" is much cleaner and easier to understand than if you used a "while" instead?
In response to some of the answers: yes, I understand the technical difference between "do/while" and "while". This is a deeper question about readability and structuring code involving loops.
Let me ask another way: suppose you were forbidden from using "do/while" - is there a realistic example where this would give you no choice but to write unclean code using "while"?
From "The C++ Programming Language", 6.3.3:
In my experience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work correctly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the program was first written and tested, or later after the code preceding it has been modified. I also prefer the condition "up front where I can see it." Consequently, I tend to avoid do-statements. -Bjarne
Avoiding the do/while loop is a recommendation included in the C++ Core Guidelines as ES.75, avoid do-statements.
|
Yes I agree that do while loops can be rewritten to a while loop, however I disagree that always using a while loop is better. do while always get run at least once and that is a very useful property (most typical example being input checking (from keyboard))
#include <stdio.h>
int main() {
char c;
do {
printf("enter a number");
scanf("%c", &c);
} while (c < '0' || c > '9');
}
This can of course be rewritten to a while loop, but this is usually viewed as a much more elegant solution.
|
994,907
| 994,963
|
Passing a Safearray of custom types from C++ to C#
|
how can one use a Safearray to pass an array of custom types (a class containing only properties) from C++ to C#? Is using the VT_RECORD type the right way to do it?
I am trying in the following way, but SafeArrayPutElement returns an error when trying to fill the safearray the reference to the array of classes gets to the managed code as a NULL.
I have something like the following in the managed world:
[ComVisible(true)]
public interface IStatistics
{
double Mean { get; set; }
double StdDev { get; set; }
}
[Serializable]
[ComVisible(true)]
public class Statistics : IStatistics
{
public Mean { get; set; }
public double StdDev { get; set; }
}
Unmanaged world:
HRESULT hr = CoInitialize(NULL);
...
SAFEARRAY *pEquationsStatistics;
// common dimensions for all arrays
SAFEARRAYBOUND dimensions[1];
dimensions[0].cElements = 2;
dimensions[0].lLbound = 0;
pEquationsStatistics = SafeArrayCreate(VT_RECORD, 1, dimensions);
...
for (long i = 0; i < dimensions[0].cElements; i++)
{
long indices[1];
indices[0] = 0;
...
// Equation statistics
IStatisticsPtr pIStatistics(__uuidof(Statistics));
pIStatistics->PutMean(1.0); // so far so good
result = SafeArrayPutElement(pEquationsStatistics, indices, pIStatistics);
...
indices[0]++;
}
Please note that the I am able use the SafeArray to pass other arrays of BSTR with no problems between the two applications. So this is something peculiar to passing a structure.
Stefano
|
I'm not really sure if I understand your question right, but maybe you need VT_DISPATCH?
I think if you want it to work with VT_RECORD, then your struct should actually be a struct (not a class) and also needs the [StructLayout(LayoutKind.Sequential)] attribute.
Edit: Can it be that the error you first got was DISP_E_BADINDEX? What exactly is indices in your code? What does it contain? (You know that the signature of SafeArrayPutElement requires it to be a pointer, right?)
|
994,949
| 995,287
|
Specialize Function Templates vs Function Overload vs Class Specializing
|
According to this article from Herb Sutter, one should always pick Class Specializing over Function Overload and definitely over Specialized Function Templates.
The reason is that
Specializations don't overload. Overload resolution only selects a base template (or a nontemplate function, if one is available). Only after it's been decided which base template is going to be selected, and that choice is locked in, will the compiler look around to see if there happens to be a suitable specialization of that template available, and if so that specialization will get used.
we can’t particial specialize function templates.
I must admit that before I read the article I have banged my head against the wall a few times. Why isn’t he picking my specialized function …
After reading the article I’ve never used Specialized Function Templates again.
Example:
template <class T> void foo( T t);
We should write foo like this so we can specialize it with class templates instead of function specializing.
template<class T>
struct FooImpl;
template <class T> void foo( T t) {
FooImpl<T>::foo(t);
}
Now we can specialze the template and don’t have to worry about the overload rules and we can even partitial specialize the template like this:
template<class U, class V>
struct FooImpl< QMap< U, V > >;
Here is the question.
It seems that the StackOverflow members prefer Specialized Function Templates? Why?
Because the Specialized Function Templates get a lot more upvotes than the Overload Solutions and the Class Specializing.
With the information that i have at the moment i find it perverse because i know that i can get it right, but i know that the one who comes after me will hit the wall.
There are already some links to the GOTWCA article so you must have read the article. This means that upvoters must have some extra information, please stand up and enlighten me.
|
The problem with explicitly specialising a function template only applies if the function is also overloaded:
template <typename T> void foo (T*); // #1
template <typename T> void foo (T); // #2
template <> void foo<int*> (int*);
int main () {
int * i;
foo (i); // Calls #1 not specialization of #2
}
Without the #1 overload, the code will work as expected. However, a function that starts out not being overloaded may have overloads added as the code is maintained into the future.
This is one of those examples where, although I hate to say it, C++ has too many ways to do the same thing. Personally, if you find you need to specialise a function template, then I like the pattern suggested by TimW in his comment against Neil Butterworth's answer, ie. it's best to do so by having the current function dispatch it's call to a specialized class template instead:
template <typename T> class DoFoo {
static void do (T) { /* default behaviour */ }
};
template <> class DoFoo<int*> {
static void do (int*) { /* int * behaviour */ }
};
template <typename T> void foo (T t)
{
DoFoo<T>::do (t);
}
If 'foo' is overloaded, then at least it's clearer to the developer that this function won't be called, ie. the developer doesn't need to be a standards guru to know how the specialization rules interact with overload resolution.
Ultimately, however, the code generated by the compiler is going to be the same, this is purely a code comprehension issue on the part of the developer.
|
995,253
| 995,311
|
How to compile the Botan crypto library as a static lib in VC++?
|
I've been extremely unsuccessful in compiling Botan as a static library in Visual C++. The build.h file contains the following code:
#ifndef BOTAN_DLL
#define BOTAN_DLL __declspec(dllexport)
#endif
This macro then shows up pretty much everywhere in the Botan codebase, like this:
class BOTAN_DLL AutoSeeded_RNG : public RandomNumberGenerator
My understanding from a previous question is that all you need to do is define BOTAN_DLL without a value and it should compile as a static library just fine. However, doing so causes a huge list of build errors like "missing tag name." Anyone know how to do this?
EDIT: Here is a sample of the errors that result from adding /D "BOTAN_DLL" to the makefile:
cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /D "BOTAN_DLL" /nologo
/c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj
adler32.cpp
build\include\botan/allocate.h(19) : error C2332: 'class' : missing tag name
build\include\botan/allocate.h(19) : error C2143: syntax error : missing ';' bef
ore 'constant'
build\include\botan/allocate.h(19) : error C2059: syntax error : 'constant'
build\include\botan/allocate.h(20) : error C2143: syntax error : missing ';' bef
ore '{'
build\include\botan/allocate.h(20) : error C2447: '{' : missing function header
(old-style formal list?)
build\include\botan/secmem.h(229) : error C2143: syntax error : missing ';' befo
re '*'
build\include\botan/secmem.h(230) : see reference to class template inst
antiation 'Botan::MemoryRegion<T>' being compiled
build\include\botan/secmem.h(229) : error C4430: missing type specifier - int as
sumed. Note: C++ does not support default-int
|
What are the first few error messages you get? Maybe you have forgotten a header file include?
It looks like maybe your compilation command is wrong:
cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /D "BOTAN_DLL" /nologo
/c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj
I think you incorrectly have a space between the /D directive and the value of the preprocessor symbol you are defining. It should be this:
cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /DBOTAN_DLL= /nologo
/c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj
EDIT: if you have /DBOTAN_DLL, this is equivalent to /DBOTAN_DLL=1, you want to use /DBOTAN_DLL= which will give it no associated value. With this /DBOTAN_DLL, it is inserted into your code as the value 1, and the compiler sees the error:
class 1 Allocator { ...
|
995,314
| 995,330
|
boost::bind and class member function
|
Consider following example.
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
void
func(int e, int x) {
std::cerr << "x is " << x << std::endl;
std::cerr << "e is " << e << std::endl;
}
struct foo {
std::vector<int> v;
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(func, _1, x));
}
void func2(int e, int x) {
std::cerr << "x is " << x << std::endl;
std::cerr << "e is " << e << std::endl;
}
};
int
main()
{
foo f;
f.v.push_back(1);
f.v.push_back(2);
f.v.push_back(3);
f.v.push_back(4);
f.calc(1);
return 0;
}
All works fine if I use func() function. But in real life application I have to use class member function, i.e. foo::func2() in this example. How can I do this with boost::bind ?
|
You were really, really close:
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(&foo::func2, this, _1, x));
}
EDIT: oops, so was I. heh.
Although, on reflection, there is nothing really wrong with your first working example. You should really favour free functions over member functions where possible - you can see the increased simplicity in your version.
|
995,434
| 995,456
|
Arrays of strings in Managed C++
|
I'm trying to write an application in Managed C++, but I cannot work out how to declare an array of strings.
String^ linet[];
throws an error
'System::String ^' : a native array cannot contain this managed type
So I suppose there's a different way to do this for managed data types. What exactly is it?
|
Do you really mean Managed C++? Not C++/CLI?
Assuming you're actually using C++/CLI (because of the error message you posted), there are two ways to do this:
array<String^>^ managedArray = gcnew array<String^>(10);
will create a managed array, i.e. the same type as string[] in C#.
gcroot<String^>[] unmanagedArray;
will create an unmanaged C++ array (I've never actually tried this with arrays - it works well with stl containers, so it should work here, too).
|
995,902
| 26,982,335
|
Unable to find the location of C++'s standard libraries in OS/X?
|
I have looked at /System/Library, but I have not found the iostream library/module by
ack iostream
Where are the standard libraries in OS/X?
|
On OS X 10.10 Yosemite, they're located here:
/usr/include/c++
|
996,135
| 996,154
|
How are Java generics different from C++ templates? Why can't I use int as a parameter?
|
I am trying to create
ArrayList<int> myList = new ArrayList<int>();
in Java but that does not work.
Can someone explain why int as type parameter does not work?
Using Integer class for int primitive works, but can someone explain why int is not accepted?
Java version 1.6
|
Java generics are so different from C++ templates that I am not going to try to list the differences here. (See What are the differences between “generic” types in C++ and Java? for more details.)
In this particular case, the problem is that you cannot use primitives as generic type parameters (see JLS §4.5.1: "Type arguments may be either reference types or wildcards.").
However, due to autoboxing, you can do things like:
List<Integer> ints = new ArrayList<Integer>();
ints.add(3); // 3 is autoboxed into Integer.valueOf(3)
So that removes some of the pain. It definitely hurts runtime efficiency, though.
|
996,200
| 996,251
|
Is there a right way to return a new object instance by reference in C++?
|
So I was writing some code, and I had something like this:
class Box
{
private:
float x, y, w, h;
public:
//...
Rectangle & GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
};
Then later in some code:
Rectangle rect = theBox.GetRect();
Which worked in my debug build, but in release there were "issues" returning that Rectangle by reference -- I basically got an uninitialized rectangle. The Rectangle class has an = operator and a copy constructor. Without getting into why this broke, I'm actually more interested in the correct way to return a (new) object by reference for the purpose of assigning copying to a variable. Am I just being silly? Should it not be done? I know I can return a pointer and then dereference on assignment, but I'd rather not. Some part of me feels like returning by value would result in redundant copying of the object -- does the compiler figure that out and optimize it?
It seems like a trivial question. I feel almost embarrassed I don't know this after many years of C++ coding so hopefully someone can clear this up for me. :)
|
You can't return a reference to a temporary object on the stack. You have three options:
Return it by value
Return by reference via a pointer to something that you created on the heap with the new operator.
Return by reference what you received by reference as an argument. [EDIT: Thanks to @harshath.jr for pointing this out]
Note that when you return by value as in the code below, the compiler should optimize the assignment to avoid the copy - i.e. it will just create a single Rectangle (rect) by optimizing the create+assign+copy into a create. This only works when you create the new object when returning from the function.
Rectangle GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
Rectangle rect = theBox.GetRect();
|
996,844
| 996,868
|
C++ shift operator precedence weirdness
|
Consider the following code:
typedef vector<int> intVec;
intVec& operator<<(intVec& dst, const int i) {
dst.push_back(i);
return dst;
}
int intResult0() {
return 23;
}
int intResult1() {
return 42;
}
// main
intVec v;
v << intResult0() << intResult1();
The weird thing is, that the compiler generates code, which evaluates intResult1 BEFORE intResult0 (tested with newest VC und gcc).
Why would the compiler do this? By doing so, the time between evaluation and usage of the respective values is (unnecessarily) increased(?), i.e. 42 is fetched first, but pushed last to the vector.
Does the C++ standard dictate this?
|
According to Stroustrup section 6.2.2:
The order of evaluation of
subexpressions within an expression is
undefined.
|
997,018
| 997,137
|
JNI Call to Authenticate user using LogonUser?
|
C++ noob here wonding how i can authenticate a Windows User via Java servlet.
Here is the code i have put together to take in a JNI call from my java servlet with the user's username domain and password:
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include "Validate.h"
JNIEXPORT jstring JNICALL Java_Validate_takeInfo(JNIEnv *env, jobject obj, jstring domain, jstring id, jstring idca, jstring password)
{
const char *nt_domain;
const char *nt_id;
const char *nt_idca;
const char *nt_password;
nt_domain = env->GetStringUTFChars(domain, NULL);
nt_id = env->GetStringUTFChars(id, NULL);
nt_idca= env->GetStringUTFChars(idca, NULL);
nt_password = env->GetStringUTFChars(password, NULL);
handle hToken = 0;
char *otherString;
otherString = LogonUser(nt_id, nt_domain, nt_password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken );
jstring newString = env->NewStringUTF((const char*)otherString);
return newString;
}
I get these errors when trying to compile:
D:\JNI\Validate.cpp(21) : error C2065: 'handle' : undeclared identifier
D:\JNI\Validate.cpp(21) : error C2146: syntax error : missing ';' before
ier 'hToken'
D:\JNI\Validate.cpp(21) : error C2065: 'hToken' : undeclared identifier
D:\JNI\Validate.cpp(24) : error C2065: 'LOGON32_LOGON_NETWORK' : undeclar
tifier
D:\JNI\Validate.cpp(24) : error C2065: 'LOGON32_PROVIDER_DEFAULT' : undec
dentifier
D:\JNI\Validate.cpp(24) : error C3861: 'LogonUser': identifier not found
I am assuming i am not including something i need. Any help is greatly appreciated.
|
That your compiler couldn't find LogonUser suggests that you're missing the windows headers. Include windows.h
Also, the generic windows handle type is spelled HANDLE, all in caps.
See the LogonUser docs for more details.
|
997,117
| 997,251
|
How to make configure script check the dependencies
|
I generated a configure script with autoconf to build my project.
It works fine unless I don't have some needed library installed. Make returns error when lacking some files, but it should be actually checked by the configure script i think?
So my question is: How to modify an autoconf generated script to seek for dependencies and tell the user which libraries it lacks?
|
Depends on the dependency, there is no generic solution.
There are AC_CHECK_LIB and AC_SEARCH_LIBS macros that may work for you if the libraries and headers are installed in standard locations.
Many packages nowadays support pkg-config or something similar which allows you to check for existence of libraries, and also can supply you the compiler and linker flags required.
With packages that do not work with AC macros and do not support pkg-config or similar, you'll probably have to write a ton of scripts yourself to find out whether the dependency is available and what compiler and linker options it requires. And even then it is hard to make it portable.
|
997,232
| 997,264
|
CRC error-correction library?
|
Is there a CRC library that enables the user not only detect errors but also correct them? I'm looking for a C/C++ or Java library, ideally open-source.
|
I believe that CRCs can only detect errors, not correct them. That's certainly true of the most common implementation. You want some kind of error correction technique, not a CRC. I'm not aware of any libraries for doing this, but they must be easy enough to find once you know what you're looking for.
|
997,250
| 1,002,825
|
Property Pages (Wizard) - OnQueryCancel
|
I am trying to handle the 'Cancel' button in my property pages (wizard) and I've implemented the 'OnQueryCancel' function to catch the cancel message successfully, but unfortunately it seems that the 'OnQueryCancel' function is being called twice if the user clicked the cancel button. Any ideas on how I could address this issue? Thanks!
virtual BOOL OnQueryCancel();
BOOL CWiz_Page1::OnQueryCancel()
{
int ret;
ret = MessageBox("Are you sure?", NULL, MB_YESNO);
if(ret == IDYES)
return true;
else
return false;
}
|
My first guess is that you have directly sunk the "query cancel" message (is that a message?) or maybe you have a click handler on the button itself AND it is called automatically on click of the cancel button. Try commenting out your message map entry.
Try creating a new project with classwizard and compare.
|
997,366
| 997,914
|
C++/GLFW - The right way to use Mutex objects?
|
I'm working on a simulation that uses multithreading extensively. The thing is that, until now i've never used any mutex objects to protect my data. And the result, is that i'm getting bunch of segmentation faults..
I'm trying to lock/unlock with mutex while : reading/writing but that causes me another segfault :
#0 77D27DD2 ntdll!RtlEnumerateGenericTableLikeADirectory() (C:\Windows\system32\ntdll.dll:??)
#1 00000000 ??() (??:??)
Of course, I created a test project where I applied the lock/unlock thing for a basic situation and it worked, here is a basic example that shows how to deal with Mutex objects using GLFW :
#include <GL/glfw.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> table;
GLFWmutex th_mutex;
void GLFWCALL Thread_1(void* arg) {
glfwLockMutex(th_mutex);
table.pop_back();
glfwUnlockMutex(th_mutex);
}
void GLFWCALL Thread_2(void* arg) {
glfwLockMutex(th_mutex);
table.erase(table.begin());
glfwUnlockMutex(th_mutex);
}
int main()
{
bool running = true;
GLFWthread th_1, th_2;
glfwInit();
if( !glfwOpenWindow( 512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) )
{
glfwTerminate();
return 0;
}
glfwSetWindowTitle("GLFW Application");
for(int i = 0;i < 10; i++) {
table.push_back(i);
}
th_mutex = glfwCreateMutex();
th_1 = glfwCreateThread(Thread_1, NULL);
th_2 = glfwCreateThread(Thread_2, NULL);
while(running)
{
// exit if ESC was pressed or window was closed
running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED);
}
glfwTerminate();
return 0;
}
The project, i'm working is bigger, i have 5 threads running on it, and a lot of vectors, maps, queues are accessed in the same time. Somewhere in the code, i tried to do something like :
void GLFWCALL CreateVehicleThread(void* arg) {
int index = (*static_cast<PulseStateByEntrance*>(arg)).index;
double t_initial = (*static_cast<PulseStateByEntrance*>(arg)).initial_time;
double t_final = (*static_cast<PulseStateByEntrance*>(arg)).final_time;
int pulse = (*static_cast<PulseStateByEntrance*>(arg)).pulse;
int nb_entrance = (*static_cast<PulseStateByEntrance*>(arg)).nb_entrance;
int min_time_creation = static_cast<int>(ceil(3600 / pulse));
while((glfwGetTime() - (*static_cast<PulseStateByEntrance*>(arg)).initial_time)
< ((*static_cast<PulseStateByEntrance*>(arg)).final_time - (*static_cast<PulseStateByEntrance*>(arg)).initial_time)) {
double t_elapsed = glfwGetTime() - t_initial;
if(t_elapsed > min_time_creation) {
**int nb_vehicle_per_cycle = static_cast<int>((t_elapsed * pulse)/3600);
glfwLockMutex(th_mutex);
VehicleManager::CreateVehicles(nb_vehicle_per_cycle, nb_entrance);
glfwUnlockMutex(th_mutex);**
t_initial = glfwGetTime();
}
}
}
The reason why, i'm putting my VehicleManager:CreateVehicles() method between lock/unlock is because in this method there is this line :
VehicleManager::vehicles_.push_back(vehicle);
So i wanted to protect the vector : vehicles_. But, as a result i got that segfault above. And even with :
glfwLockMutex(th_mutex);
VehicleManager::vechicles_.push_back(vehicle);
glfwUnlockMutex(th_mutex);
i got the same segfault.
I hope, i've made my self clear enough for you to understand the nature of my problem. I suppose, not all of you have worked with GLFW that's why i gave you the first basic example so you can understand how mutexes work with this library.
Thanks !
|
You could wrap your containers which will make your code easier to understand:
template<typename T>
class MultithreadedVector
{
public:
void pushback( T data )
{
glfwLockMutex(m_mutex);
m_container.push_back( data );
glfwUnlockMutex(m_mutex);
}
//then similar for erase etc
private:
std::vector<T> m_container;
GLFWmutex m_mutex;
};
|
997,498
| 997,582
|
Poker code cleanup modification from book...not quite right
|
Working through more book examples- this one is a partial poker program-
This segment deals with straight hand....
First what was given- only relevant parts....will provide entire code if needed...
int suits[5]; //index 1..4- value start at 1
int values[14]; //index 1..13- value same as rank, A = 1, K = 13
cin.get(rankCh);
switch (toUpper(rankCh)) {
case 'A': values = 1; break;
case '2': values = 2; break;
case '3': values = 3; break;
case '4': values = 4; break;
case '5': values = 5; break;
case '6': values = 6; break;
case '7': values = 7; break;
case '8': values = 8; break;
case '9': values = 9; break;
case 'T': values = 10; break;
case 'J': values = 11; break;
case 'Q': values = 12; break;
case 'K': values = 13; break;
default:
badCard = true;
}
Other functions:
bool isFlush(int suits[]) {
for(i = 1; i <= 4; i++)
if (suits[i] == 5) //5 here is Number of Cards
return true;
return false;
}
Yeah, I know about the array declarations but that is how it is defined- nice justification for it in the text...starting to number at 1
I want my straight hand to handle both Ace high and low- right now as define above aces are low...
Two versions: 1st appears not sure correct with low aces...
CODE
bool isStraight(int values[]) //Version one only straight- low aces only
{
int count = 0;
for (i = 1; i <= 13; i++) {
if (values[i] != 1) {
count++;
} else
count = 0;
if (count == 5) //5 is NUMCARDS
return true;
}
return false;
}
Now this is the where I need some recommendation: to have a function to handle both ace high and low:
bool isStraight(int values[]) //Version handles both high and low
{
int count = 0;
for (i = 1; i <= 13; i++) {
if (values[i] != 1) {
count++;
// if(i == 1 && values[1] != 0) //Check for high and low
// count++;
} else
count = 0;
if (count == 5) //5 is NUMCARDS
return true;
}
return false;
}
Would what I have in comments work to handle both ace high and low...
Since i = 1 is represented as ace and not sure what values[1] is correct should it be values[13] or what...maybe something like
if (i == 1)
values[13] //not sure...
Recommendations-
do not want wholesale changes- just to have minor changes with what I have...I do not want to sort or solve by brute force i.e like values[1] == 1 && values [2] ==1 you get the point- the text does that already but I am trying to rewrite it this way...
Thanks...Hope I am getting across my modification I would like...
|
EDIT: I figured I'd would first answer your question directly. Lets first clear up how the original algorithm worked. Basically it loops from 1 to 13, and each time it sees a card in that slot, it adds to count. If anything ever breaks the sequence, it resets the counter. Finally, if the counter reaches 5, you have a straight.
I can't say off hand if your solution would work, I say give it a go. However, a simple quick patch to the original would probably go something like this:
//Version handles both high and low
bool isStraight(int values[]) {
int count = 0;
for (i = 1; i <= 13; i++) {
if (values[i] != 1) {
count++;
} else
count = 0;
if (count == 5) //5 is NUMCARDS
return true;
}
// handle ace high.
if(count == 4 && values[1] != 0) {
return true;
}
return false;
}
Basically what that does is say "if we already have 4 in a row, and we've just looked at the very last card (the loop is over), then check an ace is there, if so, we do have a straight and it is ace high".
ORIGINAL ANSWER:
I think the easiest way to handle ace high and low is to have the "get rank" function have two modes, one which returns ace high, the other which returns ace low. Then just calculate the hand value for each case and take the better one.
Also, your get rank could be way simpler :-P.
int get_rank(char card) {
static const char *cards = "A23456789TJQK";
char *p = strchr(cards, toupper(card));
if(p) {
return (p - cards) + 1;
} else {
return -1;
}
}
so if you want to have a get_rank which has an ace_high or an ace_low, you could do this:
int get_rank(char card, bool ace_high) {
static const char *cards_high = "23456789TJQKA";
static const char *cards_low = "A23456789TJQK";
const char *cards = ace_high ? cards_high : cards_low;
char *p = strchr(cards, toupper(card));
if(p) {
return (p - cards) + 1;
} else {
return -1;
}
}
EDIT:
for fun, i've made a quick and dirty program which detects straights (handling both high and low ace). It is fairly simple, but could be shorter (also note that there is no attempt at buffer safety with these arrays, something of production quality should use something safer such as std::vector:
#include <algorithm>
#include <iostream>
#include <cstring>
int get_rank(char card, bool ace_high) {
static const char *cards_high = "23456789TJQKA";
static const char *cards_low = "A23456789TJQK";
const char *cards = ace_high ? cards_high : cards_low;
char *p = strchr(cards, toupper(card));
if(p) {
return (p - cards) + 1;
} else {
return -1;
}
}
bool is_rank_less_low(int card1, int card2) {
return get_rank(card1, false) < get_rank(card2, false);
}
bool is_rank_less_high(int card1, int card2) {
return get_rank(card1, true) < get_rank(card2, true);
}
bool is_straight(int hand[], bool ace_high) {
std::sort(hand, hand + 5, ace_high ? is_rank_less_high : is_rank_less_low);
int rank = get_rank(hand[0], ace_high);
for(int i = 1; i < 5; ++i) {
int new_rank = get_rank(hand[i], ace_high);
if(new_rank != rank + 1) {
return false;
}
rank = new_rank;
}
return true;
}
bool is_straight(int hand[]) {
return is_straight(hand, false) || is_straight(hand, true);
}
int main() {
int hand1[5] = { 'T', 'J', 'Q', 'K', 'A' };
int hand2[5] = { 'A', '2', '3', '4', '5' };
std::cout << is_straight(hand1) << std::endl;
std::cout << is_straight(hand2) << std::endl;
}
|
997,512
| 997,531
|
String representation of time_t?
|
time_t seconds;
time(&seconds);
cout << seconds << endl;
This gives me a timestamp. How can I get that epoch date into a string?
std::string s = seconds;
does not work
|
Try std::stringstream.
#include <string>
#include <sstream>
std::stringstream ss;
ss << seconds;
std::string ts = ss.str();
A nice wrapper around the above technique is Boost's lexical_cast:
#include <boost/lexical_cast.hpp>
#include <string>
std::string ts = boost::lexical_cast<std::string>(seconds);
And for questions like this, I'm fond of linking The String Formatters of Manor Farm by Herb Sutter.
UPDATE:
With C++11, use to_string().
|
997,602
| 997,666
|
Link error "LogonUser" compiling C++ program?
|
Hey Folks i am trying to compile this C++ program:
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <Windows.h>
#include "Validate.h"
JNIEXPORT jstring JNICALL Java_Validate_takeInfo(JNIEnv *env, jobject obj,
jstring domain, jstring id, jstring idca, jstring password)
{
const char *nt_domain;
const char *nt_id;
const char *nt_idca;
const char *nt_password;
nt_domain = env->GetStringUTFChars(domain, NULL);
nt_id = env->GetStringUTFChars(id, NULL);
nt_idca= env->GetStringUTFChars(idca, NULL);
nt_password = env->GetStringUTFChars(password, NULL);
HANDLE hToken = 0;
char *otherString;
bool aut;
aut = LogonUser(nt_id, nt_domain, nt_password, LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT, &hToken );
if(aut)
{
otherString = "true";
}
else
{
otherString = "false";
}
jstring newString = env->NewStringUTF((const char*)otherString);
return newString;
}
int main()
{
return 0;
}
Using this command:
cl -I"c:\Program files\Java\jdk1.5.0_07\include"
-I"C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Include"
-I"c:\program files\java\jdk1.5.0_07\include\win32"
-LD D:\JNI\%filename%.cpp -D:\JNI\Fe%filename%.dll -link
-LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\lib"
-LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Lib"
However i always get the following error:
Validate.obj : error LNK2019: unresolved external symbol __imp__LogonUserA@24
referenced in function _Java_Validate_takeInfo@24
Validate.dll : fatal error LNK1120: 1 unresolved externals
I have probably tried a thousand different ways to compile playing with the LIBPATH switch.
-link -LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\lib";"C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Lib"
and many others.
[Update] if i switch around the lib paths and put "\PlatformSDK\lib" before the "\VC\lib" switch i get this error:
LINK : fatal error LNK1104: cannot open file 'uuid.lib'
becuase it now cannot recognise the other libpath. Any idea? [/Update]
How do i declare multiple libpaths? is there something else causing this?
As always, thanks guys
|
MSDN says that LogonUser is in Advapi32.lib. It looks like the problem is that you're not including Advapi32.lib. LIBPATH affects where the linker searches for libraries, not what libraries the linker searches for, and nowhere are you telling the linker to search for Advapi32.dll.
On Visual C++ 2008, you should be able to do include Advapi32.lib by going under Project, Properties, Configuration Properties, Linker, Additional Dependencies. I'm not sure about other versions.)
From the command line, you should be able to just list Advapi32.lib as an additional file to be linked. Try this:
cl -I"c:\Program files\Java\jdk1.5.0_07\include"
-I"C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Include"
-I"c:\program files\java\jdk1.5.0_07\include\win32"
-LD D:\JNI\%filename%.cpp -D:\JNI\Fe%filename%.dll -link
-LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\lib"
-LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Lib"
Advapi32.lib
|
997,620
| 997,796
|
How do I take a DIB and convert it to a tif using libtiff
|
I am trying to read in a scanned image and compress it from a DIB in memory into a TIF file. I am using the libtiff library and have found a couple examples online but none of them really do as I need them to. I need to take the image from the DIB and turn it into a B&W image.
Here is the code I have modified from an online example. It does turn it black and white but it also only shows one section of the scan rather than the whole thing. Any help would be appreciated.
EDIT*: I've noticed this happens if I scan it in as a gray image, if I scan it in as black and white then the image that is returned is entirely black, I don't know if this helps at all.
// set up the image tags
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, w);
TIFFSetField(tif, TIFFTAG_IMAGELENGTH, h);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 1);
TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(tif, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE);
TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
unsigned char * psrc = (unsigned char *)lpBits;
unsigned char * pdst = new unsigned char[(w)];
UINT32 src_index;
UINT32 dst_index;
// now go line by line to write out the image data
for (unsigned int row = 0; row < h; row++ )
{
// initialize the scan line to zero
memset(pdst,0,(size_t)(w));
// moving the data from the dib to a row structure that
// can be used by the tiff library
for (unsigned int col = 0; col < w; col++){
src_index = (h - row - 1) * total_width * bytecount
+ col * bytecount;
dst_index = col;
pdst[dst_index++] = psrc[src_index+2];
pdst[dst_index++] = psrc[src_index+1];
pdst[dst_index] = psrc[src_index];
result++;
}
// now actually write the row data
TIFFWriteScanline(tif, pdst, row, 0);
}
|
I may be wrong, but I think that for CCITTFAX4 encoding libtiff expects eight pixels per byte, padded to the end of the byte if the image width is not divisible by 8.
If the width of the image is 150, for example, the scanline should be 19 bytes, not 150.
There is a good example of using libtiff here, though it does not include cutting the color information off at a threshold and packing the pixels 8 per byte.
|
997,821
| 997,855
|
How to make a function return a pointer to a function? (C++)
|
I'm trying to make a function that takes a character, then returns a pointer to a function depending on what the character was. I just am not sure how to make a function return a pointer to a function.
|
#include <iostream>
using namespace std;
int f1() {
return 1;
}
int f2() {
return 2;
}
typedef int (*fptr)();
fptr f( char c ) {
if ( c == '1' ) {
return f1;
}
else {
return f2;
}
}
int main() {
char c = '1';
fptr fp = f( c );
cout << fp() << endl;
}
|
997,925
| 998,236
|
How to buffer data for send() and select()?
|
While a send() succeeds with all data being sent most of the time, it is not always the case. Thus people are advised to use the write-fdset for select() and poll() to check when the socket is writeable.
How do usual mechanisms look like to actually buffer the data to send while still maintaining a well comprehensible sourcecode?
|
As we're in C++ land, you could store the data in a std::vector
New data gets appended to the end of the vector. When you get notification that the socket is writable, try to send the complete vector. send() will return how much was really sent. Then simply erase that number of bytes from the beginning of the vector:
std::vector<char> buffer;
...
if( ! buffer.empty() )
{
int bytesRead = send( socket, &buffer[ 0 ], buffer.size(), flags );
if( bytesRead > 0 )
buffer.erase( 0, bytesRead );
else
// some error...
}
So there's probably more error checking to do, but you get the idea?
Rather queueing each individual send request, the advantage here is that you get to potentially combine multiple higher level sends into one socket send, assuming you're using TCP?
But as Remus quite rightly mentions, your flow control and API is the tricky bit - i.e. how do you stop the buffer becoming too big?
|
997,946
| 27,856,440
|
How to get current time and date in C++?
|
Is there a cross-platform way to get the current date and time in C++?
|
Since C++ 11 you can use std::chrono::system_clock::now()
Example (copied from en.cppreference.com):
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s"
<< std::endl;
}
This should print something like this:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s
|
998,072
| 1,210,290
|
Tee-ing input (cin) out to a log file (or clog)
|
I am looking for a way to branch (tee) the input read from an istream (cin, in my case) out to a log file (clog/ofstream/etc), while still using the input for processing.
I have read about boost::tee_device, and it is very similar to my requirements. Unfortunately, it is implemented as an ostream, and thus solves a similar problem from "the other side of the pipe".
I attempted to write an istream (adaptor) class which forwards the input functions on to a wrapped input stream (cin), and also sends what was read to the log file.
This works fine for basic types which call operator>>(...) directly, however, I have run into issues with some more advanced usage of the input stream, for example, for operator>>(std::string), and the std::string getline function.
Is there any easier way to do this (possibly via rdbuf() manipulation)?
Thanks!
Edit: I could change my code all over the place to something like: cin >> value; clog << value; -- but that would be a significant and ugly change. I would also prefer to have an easy way to turn logging off. Thus, I would like a way to model this as an istream "filter" and then simply replace all references to cin with this istream "logger".
Ideal Solution:
class log_istream : public std::istream
{
public:
log_istream( std::istream & in , std::ostream & out );
/* ... istream forwarding functions ... */
private:
std::istream & in_;
std::ostream & out_;
};
int main() {
log_istream logger( std::cin , std::ofstream("logfile.out") );
logger >> value; // this implies infile >> value and logfile << value
getline(logger,my_string); // this also implies logfile.writeline(value)
// etc
}
etc.
|
Final Answer:
#ifndef TEE_ISTREAM_H_
#define TEE_ISTREAM_H_
/*****************************************************************************/
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/invert.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/tr1/memory.hpp>
#include <iostream>
/*****************************************************************************/
namespace bio = boost::iostreams;
/*****************************************************************************/
class tee_source : public bio::source {
public:
tee_source( std::istream & in, const std::string & filename )
: in_(in), log_file_(filename, std::ios::app), tee_(bio::tee(log_file_), 1)
{ }
std::streamsize read(char* s, std::streamsize n)
{
return tee_.read(in_,s,n);
}
private:
std::istream & in_;
bio::file log_file_;
bio::inverse< bio::tee_filter< bio::file > > tee_;
};
/*****************************************************************************/
typedef bio::filtering_istream tee_istream_t;
typedef std::tr1::shared_ptr< tee_istream_t > tee_istream_ptr_t;
/*****************************************************************************/
inline tee_istream_ptr_t make_tee_istream( std::istream & in, const std::string & filename )
{
return tee_istream_ptr_t( new tee_istream_t( tee_source( in , filename ), 0 ) );
}
/*****************************************************************************/
#endif
|
998,162
| 998,191
|
Is it possible to disable stderr in C++?
|
I wrote a program for linux using libxml2 for html parsing. Although it does its job, the html parser writes lots of various errors to stderr. Is it possible to disable stderr at all (or redirect it to /dev/null while not having to run it with a redirecting shell script)? I can live with having to write my own errors to stdout, I just want to get rid of these errors.
|
Use freopen to redirect to dev/null:
freopen("/dev/null", "w", stderr);
|
998,247
| 998,269
|
Are static fields inherited?
|
When static members are inherited, are they static for the entire hierarchy, or just that class, i.e.:
class SomeClass
{
public:
SomeClass(){total++;}
static int total;
};
class SomeDerivedClass: public SomeClass
{
public:
SomeDerivedClass(){total++;}
};
int main()
{
SomeClass A;
SomeClass B;
SomeDerivedClass C;
return 0;
}
would total be 3 in all three instances, or would it be 2 for SomeClass and 1 for SomeDerivedClass?
|
3 in all cases, since the static int total inherited by SomeDerivedClass is exactly the one in SomeClass, not a distinct variable.
Edit: actually 4 in all cases, as @ejames spotted and pointed out in his answer, which see.
Edit: the code in the second question is missing the int in both cases, but adding it makes it OK, i.e.:
class A
{
public:
static int MaxHP;
};
int A::MaxHP = 23;
class Cat: A
{
public:
static const int MaxHP = 100;
};
works fine and with different values for A::MaxHP and Cat::MaxHP -- in this case the subclass is "not inheriting" the static from the base class, since, so to speak, it's "hiding" it with its own homonymous one.
|
998,248
| 998,253
|
How can I stop g++ from linking unwanted exception-handling code?
|
I'm developing an embedded application using GCC/G++ compiled for arm-eabi. Due to resource constraints, I'm trying to disable the standard C++ exception handling. I'm compiling the code with "-fno-exceptions
-nostartfiles -ffreestanding".
When a global instance of a class exists, and that class contains an instance of another class as a member, then a lot of exception handling code is being linked in. This wouldn't be so bad, except that it's also bringing in lots of stdio stuff, like printf, fopen, fclose and other FILE functions. This application has no filesystem, and even if it did, these functions waste too much code space.
I understand that even with -fno-exceptions, G++ links in an operator new that uses exceptions, because the library doesn't have a non-exception-using operator new (except new(nothrow)). I created replacements for operator new and delete, and these are linked into the output as well as the unwanted standard-library functions.
What puzzles me is that I'm not calling new anywhere. It's only when a global object contains another object that all this code is linked in.
For example:
class UartA {
...
private:
Ringbuffer* rxbuf;
};
class UartB {
...
private:
Ringbuffer rxbuf;
};
If a global instance of UartA is created, the exception handling, operator new, and stdio stuff are not linked in. This is what I want.
If a global instance of UartB is created (where rxbuf is an instance instead of a pointer), the unwanted code is linked in.
Neither UartA nor UartB use operator new, exceptions or stdio. They differ only by the type of rxbuf.
Can you suggest how to prevent linking the extra code? Also, why is this being linked in for UartB, but not UartA?
|
I think the closest you can get is compiling and linking with -fno-exceptions and -fno-rtti. If there's a better way to get rid of the rest, I'd be glad to hear it myself.
As far as getting rid of new, try -nostdlib.
|
998,311
| 998,418
|
How to declare two different static variables? (C++)
|
EDIT: declaring them private was a typo, I fixed it:
Relating to another question, if I declared a static variable in a class, then derived a class from that, is there any way to declare the static variable as individual per each class. Ie:
class A:
{
public:
static int x;
};
class B:A
{
public:
const static int x;
};
does that define TWO DIFFERENT static variables x, one for A and one for B, or will I get an error for redefining x, and if I do get an error, how do a I create two seperate static variables?
|
When you're using static variables, it might be a good idea to refer to them explicitly:
public class B:A
{
public const static int x;
public int foo()
{
return B::x;
}
}
That way, even if the class "above" yours in the hierarchy decides to create a similarly-named member, it won't break your code. Likewise, I usually try to us the this keyword when accessing normal member fields.
Updated to use C++ syntax.
|
998,425
| 998,457
|
Why does const imply internal linkage in C++, when it doesn't in C?
|
See subject. What were they thinking?
UPDATE: Changed from "static" to "internal linkage" to save confusion.
To give an example... Putting the following in a file:
const int var_a = 1;
int var_b = 1;
...and compiling with g++ -c test.cpp only exports var_b.
|
I believe you mean
Why does const imply internal linkage in C++
It's true that if you declare a const object at namespace scope, then it has internal linkage.
Appendix C (C++11, C.1.2) gives the rationale
Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage
Rationale: Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put const objects in header files that are included in many compilation units.
|
998,429
| 998,478
|
OpenCV: Accessing And Taking The Square Root Of Pixels
|
I'm using OpenCV for object detection and one of the operations I would like to be able to perform is a per-pixel square root. I imagine the loop would be something like:
IplImage* img_;
...
for (int y = 0; y < img_->height; y++) {
for(int x = 0; x < img_->width; x++) {
// Take pixel square root here
}
}
My question is how can I access the pixel value at coordinates (x, y) in an IplImage object?
|
Assuming img_ is of type IplImage, and assuming 16 bit unsigned integer data, I would say
unsigned short pixel_value = ((unsigned short *)&(img_->imageData[img_->widthStep * y]))[x];
See also here for IplImage definition.
|
998,571
| 998,686
|
C++ Template for safe integer casts
|
I am trying to write a C++ template function that will throw a runtime exception on integer overflow in casts between different integral types, with different widths, and possible signed/unsigned mismatch. For these purposes I'm not concerned with casting from floating-point types to integral types, nor other object-to-object conversions. I'd like to do this without having to write lots of special case code. This is what I currently have:
template< typename T, typename R > void safe_cast( const T& source, R& result )
{
// get the maximum safe value of type R
R rMax = (R) ~0;
if ( rMax < 0 ) // R is a signed type
{
// assume that we're on an 8-bit twos-compliment machine
rMax = ~( 0x80 << ( ( sizeof( R ) - 1 ) * 8 ) );
}
if ( ( source & rMax ) != source )
{
throw new IntegerOverflowException( source );
}
result = static_cast<R>( source );
}
Is this correct and efficient?
EDIT: For various reasons stl isn't available, so I can't use std::numeric_limits, and anything from Boost is right out.
|
Have you tried SafeInt? It's a cross platform template that will do integer overflow checks for a variety of integer types. It's available on github
https://github.com/dcleblanc/SafeInt
|
999,120
| 999,218
|
C++ "hello world" Boost tee example program
|
The Boost C++ library has Function Template tee
The class templates tee_filter and tee_device provide two ways to split an output sequence
so that all data is directed simultaneously to two different locations.
I am looking for a complete C++ example using Boost tee to output to standard out and to a file like "sample.txt".
|
Based on help from the question John linked:
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
using std::ostream;
using std::ofstream;
using std::cout;
namespace bio = boost::iostreams;
using bio::tee_device;
using bio::stream;
int main()
{
typedef tee_device<ostream, ofstream> TeeDevice;
typedef stream<TeeDevice> TeeStream;
ofstream ofs("sample.txt");
TeeDevice my_tee(cout, ofs);
TeeStream my_split(my_tee);
my_split << "Hello, World!\n";
my_split.flush();
my_split.close();
}
|
999,303
| 1,000,048
|
Qt: Custom widget in QScrollArea
|
I am attempting to create a custom widget. My Widget renders itself unless it is inside a scroll area. The code below works. If I change the if(0) to an if(1) inside the MainWindow constructor, it will not render the "Hello World" string. I assume that I must (re)implement some additional methods, but so far I have not been able to find the correct ones with trial and error.
// hellowidget.h
#ifndef HELLOWIDGET_H
#define HELLOWIDGET_H
#include <QtGui>
class HelloWidget : public QWidget
{
Q_OBJECT
public:
HelloWidget(QWidget *parent = 0);
void paintEvent(QPaintEvent *event);
};
#endif // HELLOWIDGET_H
// hellowidget.cpp
#include "hellowidget.h"
HelloWidget::HelloWidget(QWidget *parent)
: QWidget(parent)
{
}
void HelloWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawText(rect(), Qt::AlignCenter, "Hello World");
}
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private:
};
#endif // MAINWINDOW_H
// mainwindow.cpp
#include "mainwindow.h"
#include "hellowidget.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
HelloWidget *hello = new HelloWidget;
QWidget *central = hello;
if( 0 )
{
QScrollArea *scroll = new QScrollArea ;
scroll->setWidget(hello);
central = scroll;
}
setCentralWidget( central );
}
MainWindow::~MainWindow()
{
}
// main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
You just have to give your HelloWidget a size and place.
Add this line to your code.
hello->setGeometry(QRect(110, 80, 120, 80));
Or if you want to fill the scroll area with your widget:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QScrollArea *const scroll(new QScrollArea);
QHBoxLayout *const layout(new QHBoxLayout(scroll));
HelloWidget *const hello(new HelloWidget);
hello->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
layout->addWidget(hello);
setCentralWidget( scroll );
}
|
999,340
| 999,353
|
Question about pure virtual destructor
|
If we define a abstract class which has a pure virtual destructor, why do we have to give a definition of a destructor in the abstract class?
|
The destructor for the base class must be called when the object is destroyed, so it needs a definition.
|
999,358
| 999,383
|
"Undefined symbols" linker error with simple template class
|
Been away from C++ for a few years and am getting a linker error from the following code:
Gene.h
#ifndef GENE_H_INCLUDED
#define GENE_H_INCLUDED
template <typename T>
class Gene {
public:
T getValue();
void setValue(T value);
void setRange(T min, T max);
private:
T value;
T minValue;
T maxValue;
};
#endif // GENE_H_INCLUDED
Gene.cpp
#include "Gene.h"
template <typename T>
T Gene<T>::getValue() {
return this->value;
}
template <typename T>
void Gene<T>::setValue(T value) {
if(value >= this->minValue && value <= this->minValue) {
this->value = value;
}
}
template <typename T>
void Gene<T>::setRange(T min, T max) {
this->minValue = min;
this->maxValue = max;
}
Using Code::Blocks and GCC if it matters to anyone. Also, clearly porting some GA stuff to C++ for fun and practice.
|
The template definition (the cpp file in your code) has to be included prior to instantiating a given template class, so you either have to include function definitions in the header, or #include the cpp file prior to using the class (or do explicit instantiations if you have a limited number of them).
|
999,371
| 999,400
|
Container of pointers
|
I'm having some trouble in declaring a STL Set of pointers to class instances. More specifically, I have this scenario:
class SimulatedDiskFile {
private:
// ...
public:
// ...
struct comparator {
bool operator () (SimulatedDiskFile* const& file_1, SimulatedDiskFile* const& file_2) {
return ((*file_1)->getFileName() < (*file_2)->getFileName());
}
};
}
typedef set<SimulatedDiskFile*, SimulatedDiskFile::comparator> FileSet;
The code above is not working. Compiler says it didn't find a member SimulatedDiskFile::comparator() function. If I put the function with this declaration (outside the struct), compiler says it was expecting a type.
Now here com my doubts (not only one, but related, I guess):
What is the the correct declaration for a set of pointers?
What is the correct declaration for a comparison funcion that compares pointers?
I did look up in many places before posting, but I found the references confusing and not quite related to my special case (as stupidly trivial as I think it is - actually, maybe this is the cause). So, any good links are of great help too!
Thanks in advance!
|
Fixing a few glitches,
#include <set>
class SimulatedDiskFile {
public:
int getFileName() { return 23; }
struct comparator {
bool operator () (SimulatedDiskFile* file_1, SimulatedDiskFile* file_2) {
return (file_1->getFileName() < file_2->getFileName());
}
};
};
typedef std::set<SimulatedDiskFile*, SimulatedDiskFile::comparator> FileSet;
compiles just fine.
|
999,699
| 999,717
|
Thread Safe Data and Thread Safe Containers
|
Hi Guys I want to know what is the difference between thread safe Data and Thread Safe Containers
|
Thread safe data:
Generally refers to data which is protected using mutexes, semaphores or other similar constructs.
Data is considered thread safe if measures have been put in place to ensure that:
It can be modified from multiple threads in a controlled manner, to ensure the resultant data structure doesn't becoming corrupt, or lead to race conditions in the code.
It can be read in a reliable fashion without the data become corrupt during the read process. This is especially important with STL-style containers which use iterators.
Mutexes generally work by blocking access to other threads while one thread is modifying shared data. This is also known as a critical section, and RAII is a common design pattern used in conjunction with critical sections.
Depending on the CPU type, some primitive data types (e.g. int) and operations (increment) might not need mutex protection (e.g. if they resolve down to an atomic instruction in machine language). However:
It is bad practice to make any assumptions about CPU architecture.
You should always code defensively to ensure code will remain thread-safe regardless of the target platform.
Thread safe containers:
Are containers which have measures in place to ensure that any changes made to them occur in a thread-safe manner.
For example, a thread safe container may allow items to be inserted or removed using a specific set of public methods which ensure that any code which uses it is thread-safe.
In other words, the container class provides the mutex protection as a service to the caller, and the user doesn't have to roll their own.
|
999,727
| 999,734
|
Cannot convert from 'const wchar_t *' to '_TCHAR *'
|
_TCHAR* strGroupName = NULL;
const _TCHAR* strTempName = NULL;
//Assign some value to strTempName
strGroupName = _tcschr(strTempName, 92) //C2440
I get an error at the above line while compiling this code in VS2008. In VC6 it compiles fine.
Error C2440: '=' : cannot convert from
'const wchar_t *' to '_TCHAR *'
What seems to be the problem and how do I fix it?
|
Try casting it as
strGroupName = (_TCHAR*)_tcschr(strTempName, 92);
Seems to me that VS2008 got a little more strict on type casts, and won't automatically do them in some cases.
|
1,000,167
| 1,000,198
|
Error C2593: Operator = is ambiguous
|
typedef map<wstring , IWString> REVERSETAG_CACHE ;
REVERSETAG_CACHE::iterator revrsetagcacheiter;
.
.
.
wstring strCurTag;
strCurTag = revrsetagcacheiter->second; //Error C2593
Error C2593: Operator = is ambiguous
Why does the above assignment give this error? It works in VC6. Does not compile in VC9.
|
revrsetagcacheiter->second is of type IWString .
Hence it won't compile. I don't think it will compile in VC6 also.
I'll try one final time: Is your BasicString class c_str() method ? If so try converting it to wstring using std::wstring str(iter->second.c_str());
|
1,000,303
| 1,000,320
|
Is there a faster way to detect object type at runtime than using dynamic_cast?
|
I have a hierarchy of types - GenericClass and a number of derived classes, InterestingDerivedClass included, GenericClass is polymorphic. There's an interface
interface ICallback {
virtual void DoStuff( GenericClass* ) = 0;
};
which I need to implement. Then I want to detect the case when GenericClass* pointer passed into ICallback::DoStuff() is really a pointer to InterestingDerivedClass:
class CallbackImpl : public ICallback {
void DoStuff( GenericClass* param ) {
if( dynamic_cast<InterestingDerivedClass*>( param ) != 0 ) {
return; //nothing to do here
}
//do generic stuff
}
}
The GenericClass and the derived classes are out of my control, I only control the CallbackImpl.
I timed the dynamic_cast statement - it takes about 1400 cycles which is acceptable for the moment, but looks like not very fast. I tried to read the disassembly of what is executed during dynamic_cast in the debugger and saw it takes a lot of instructions.
Since I really don't need the pointer to the derived class is there a faster way of detecting object type at runtime using RTTI only? Maybe some implementation-specific method that only checks the "is a" relationship but doesn't retrieve the pointer?
|
I always look on the use of dynamic_cast as a code smell. You can replace it in all circumstances with polymorphic behaviour and improve your code quality. In your example I would do something like this:
class GenericClass
{
virtual void DoStuff()
{
// do interesting stuff here
}
};
class InterestingDerivedClass : public GenericClass
{
void DoStuff()
{
// do nothing
}
};
class CallbackImpl : public ICallback {
void DoStuff( GenericClass* param ) {
param->DoStuff();
}
}
In your case, you cannot modify the target classes, you are programming to a contract implied by the declaration of the GenericClass type. Therefore, there is unlikely to be anything that you can do that would be faster than dynamic_cast would be, since anything else would require modifying the client code.
|
1,000,343
| 1,051,256
|
Boost serialization problem
|
i have situation like this:
class IData
{
virtual void get() = 0;
virtual void set() = 0;
}
BOOST_ASSUME_IS_ABSTRACT(IData)
BOOST_EXPORT_CLASS(IData)
template<typename T>
class ConcreteData : public IData
{
public:
protected:
template<typename Archive>
void serialize(Archive& ar, const unsigned version)
{
ar & data;
}
private:
std::vector<T> mData;
}
BOOST_EXPORT_CLASS(ConcreteData<float>)
BOOST_EXPORT_CLASS(ConcreteData<int>)
BOOST_EXPORT_CLASS(ConcreteData<double>)
i want to serialize and deserialize "IData" instances via boost serialization but it seems not working. Has anyone done this before or do you have any suggestions.by the way i am usin VS 2005.
|
Try using BOOST_CLASS_EXPORT_GUID instead:
BOOST_CLASS_EXPORT_GUID(ConcreteData<float>, "ConcreteData<float>")
BOOST_CLASS_EXPORT_GUID(ConcreteData<int>, "ConcreteData<int>")
|
1,000,577
| 4,790,981
|
Can I stop COM from swallowing uncaught C++ exceptions in the callee process?
|
I am maintaining a project which uses inter-process COM with C++. At the top level of the callee functions there are try/catch statements directly before the return back through COM. The catch converts any C++ exceptions into custom error codes that are passed back to the caller through the COM layer.
For the purpose of debugging I want to disable this try/catch, and simply let the exception cause a crash in the callee process (as would normally happen with an uncaught C++ exception). Unfortunately for me the COM boundary seems to swallow these uncaught C++ exceptions and I don't get a crash.
Is there a way to change this behaviour in COM? Ie, I want it to allow the uncaught C++ exception to cause a crash in the callee process.
I want this to happen so that I can attach a debugger and see the context in which the exception is thrown. If I simply leave our try/catch in place, and breakpoint on the catch, then the stack has already unwound, and so this is too late for me.
The original "COM masters" who wrote this application are all either unavailable or can't remember enough details.
|
This just in, a year and a half after the question was asked -
Raymond Chen has written a post about "How to turn off the exception handler that COM 'helpfully' wraps around your server". Seems like the ultimate answer to the question. If not for the OP, for future readers.
|
1,000,663
| 1,000,672
|
Using a C++ class member function as a C callback function
|
I have a C library that needs a callback function to be registered to customize some processing. Type of the callback function is int a(int *, int *).
I am writing C++ code similar to the following and try to register a C++ class function as the callback function:
class A {
public:
A();
~A();
int e(int *k, int *j);
};
A::A()
{
register_with_library(e)
}
int
A::e(int *k, int *e)
{
return 0;
}
A::~A()
{
}
The compiler throws following error:
In constructor 'A::A()',
error:
argument of type ‘int (A::)(int*, int*)’ does not match ‘int (*)(int*, int*)’.
My questions:
First of all is it possible to register a C++ class member function like I am trying to do and if so how?
(I read 32.8 at http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html. But in my opinion it does not solve the problem)
Is there a alternate/better way to tackle this?
|
You can do that if the member function is static.
Non-static member functions of class A have an implicit first parameter of type class A* which corresponds to this pointer. That's why you could only register them if the signature of the callback also had the first parameter of class A* type.
|
1,000,908
| 15,445,167
|
Is it possible to forbid deriving from a class at compile time?
|
I have a value class according to the description in "C++ Coding Standards", Item 32. In short, that means it provides value semantics and does not have any virtual methods.
I don't want a class to derive from this class. Beside others, one reason is that it has a public nonvirtual destructor. But a base class should have a destructor that is public and virtual or protected and nonvirtual.
I don't know a possibility to write the value class, such that it is not possible to derive from it. I want to forbid it at compile time. Is there perhaps any known idiom to do that? If not, perhaps there are some new possibilities in the upcoming C++0x? Or are there good reasons that there is no such possibility?
|
Even if the question is not marked for C++11, for people who get here it should be mentioned that C++11 supports new contextual identifier final. See wiki page
|
1,001,067
| 1,001,117
|
STL string comparison functor
|
I have the following functor:
class ComparatorClass {
public:
bool operator () (SimulatedDiskFile * file_1, SimulatedDiskFile * file_2) {
string file_1_name = file_1->getFileName();
string file_2_name = file_2->getFileName();
cout << file_1_name << " and " << file_2_name << ": ";
if (file_1_name < file_2_name) {
cout << "true" << endl;
return true;
}
else {
cout << "false" << endl;
return false;
}
}
};
It is supposed to be a strict weak ordering, and it's this long (could be one line only) for debug purposes.
I'm using this functor as a comparator functor for a stl::set. Problem being, it only inserts the first element. By adding console output to the comparator function, I learned that it's actually comparing the file name to itself every time.
Other relevant lines are:
typedef set<SimulatedDiskFile *, ComparatorClass> FileSet;
and
// (FileSet files_;) <- SimulatedDisk private class member
void SimulatedDisk::addFile(SimulatedDiskFile * file) {
files_.insert(file);
positions_calculated_ = false;
}
EDIT: the code that calls .addFile() is:
current_request = all_requests.begin();
while (current_request != all_requests.end()) {
SimulatedDiskFile temp_file(current_request->getFileName(), current_request->getResponseSize());
disk.addFile(&temp_file);
current_request++;
}
Where all_requests is a list, and class Request is such that:
class Request {
private:
string file_name_;
int response_code_;
int response_size_;
public:
void setFileName(string file_name);
string getFileName();
void setResponseCode(int response_code);
int getResponseCode();
void setResponseSize(int response_size);
int getResponseSize();
};
I wish I could offer my hypotesis as to what's going on, but I actually have no idea. Thanks in advance for any pointers.
|
There's nothing wrong with the code you've posted, functionally speaking. Here's a complete test program - I've only filled in the blanks, not changing your code at all.
#include <iostream>
#include <string>
#include <set>
using namespace std;
class SimulatedDiskFile
{
public:
string getFileName() { return name; }
SimulatedDiskFile(const string &n)
: name(n) { }
string name;
};
class ComparatorClass {
public:
bool operator () (SimulatedDiskFile * file_1, SimulatedDiskFile * file_2) {
string file_1_name = file_1->getFileName();
string file_2_name = file_2->getFileName();
cout << file_1_name << " and " << file_2_name << ": ";
if (file_1_name < file_2_name) {
cout << "true" << endl;
return true;
}
else {
cout << "false" << endl;
return false;
}
}
};
typedef set<SimulatedDiskFile *, ComparatorClass> FileSet;
int main()
{
FileSet files;
files.insert(new SimulatedDiskFile("a"));
files.insert(new SimulatedDiskFile("z"));
files.insert(new SimulatedDiskFile("m"));
FileSet::iterator f;
for (f = files.begin(); f != files.end(); f++)
cout << (*f)->name << std::endl;
return 0;
}
I get this output:
z and a: false
a and z: true
z and a: false
m and a: false
m and z: true
z and m: false
a and m: true
m and a: false
a
m
z
Note that the set ends up with all three things stored in it, and your comparison logging shows sensible behaviour.
Edit:
Your bug is in these line:
SimulatedDiskFile temp_file(current_request->getFileName(), current_request->getResponseSize());
disk.addFile(&temp_file);
You're taking the address of a local object. Each time around the loop that object is destroyed and the next object is allocated into exactly the same space. So only the final object still exists at the end of the loop and you've added multiple pointers to that same object. Outside the loop, all bets are off because now none of the objects exist.
Either allocate each SimulatedDiskFile with new (like in my test, but then you'll have to figure out when to delete them), or else don't use pointers at all (far easier if it fits the constraints of your problem).
|
1,001,154
| 1,001,186
|
Using a namespace twice
|
In c++ Is it OK to include same namespace twice?
compiler wont give any error but still will it affect in anyway
Thanks,
EDIT:
I meant
using namespace std;
// . . STUFF
using namespace std;
|
It depends what you mean by 'include'. Saying:
using namespace std;
...
using namespace std:
is OK. But saying:
namespace X {
...
namespace X {
would create a nested namespace called X::X, which is probably not what you wanted.
|
1,001,375
| 1,001,413
|
C++ - Undefined reference to a class recently created !
|
I just created this new class :
//------------------------------------------------------------------------------
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
//------------------------------------------------------------------------------
#include <vector>
#include <GL/GLFW.h>
//------------------------------------------------------------------------------
template<class T>
class MultithreadedVector {
public:
MultithreadedVector();
void push_back(T data);
void erase(typename std::vector<T>::iterator it);
std::vector<T> get_container();
private:
std::vector<T> container_;
GLFWmutex th_mutex_;
};
//------------------------------------------------------------------------------
#endif // MULTITHREADEDVECTOR_H_INCLUDED
//------------------------------------------------------------------------------
The definition of the class :
//------------------------------------------------------------------------------
#include "MultithreadedVector.h"
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
template<class T>
MultithreadedVector<T>::MultithreadedVector() {
th_mutex_ = glfwCreateMutex();
}
template<class T>
void MultithreadedVector<T>::push_back(T data) {
glfwLockMutex(th_mutex_);
container_.push_back(data);
glfwUnlockMutex(th_mutex_);
}
template<class T>
void MultithreadedVector<T>::erase(typename vector<T>::iterator it) {
glfwLockMutex(th_mutex_);
container_.erase(it);
glfwUnlockMutex(th_mutex_);
}
template<class T>
vector<T> MultithreadedVector<T>::get_container() {
return container_;
}
Now the problem is that when i try to use it in my code as a static member of another class :
// VehicleManager.h
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
#include "MultithreadedVector.h"
#include "Vehicle.h"
class Foo {
public:
// stuffs
private:
static MultithreadedVector<Vehicle> vehicles_;
...
}
#endif
Then inside : VehicleManager.cpp
#include "VehicleManager.h"
MultithreadedVector<Vehicle> VehicleManager::vehicles_;
void VehicleManager::Method() {
Vehicle vehicle;
VehicleManager::vehicles_.push_back(vehicle);
}
But it doesn't compile :(, i get this error msg everytime :
C:\***\VehicleManager.cpp|188|undefined reference to `MultithreadedVector<Vehicle>::push_back(Vehicle)'|
I really don't understand why, especially that i have defined the static class member at the global scope of VehicleManager.cpp.
PS: I'm using Code::Blocks.
Thanks !
|
That's what will happen when blindly moving a class template implementation to a cpp file.
To make that work, you must know exactly for what types of T you will instantiate the class template and specify them in the cpp file.
In this case, put this in the cpp file:
template class MultithreadedVector<Vehicle>;
Note that the cpp file must know about Vehicle then.
|
1,001,420
| 1,001,428
|
How to define a function with same name which is present in different file
|
I want to define a class like this
class HttpRestAccessor
{
public:
IResource& UpdateResource(string& , IResource& );
};
and implementing in cpp file
IResource& HttpRestAccessor::UpdateResource(string& resourceUri, IResource& resource)
this cpp file refers to Winbase.h which has defined UpdateResource as follows
#define UpdateResource UpdateResourceW
And hence while compiling i get following error
error C2039: 'UpdateResourceW' : is not a member of 'RestToolkit::HttpRestAccessor'
this problem would be solved if rename function name to something different.
but I would love to keep my function name as UpdateResource.
Thanks In Advance,
Uday
|
Macro's totally ignore scope.
Basically the pre-precessor will do a find/replace of UpdateResource with UpdateResourceW so you're all out of luck.
renaming the method is your only option
|
1,001,522
| 1,001,682
|
Pointers in C# and how frequently it is used in the application?
|
For me , the Pointer was one of the hardest concept in programming languages in C++. When I was learning C++, I spent tremendous amount of time learning it. However, Now I primarily work in projects that are entirely written in languages like C#, and VB.NET etc. As a matter fact, I have NOT touched C++ for almost 4 years. Even though, C# has pointer, but I have not encouter the situation where I must use pointer in C#. So my question is , what kinds of productivity can we obtain in C# by using pointer ? what are the situation where the uses of the pointer is must?
|
Personally, I've never had a need for using pointers in .NET, but if you're dealing with absolute performance critical code, you'd use pointers. If you look at the System.String class, you'll see that a lot of the methods that handle the string manipulation, use pointers. Also, when dealing with image processing, very often it's useful to use pointers. Now, one can definitely argue whether those sort of applications should be written in .NET in the first place (I think they should), but at least if you need to squeeze out that extra bit of speed, you can.
|
1,001,535
| 1,001,576
|
Linking C++ code with 'gcc' (without g++)
|
Hi all: quick question: I'm in a situation where it would be useful to generate my C++ executable using only 'gcc' (without g++). Reason for this is that I have to submit the code to an automatic submission server which doesn't recognize the 'g++' (or 'c++', for that matter) command.
In my experiments, while I'm compiling gcc works well. Problem is, when I try to link the generated object files it gets messed up. Now, based on what I understood from the gcc man page (I may be way off, so tell me if I am), g++ is basically gcc, but it links the C++ library.
If this is true, how can I (if possible) explicitly link the C++ library without using the g++ (or c++) command?
EDIT: I'm adding the makefile to better illustrate the problem:
COMPILER = gcc
CFLAGS = -Wall -g -x c++
# MODULE COMPILATION
model: modules/model.h modules/sources/model.cpp
$(COMPILER) $(CFLAGS) -c modules/sources/model.cpp -o obj/model.o
algorithms: modules/algorithms.h modules/sources/algorithms.cpp
$(COMPILER) $(CFLAGS) -c modules/sources/algorithms.cpp -o obj/algorithms.o
io: modules/io.h modules/sources/io.cpp
$(COMPILER) $(CFLAGS) -c modules/sources/io.cpp -o obj/io.o
stopwatch: modules/stopwatch.h modules/sources/stopwatch.cpp
$(COMPILER) $(CFLAGS) -c modules/sources/stopwatch.cpp -o obj/stopwatch.o
# EXECUTABLE GENERATION
exe: model algorithms io stopwatch
$(COMPILER) $(CFLAGS) main.cpp obj/model.o obj/algorithms.o obj/io.o obj/stopwatch.o -o bin/process
# DEFAULT TEST CASE
run: exe
./bin/process -i data/nasa_small.log -a data/nasa_small.access -s data/nasa_small.stack
# CLEANING ROUTINE
clean:
rm -f obj/*
|
You can link the standard c++ library with the -l flag to gcc:
gcc cplusplus.o -lstdc++ -o myexe
|
1,001,544
| 1,001,645
|
Options for a message passing system for a game
|
I'm working on an RTS game in C++ targeted at handheld hardware (Pandora). For reference, the Pandora has a single ARM processor at ~600Mhz and runs Linux. We're trying to settle on a good message passing system (both internal and external), and this is new territory for me.
It may help to give an example of a message we'd like to pass. A unit may make this call to load its models into memory:
sendMessage("model-loader", "load-model", my_model.path, model_id );
In return, the unit could expect some kind of message containing a model object for the particular model_id, which can then be passed to the graphics system. Please note that this sendMessage function is in no way final. It just reflects my current understanding of message passing systems, which is probably not correct :)
From what I can tell there are two pretty distinct choices. One is to pass messages in memory, and only pass through the network when you need to talk to an external machine. I like this idea because the overhead seems low, but the big problem here is it seems like you need to make extensive use of mutex locking on your message queues. I'd really like to avoid excess locking if possible. I've read a few ways to implement simple queues without locking (by relying on atomic int operations) but these assume there is only one reader and one writer for a queue. This doesn't seem useful to our particular case, as an object's queue will have many writers and one reader.
The other choice is to go completely over the network layer. This has some fun advantages like getting asynchronous message passing pretty much for free. Also, we gain the ability to pass messages to other machines using the exact same calls as passing locally. However, this solution rubs me the wrong way, probably because I don't fully understand it :) Would we need a socket for every object that is going to be sending/receiving messages? If so, this seems excessive. A given game will have thousands of objects. For a somewhat underpowered device like the Pandora, I fear that abusing the network like that may end up being our bottleneck. But, I haven't run any tests yet, so this is just speculation.
MPI seems to be popular for message passing but it sure feels like overkill for what we want. This code is never going to touch a cluster or need to do heavy calculation.
Any insight into what options we have for accomplishing this is much appreciated.
|
The network will be using locking as well. It will just be where you cannot see it, in the OS kernel.
What I would do is create your own message queue object that you can rewrite as you need to. Start simple and make it better as needed. That way you can make it use any implementation you like behind the scenes without changing the rest of your code.
Look at several possible implementations that you might like to do in the future and design your API so that you can handle them all efficiently if you decide to implement in those terms.
If you want really efficient message passing look at some of the open source L4 microkernels. Those guys put a lot of time into fast message passing.
|
1,001,719
| 1,109,888
|
Detecting AC Power connection in WinPE?
|
I'm trying to determine if a laptop is connected to AC power.
The OS Im running under is WinPE.
My app is written in native C++.
WMI queries using Win32_Battery are not supported and the GetSystemPowerStatus API always returns '1' for ACLineStatus (running on AC power or not).
Any ideas?
Additonal investigation:
Just tried the API 'CallNtPowerInformation' with POWER_INFORMATION_LEVEL::SystemBatteryState. The SYSTEM_BATTERY_STATUS structure element AcOnLine also returns 1 regardless of power supply status. Probably just calls the same system level code but thought I'd add it in here.
|
I managed to answer my own question and it proved to be very simple in the end.
In WinPE the following noddy script returned null when executed because the battery wasn't being recognised:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Battery",,48)
For Each objItem in colItems
Wscript.Echo objItem.BatteryStatus
Wscript.Echo objItem.Caption
Next
I found a battery device driver in my PE image (\windows\inf\battery.inf) which once installed resulted in the battery being recognised and the above script returning the expected values. i.e. BatteryStatus = 2 (The system has access to AC so no battery is being discharged) or BatteryStatus = 1 (The battery is discharging i.e. AC not connected).
Driver can be installed in the PE image itself or loaded on demand. i.e. drvload
|
1,002,024
| 1,002,071
|
Sorting two linked lists according to memory location
|
I need to merge two doubly-linked lists, but not by their values (the lists are not sorted).
I want to obtain a single list that has all the nodes from the two, but in the order in which they appear in memory.
Maybe this image helps more:
http://img140.imageshack.us/i/drawing2.png/
Is there any algorithm (preferably a fast one) that can do this kind of merge ?
Maybe this is a bit helpful:
the start node of the lists is always before the other ones.
a list can have up to 8192 nodes.
I know where the nodes are located in memory because the lists keep track of free location in a big block of memory (used in a memory allocator).
I work in C++.
Thanks in advance!
|
Well it sounds like you aren't using std::list, so I'll go with the generic solution. Since your requirement is to merge the lists, but have the nodes be in order of there physical location in memory. You can likely just append the two lists, then sort the nodes by address of the nodes.
see: http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html for a sorting algorithm for linked lists.
When sorting, instead of comparing node1->value < node2->value just do (size_t)node1 < (size_t)node2, or something to that nature.
|
1,002,064
| 1,002,293
|
Screen capture from windows service
|
I've got DirectShow based screen capture software. Internally it calls CopyScreenToBitmap function to grab screen. Then the picture is compressed by ffdshow.
It works fine as a desktop application, but as window service, on certain computers it does not work (black picture). I've set 'Allow service to interact with desktop' and run that service on current user account.
Any ideas what could be wrong?
I test it on windows XP, but it is expected to work on Vista and 7 as well.
Yes it works as desktop application on all computers, but on some of them (on majority of them) it fails as a service.
|
Try this in addition to allowing access to the desktop:
Enumerate all Window Stations: EnumWindowStations
Find the window station for the logged on user, and make it your process' window station: SetProcessWindowStation - see example in this thread
Then set the desktop for your current thread to the default desktop of the window station also here
Then get the DC of the desktop using one of a few methods, including
CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL)
Good luck
|
1,002,164
| 1,571,635
|
Write applications in C or C++ for Android?
|
I'm trying to develop/port a game to Android, but it's in C, and Android supports Java, but I'm sure there must be a way to get a C app on there, anyone knows of a way to accomplish this?
|
For anyone coming to this via Google, note that starting from SDK 1.6 Android now has an official native SDK.
You can download the Android NDK (Native Development Kit) from here:
https://developer.android.com/ndk/downloads/index.html
Also there is an blog post about the NDK:
http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html
|
1,002,503
| 1,002,521
|
How is C++'s multiple inheritance implemented?
|
Single inheritance is easy to implement. For example, in C, the inheritance can be simulated as:
struct Base { int a; }
struct Descendant { Base parent; int b; }
But with multiple inheritance, the compiler has to arrange multiple parents inside newly constructed class. How is it done?
The problem I see arising is: should the parents be arranged in AB or BA, or maybe even other way? And then, if I do a cast:
SecondBase * base = (SecondBase *) &object_with_base1_and_base2_parents;
The compiler must consider whether to alter or not the original pointer. Similar tricky things are required with virtuals.
|
The following paper from the creator of C++ describes a possible implementation of multiple inheritance:
Multiple Inheritance for C++ - Bjarne Stroustrup
|
1,002,543
| 1,009,245
|
How can I capture output from the Windows cmd shell?
|
Is there any way with, say Perl or PHP, that I can grab output from another process that outputs to the Windows cmd shell? I have a game server that outputs certain information, for example say 'player finished track in 43s' and I want to grab that line and use Perl or PHP to send a request to a webserver to update ranks on a web page. Is there a way to grab that output pipe in Perl or PHP? Or could I achieve this using C++ Windows API maybe?
Let me clarify here: I want to execute a seperate Perl or PHP script that grabs output from the Windows cmd shell, and the output that is being displayed to the Windows cmd shell is coming from a different process.
|
You need to start your server within Perl:
my $server_out = `server.exe`; # Note the backticks.
Now $server_out contains the output of server.exe. But the trick here is that you have to wait until server.exe exits to get the out put.
Try IPC::Run (which is not a core module)
use English;
use IPC::Run;
my ($stdout, $stderr);
IPC::Run::run([$cmd, $arg1, $arg2, $argN], \undef, \$stdout, $stderr);
while(<$stdout>) {
print "Cmd said $_\n";
}
Note: Code not tested.
Found the info here.
|
1,002,587
| 1,002,746
|
Can I use the Curiously Recurring Template Pattern here (C++)?
|
I have a C++ application that can be simplified to something like this:
class AbstractWidget {
public:
virtual ~AbstractWidget() {}
virtual void foo() {}
virtual void bar() {}
// (other virtual methods)
};
class WidgetCollection {
private:
vector<AbstractWidget*> widgets;
public:
void addWidget(AbstractWidget* widget) {
widgets.push_back(widget);
}
void fooAll() {
for (unsigned int i = 0; i < widgets.size(); i++) {
widgets[i]->foo();
}
}
void barAll() {
for (unsigned int i = 0; i < widgets.size(); i++) {
widgets[i]->bar();
}
}
// (other *All() methods)
};
My application is performance-critical. There are typically thousands of widgets in the collection. The classes derived from AbstractWidget (of which there are dozens) typically leave many of the virtual functions not overridden. The ones that are overridden typically have very fast implementations.
Given this, I feel I can optimize my system with some clever meta-programming. The goal is to leverage function inlining and to avoid virtual function calls, while keeping the code managable. I've looked into the Curiously Recurring Template Pattern (see here for description). This seems to almost do what I want, but not quite.
Is there any way to make the CRTP work for me here? Or, is there any other clever solution anyone can think of?
|
CRTP or compile-time polymorphism is for when you know all of your types at compile time. As long as you're using addWidget to collect a list of widgets at runtime and as long as fooAll and barAll then have to handle members of that homogenous list of widgets at runtime, you have to be able to handle different types at runtime. So for the problem you've presented, I think you're stuck using runtime polymorphism.
A standard answer, of course, is to verify that the performance of runtime polymorphism is a problem before you try to avoid it...
If you really need to avoid runtime polymorpism, then one of the following solutions may work.
Option 1: Use a compile-time collection of widgets
If your WidgetCollection's members are known at compile time, then you can very easily use templates.
template<typename F>
void WidgetCollection(F functor)
{
functor(widgetA);
functor(widgetB);
functor(widgetC);
}
// Make Foo a functor that's specialized as needed, then...
void FooAll()
{
WidgetCollection(Foo);
}
Option 2: Replace runtime polymorphism with free functions
class AbstractWidget {
public:
virtual AbstractWidget() {}
// (other virtual methods)
};
class WidgetCollection {
private:
vector<AbstractWidget*> defaultFooableWidgets;
vector<AbstractWidget*> customFooableWidgets1;
vector<AbstractWidget*> customFooableWidgets2;
public:
void addWidget(AbstractWidget* widget) {
// decide which FooableWidgets list to push widget onto
}
void fooAll() {
for (unsigned int i = 0; i < defaultFooableWidgets.size(); i++) {
defaultFoo(defaultFooableWidgets[i]);
}
for (unsigned int i = 0; i < customFooableWidgets1.size(); i++) {
customFoo1(customFooableWidgets1[i]);
}
for (unsigned int i = 0; i < customFooableWidgets2.size(); i++) {
customFoo2(customFooableWidgets2[i]);
}
}
};
Ugly, and really not OO. Templates could help with this by reducing the need to list every special case; try something like the following (completely untested), but you're back to no inlining in this case.
class AbstractWidget {
public:
virtual AbstractWidget() {}
};
class WidgetCollection {
private:
map<void(AbstractWidget*), vector<AbstractWidget*> > fooWidgets;
public:
template<typename T>
void addWidget(T* widget) {
fooWidgets[TemplateSpecializationFunctionGivingWhichFooToUse<widget>()].push_back(widget);
}
void fooAll() {
for (map<void(AbstractWidget*), vector<AbstractWidget*> >::const_iterator i = fooWidgets.begin(); i != fooWidgets.end(); i++) {
for (unsigned int j = 0; j < i->second.size(); j++) {
(*i->first)(i->second[j]);
}
}
}
};
Option 3: Eliminate OO
OO is useful because it helps manage complexity and because it helps maintain stability in the face of change. For the circumstances you seem to be describing - thousands of widgets, whose behavior generally doesn't change, and whose member methods are very simple - you may not have much complexity or change to manage. If that's the case, then you may not need OO.
This solution is the same as runtime polymorphism, except that it requires that you maintain a static list of "virtual" methods and known subclasses (which is not OO) and it lets you replace virtual function calls with a jump table to inlined functions.
class AbstractWidget {
public:
enum WidgetType { CONCRETE_1, CONCRETE_2 };
WidgetType type;
};
class WidgetCollection {
private:
vector<AbstractWidget*> mWidgets;
public:
void addWidget(AbstractWidget* widget) {
widgets.push_back(widget);
}
void fooAll() {
for (unsigned int i = 0; i < widgets.size(); i++) {
switch(widgets[i]->type) {
// insert handling (such as calls to inline free functions) here
}
}
}
};
|
1,002,998
| 1,003,006
|
What Windows C++ IDEs support the new C++0X standard?
|
What are excellent C++ IDE options that support the new standard c++0x (windows os friendly) besides visual .net 2010 (the beta is way too slow/clunky)?
|
While not supporting the full C++0x standard, much of the TR1 stuff is included in the SP1 update to Visual Studio 2008. The SP1 update includes the feature pack that was released last year.
|
1,003,190
| 1,003,243
|
Not locking mutex for pthread_cond_timedwait and pthread_cond_signal ( on Linux )
|
Is there any downside to calling pthread_cond_timedwait without taking a lock on the associated mutex first, and also not taking a mutex lock when calling pthread_cond_signal ?
In my case there is really no condition to check, I want a behavior very similar to Java wait(long) and notify().
According to the documentation, there can be "unpredictable scheduling behavior". I am not sure what that means.
An example program seems to work fine without locking the mutexes first.
|
The first is not OK:
The pthread_cond_timedwait() and
pthread_cond_wait() functions shall
block on a condition variable. They
shall be called with mutex locked by
the calling thread or undefined
behavior results.
http://opengroup.org/onlinepubs/009695399/functions/pthread_cond_timedwait.html
The reason is that the implementation may want to rely on the mutex being locked in order to safely add you to a waiter list. And it may want to release the mutex without first checking it is held.
The second is disturbing:
if predictable scheduling behaviour is
required, then that mutex is locked by
the thread calling
pthread_cond_signal() or
pthread_cond_broadcast().
http://www.opengroup.org/onlinepubs/007908775/xsh/pthread_cond_signal.html
Off the top of my head, I'm not sure what the specific race condition is that messes up scheduler behaviour if you signal without taking the lock. So I don't know how bad the undefined scheduler behaviour can get: for instance maybe with broadcast the waiters just don't get the lock in priority order (or however your particular scheduler normally behaves). Or maybe waiters can get "lost".
Generally, though, with a condition variable you want to set the condition (at least a flag) and signal, rather than just signal, and for this you need to take the mutex. The reason is that otherwise, if you're concurrent with another thread calling wait(), then you get completely different behaviour according to whether wait() or signal() wins: if the signal() sneaks in first, then you'll wait for the full timeout even though the signal you care about has already happened. That's rarely what users of condition variables want, but may be fine for you. Perhaps this is what the docs mean by "unpredictable scheduler behaviour" - suddenly the timeslice becomes critical to the behaviour of your program.
Btw, in Java you have to have the lock in order to notify() or notifyAll():
This method should only be called by a
thread that is the owner of this
object's monitor.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#notify()
The Java synchronized {/}/wait/notifty/notifyAll behaviour is analogous to pthread_mutex_lock/pthread_mutex_unlock/pthread_cond_wait/pthread_cond_signal/pthread_cond_broadcast, and not by coincidence.
|
1,003,309
| 1,003,671
|
What exactly does C++ profiling (google cpu perf tools) measure?
|
I trying to get started with Google Perf Tools to profile some CPU intensive applications. It's a statistical calculation that dumps each step to a file using `ofstream'. I'm not a C++ expert so I'm having troubling finding the bottleneck. My first pass gives results:
Total: 857 samples
357 41.7% 41.7% 357 41.7% _write$UNIX2003
134 15.6% 57.3% 134 15.6% _exp$fenv_access_off
109 12.7% 70.0% 276 32.2% scythe::dnorm
103 12.0% 82.0% 103 12.0% _log$fenv_access_off
58 6.8% 88.8% 58 6.8% scythe::const_matrix_forward_iterator::operator*
37 4.3% 93.1% 37 4.3% scythe::matrix_forward_iterator::operator*
15 1.8% 94.9% 47 5.5% std::transform
13 1.5% 96.4% 486 56.7% SliceStep::DoStep
10 1.2% 97.5% 10 1.2% 0x0002726c
5 0.6% 98.1% 5 0.6% 0x000271c7
5 0.6% 98.7% 5 0.6% _write$NOCANCEL$UNIX2003
This is surprising, since all the real calculation occurs in SliceStep::DoStep. The "_write$UNIX2003" (where can I find out what this is?) appears to be coming from writing the output file. Now, what confuses me is that if I comment out all the outfile << "text" statements and run pprof, 95% is in SliceStep::DoStep and `_write$UNIX2003' goes away. However my application does not speed up, as measured by total time. The whole thing speeds up less than 1 percent.
What am I missing?
Added:
The pprof output without the outfile << statements is:
Total: 790 samples
205 25.9% 25.9% 205 25.9% _exp$fenv_access_off
170 21.5% 47.5% 170 21.5% _log$fenv_access_off
162 20.5% 68.0% 437 55.3% scythe::dnorm
83 10.5% 78.5% 83 10.5% scythe::const_matrix_forward_iterator::operator*
70 8.9% 87.3% 70 8.9% scythe::matrix_forward_iterator::operator*
28 3.5% 90.9% 78 9.9% std::transform
26 3.3% 94.2% 26 3.3% 0x00027262
12 1.5% 95.7% 12 1.5% _write$NOCANCEL$UNIX2003
11 1.4% 97.1% 764 96.7% SliceStep::DoStep
9 1.1% 98.2% 9 1.1% 0x00027253
6 0.8% 99.0% 6 0.8% 0x000274a6
This looks like what I'd expect, except I see no visible increase in performance (.1 second on a 10 second calculation). The code is essentially:
ofstream outfile("out.txt");
for loop:
SliceStep::DoStep()
outfile << 'result'
outfile.close()
Update: I timing using boost::timer, starting where the profiler starts and ending where it ends. I do not use threads or anything fancy.
|
From my comments:
The numbers you get from your profiler say, that the program should be around 40% faster without the print statements.
The runtime, however, stays nearly the same.
Obviously one of the measurements must be wrong. That means you have to do more and better measurements.
First I suggest starting with another easy tool: the time command. This should get you a rough idea where your time is spend.
If the results are still not conclusive you need a better testcase:
Use a larger problem
Do a warmup before measuring. Do some loops and start any measurement afterwards (in the same process).
Tiristan: It's all in user. What I'm doing is pretty simple, I think... Does the fact that the file is open the whole time mean anything?
That means the profiler is wrong.
Printing 100000 lines to the console using python results in something like:
for i in xrange(100000):
print i
To console:
time python print.py
[...]
real 0m2.370s
user 0m0.156s
sys 0m0.232s
Versus:
time python test.py > /dev/null
real 0m0.133s
user 0m0.116s
sys 0m0.008s
My point is:
Your internal measurements and time show you do not gain anything from disabling output. Google Perf Tools says you should. Who's wrong?
|
1,003,360
| 1,033,337
|
Complete C++ i18n gettext() "hello world" example
|
I am looking for a complete i18n gettext() hello world example. I have started a script based upon A tutorial on Native Language Support using GNU gettext by G. Mohanty. I am using Linux and G++.
Code:
cat >hellogt.cxx <<EOF
// hellogt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
#include <cstdlib>
int main (){
char* cwd = getenv("PWD");
std::cout << "getenv(PWD): " << (cwd?cwd:"NULL") << std::endl;
char* l = getenv("LANG");
std::cout << "getenv(LANG): " << (l?l:"NULL") << std::endl;
char* s = setlocale(LC_ALL, "");
std::cout << "setlocale(): " << (s?s:"NULL") << std::endl;
std::cout << "bindtextdomain(): " << bindtextdomain("hellogt", cwd) << std::endl;
std::cout << "textdomain(): " << textdomain( "hellogt") << std::endl;
std::cout << gettext("hello, world!") << std::endl;
}
EOF
g++ -ohellogt hellogt.cxx
xgettext -d hellogt -o hellogt.pot hellogt.cxx
msginit --no-translator -l es_MX -o hellogt_spanish.po -i hellogt.pot
sed --in-place hellogt_spanish.po --expression='/#: /,$ s/""/"hola mundo"/'
sed --in-place hellogt_spanish.po --expression='s/PACKAGE VERSION/hellogt 1.0/'
mkdir -p ./es_MX/LC_MESSAGES
msgfmt -c -v -o ./es_MX/LC_MESSAGES/hellogt.mo hellogt_spanish.po
export LANG=es_MX
ls -l $PWD/es_MX/LC_MESSAGES/hellogt.mo
./hellogt
strace -e trace=open ./hellogt
The program compiles, the text is extracted, Spanish file is created, modified and binary created but hellogt still displays English. The trace shows no evidence of looking in the current working directory for es_MX nor any references to LC_MESSAGES directory.
|
cat >hellogt.cxx <<EOF
// hellogt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
int main (){
setlocale(LC_ALL, "");
bindtextdomain("hellogt", ".");
textdomain( "hellogt");
std::cout << gettext("hello, world!") << std::endl;
}
EOF
g++ -o hellogt hellogt.cxx
xgettext --package-name hellogt --package-version 1.2 --default-domain hellogt --output hellogt.pot hellogt.cxx
msginit --no-translator --locale es_MX --output-file hellogt_spanish.po --input hellogt.pot
sed --in-place hellogt_spanish.po --expression='/"hello, world!"/,/#: / s/""/"hola mundo"/'
mkdir --parents ./es_MX.utf8/LC_MESSAGES
msgfmt --check --verbose --output-file ./es_MX.utf8/LC_MESSAGES/hellogt.mo hellogt_spanish.po
LANGUAGE=es_MX.utf8 ./hellogt
Here is a description of the files created by the above:
hellogt.cxx C++ source file
hellogt Executable image
hellogt.pot Extracted text from C++ source file (portable object template)
hellogt_spanish.po Modified text for Spanish with translations added (using sed)
es_MX.utf8/
LC_MESSAGES/
hellogt.mo Binary translated text for Spanish used at run-time
|
1,003,497
| 1,003,579
|
How to remove black background from textures in OpenGL
|
I'm looking for a way to remove the background of a 24bit bitmap, while keeping the main image totally opaque, up until now blending has served the purpose but now I need to keep the main bit opaque. I've searched on Google but found nothing helpful, I think I'm probably searching for the wrong terms though, so any help would be greatly appreciated.
Edit:
Yes sorry, I'm using black right now as the background.
|
When you are creating the texture for OpenGL, you'll want to create the texture as a 32-bit RGBA texture. Create a buffer to hold the contents of this new 32-bit texture and iterate through your 24-bit bitmap. Every time you come across your background color, set the alpha to zero in your new 32-bit bitmap.
struct Color32;
struct Color24;
void Load24BitTexture(Color24* ipTex24, int width, int height)
{
Color32* lpTex32 = new Color32[width*height];
for(x = 0; x < width; x++)
{
for(y = 0; y < height; y++)
{
int index = y*width+x;
lpTex32[index].r = ipTex24[index].r;
lpTex32[index].g = ipTex24[index].g;
lpTex32[index].b = ipTex24[index].b;
if( ipTex24[index] == BackgroundColor)
lpTex32[index].a = 0;
else
lpTex32[index].a = 255;
}
}
glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, lpTex32);
delete [] lpTex32;
}
|
1,003,905
| 1,005,445
|
"Smart" Linked Scrollbar and Edit Controls?
|
I hope that I can explain my problem well enough for someone to help.
Basically, I have a horizontal scrollbar (ranged 0 to 1000) and an edit control that represents the position of the scrollbar divided by 1000, so that the user can use either the scrollbar to select a range of numbers between 0 and 1 up to a 3 decimal precision (.001, .002, ..., .987, etc.), or enter their own number in the edit box. As they scroll the scrollbar, the number in the edit control changes to reflect the new scroll position. When a new number is entered, the scrollbar sets itself to a new position reflecting the number entered. Meanwhile I also perform some calculations with this number as it changes (through either the scrollbar or the edit control) and display the results in another dialog.
Here is my problem: I'm having trouble deciding which event handlers to use to produce the proper behavior when a user enters a number into the edit control.
I'm using a double value variable called fuelMargin to handle my edit control and a CScrollBar control variable called fuelScroll to handle the scrollbar.
In my HSCROLL event I set the edit control to the scroll position / 1000. No problems there; when the user scrolls the scrollbar the edit box is correctly updated.
As for the edit box, my first attempt was an ONCHANGE event:
void MarginDlg::OnEnChangeFueledit()
{
CEdit* editBox;
editBox = (CEdit*)GetDlgItem(IDC_FUELEDIT);
CString editString;
editBox->GetWindowText(editString);
if (editString.Compare(".") != 0 && editString.Compare("0.") != 0
&& editString.Compare(".0") != 0 && editString.Compare("0.0") != 0
&& editString.Compare(".00") != 0 && editString.Compare("0.00") != 0)
{
UpdateData();
UpdateData(FALSE);
if (fuelMargin > 1)
{
UpdateData();
fuelMargin = 1;
UpdateData(FALSE);
}
if (fuelMargin < 0)
{
UpdateData();
fuelMargin = 0;
UpdateData(FALSE);
}
fuelScroll.SetScrollPos(int(fuelMargin*1000));
}
}
I needed that first if statement in there to keep from doing an UpdateData() when the user is trying to type a number like .5 or .05 or .005. It does produce a few wonky behaviors, though; when the user tries to type something like .56, after the .5 an UpdateData() is performed, the number becomes 0.5, and the cursor is moved to the far left, so if they tried to type .56 they would accidentally end up typing 60.5 -- which goes to 1, since I won't let them enter numbers lower than 0 or higher than 1. If they enter 0.56, however, this behavior is avoided.
For my second attempt, I commented out my ONCHANGE event and put in an ONKILLFOCUS event instead:
void MarginDlg::OnEnKillfocusFueledit()
{
UpdateData();
UpdateData(FALSE);
if (fuelMargin > 1)
{
UpdateData();
fuelMargin = 1;
UpdateData(FALSE);
}
if (fuelMargin < 0)
{
UpdateData();
fuelMargin = 0;
UpdateData(FALSE);
}
fuelScroll.SetScrollPos(int(fuelMargin*1000));
}
So now the user can finish typing their number and all is hunky dory--as long as they click out of the edit box. The scrollbar won't move and results won't be calculated until the box loses focus.
I want the results to be calculated as the numbers in the box are being typed; I want the scrollbar to move as the numbers are being typed. But I don't want typing to be disrupted, i.e. the actual numbers in the box changed or the cursor moved in any way.
Suggestions?
Thanks!
|
With the first approach, it looks like you're almost there: the only really significant problem is that the repeated calls to UpdateData() mess with the cursor position as the user is typing.
Given that you're trying to have a reasonably complex interaction between the controls, what I'd suggest is not to do validation in the OnChange() at all, so that as the user is typing he can type what he wants (which is how most numeric edit controls work anyway). When the user closes the dialog the controls are on (or clicks a button that uses the data in some way) then validation should be triggered, and a suitable error shown.
Once you're free from validating in OnChange(), you can fix the "cursor moves" problem by simply not calling UpdateData() in OnChange(). Instead, just parse the number from "editString" and, if it's in the valid range, update the scrollbar. That way, the scrollbar updates as the user types, and if they type in an invalid value the scrollbar stays put, and they'll get an error when they move to whatever the next stage is. Something like this (not tested):
void MarginDlg::OnEnChangeFueledit()
{
CString editString;
GetDlgItem(IDC_FUELEDIT)->GetWindowText(editString);
double editValue;
if ((sscanf(editString,"%lf",&editValue) == 1)
{
if (editValue >= 0.0) && (editValue <= 1.0))
fuelScroll.SetScrollPos(int(editValue*1000));
}
}
The only remaining important problem to note is that, if the user types some invalid value, or a number out of the valid range, then the edit control and the scrollbar will be out of sync. The simplest way to deal with that is to just decide that the edit control is the "master" value: that is, when we want to know what the user entered, we always look at the edit control, not the scrollbar, and validate data.
As for your second approach, one possible solution might be to implement a timer message handler: in the timer handler you could say the equivalent of "if the user hasn't typed anything for a second, I'll assume they're done, and parse the number and update the scrollbar". I'm not so keen on that as a solution, though.
|
1,003,956
| 1,100,876
|
Browser Helper Object UI
|
I am a newbie working towards developing an IE extension that would appear as an overlay in certain webpages. I am getting started by creating a simple BHO in VS2008 (using C++), but I am wondering how UI may be incorporated within the project. Any ideas?
Just to give you an idea, I'm looking for overlays similar to what was developed by stickis
http://www.stickis.com/faq/
Thanks
|
Using CreateWIndowEx() was what I was looking for :)
|
1,003,987
| 1,004,063
|
Borland c++ version 0.7 is it still available?
|
My cousin is actually asking me if it's still available but I can't find that version, since it's too old, he's complaining about version 5.5 saying that it doesn't recognize his libraries. Is there any link? I doubt but I thought I'll give it a shot. 0.7 is way too old I know
|
The tools division of Borland was spun out into a separate division called CodeGear. CodeGear was subsequently bought by Embarcadero. On their website they have a Antique Software downloads section. I don't know what you mean by 0.7 as that does not appear to be a valid version, did you mean 7.0? Anyhow if its not at this site you are probably out of luck, though it might be worth emailing David Intersimone the chief evangelist. He might be able to help you, he is a great guy and very approachable.
His email address is his first name, + first initial of his second name "at" embarcadero dot com.
|
1,004,676
| 1,004,684
|
How to terminate a hanging thread inside a dll correctly?
|
Hi Everybody,
I have a third party library that contains an error. When I call a function it may hang. The library function is called inside a dll. I decided to move the call into the thread and wait for some time. If thread is finished then OK. If not – I should terminate it compulsory.
The simplified example here:
unsigned Counter = 0;
void f()
{
HANDLE hThread;
unsigned threadID;
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, DoSomething, NULL, 0, &threadID );
if (WAIT_TIMEOUT == WaitForSingleObject( hThread, 5000 ))
{
TerminateThread(hThread, 1);
wcout << L"Process is Timed Out";
}
else
{
wcout << L"Process is Ended OK";
}
CloseHandle(hThread);
wcout << Counter;
}
unsigned int _stdcall DoSomething( void * /*dummy*/ )
{
while (1)
{
++Counter;
}
_endthreadex( 0 );
return 0;
}
The Question
The TerminateThread() function is not recommended to call.
As I mentioned before, the thread is running inside a dll. If I terminate the thread using TerminateThread() my dll would not unload using FreeLibrary() or even FreeLibraryAndExitThread(). Both functions hangs.
How to Terminate the thread and keep FreeLibrary() working?
Thanks.
|
Unfortunately, you can't arbitrarily terminate a thread safely.
TerminateThread causes the thread to terminate immediately, even if the thread is holding locks or modifying some internal state. TerminateThread can cause random hangs in your application (if the thread was holding a lock) or a crash (if the thread were modifying some state and it is left inconsistent)
If you cannot trust the DLL to behave correctly and this is causing significant reliability issues for you, you should move the code invoking the DLL into a separate process - terminating a process is much safer.
|
1,004,701
| 1,005,591
|
Model - View - Controller in Qt
|
I understand more or less how does MPV works.
But I don't get what classes:
QAbstractItemModel
QAbstractItemView
QAbstractItemDelegate / QItemDelegate
Can do for me?
If that is relevant, I'm using
QGraphicsScene / QGraphicsView with some elements (visual representation of game board) that user can interact with while the interaction logic (game rules) are encapsulated in other class.
|
AbstractItemModel QAbstractItemView QAbstractItemDelegate
Are from the "Mode/View framework"
This is a very powerful framework for the data part of your application, here is a presentation of the framework.
QAbstractItemModel
Is the base class for the model of the MVC. Has a global interface for accessing and altering the data and takes care of the Observable part.
QAbstractItemView
Is the base class for the view of the MVC. Has aglobal interface for the view/selections part and it takes care of the Observer part. You don't have to worry about the observer pattern, the framework does it for you.
QAbstractItemDelegate
Is the base class for the controller of the MVC.
Is the Strategy pattern for painting, editing the elements, ...
QGraphicsScene / QGraphicsView
Are from the "The Graphics View Framework" and is independent of the Model/View framework.
This is also a very powerful framework for the graphics part.
The Scene
QGraphicsScene provides the Graphics
View scene. The scene has the
following responsibilities:
Providing a fast interface for
managing a large number of items
Propagating events to each item
Managing item state, such as selection
and focus handling Providing
untransformed rendering functionality;
mainly for printing
The View
QGraphicsView provides the view
widget, which visualizes the contents
of a scene. You can attach several
views to the same scene, to provide
several viewports into the same data
set
If you want a Model to be visible in a QGraphicsView than you will have to write your own view based on the QAbstractItemView.
Take a QGraphicsView as view port widget QAbstractScrollArea::setViewport(QWidget * widget)) and then you can
add QAbstractItemView::rowsInserted,
remove QAbstractItemView::rowsAboutToBeRemoved
and change QAbstractItemView::dataChanged
the items in the scene. Don't forget to take care of the reset an layout change events.
|
1,004,807
| 1,004,820
|
Relationship between MSVC++ rand() and C# System.Random
|
How can I make it so the same sequence of random numbers come out of an MSVC++ program and a C# .NET program?
Is it possible? Is there any relationship between MSVC++ rand() and System.Random?
Given the example below it seems they are totally different.
#include <iostream>
using namespace std;
int main()
{
srand( 1 ) ;
cout << rand() << endl <<
rand() << endl <<
rand() << endl ;
}
using System;
class Program
{
static void Main( string[] args )
{
Random random = new Random( 1 );
Console.WriteLine( random.Next() );
Console.WriteLine( random.Next() );
Console.WriteLine( random.Next() );
}
}
|
It is possible (not exactlly easy) to use .NET mangaged libraries in unmanaged C++. You might want to take a look at the MSDN documentation.
|
1,004,961
| 1,004,975
|
Bug on a custom C++ class
|
I need help on finding the problem using a custom c++ class to manage 3D positions. Here is the relevant code from the class
Punto operator+(Punto p){
return Punto(this->x + p.x, this->y + p.y, this->z + p.z);
}
Punto operator+(Punto *p){
return Punto(this->x + p->x, this->y + p->y, this->z + p->z);
}
Punto operator-(Punto p){
return Punto(this->x - p.x, this->y - p.y, this->z - p.z);
}
Punto operator-(Punto *p){
return Punto(this->x - p->x, this->y - p->y, this->z - p->z);
}
Punto *operator=(Punto p){
this->x = p.x;
this->y = p.y;
this->z = p.z;
return this;
}
Punto *operator=(Punto *p){
this->x = p->x;
this->y = p->y;
this->z = p->z;
return this;
}
I'm using it here like this:
p = fem->elementoFrontera[i]->nodo[0] - fem->elementoFrontera[i]->nodo[1];
Where nodo[i] is a Punto*, and it compiles fine, but when I try to do:
p = fem->elementoFrontera[i]->nodo[0] + fem->elementoFrontera[i]->nodo[1];
The compiler says:
In member function void
mdTOT::pintarElementosFrontera()':
error: invalid operands of types
Punto*' and Punto*' to binary
operator+'
|
The first one compiles fine because you can subtract pointers in C/C++, but not add pointers. But in any case it doesn't do what you need - it doesn't use your overloaded operator. Since your operators are defined in a class, you need to operate on class instances, not on pointers. So, change to something like
Punto p = *(fem->elementoFrontera[i]->nodo[0]) + *(fem->elementoFrontera[i]->nodo[1]);
Another thing - you should use class references, not values, in operator definition. E.g.
Punto& operator+(const Punto& p) {
EDIT. To simplify the code, you can create an accessor function, like this:
const Punto& NodoRef(int i, int j) {
return *(fem->elementoFronteria[i]->Nodo[j]);
}
and then your code becomes as clean as
p = NodoRef(i,0) + NodoRef(i,1);
The NodoRef may be defined in your fem class, or outside. Just make sure the object fem is alive in the scope where you use the NodoRef.
|
1,005,072
| 1,005,772
|
Exceptions on Linux from a shared object (.so)
|
I have a test program called ftest. It loads .so files that contain tests and runs the tests that it finds in there. One of these tests loads and runs a .so that contains a Postgres database driver for our O/RM.
When the Postgres driver throws an exception which is defined in that .so file (or one that it links to, but ftest does not link to) and is caught by the test framework the exception destructor triggers a segfault.
This segfault happens whenever the compiled exception is in a .so that has been dynamically loaded (using dload).
This sort of thing works fine in Windows which has the same architecture. We don't really want to restrict ourselves to only use exceptions that are from the core libraries -- add-ins should be free to create their own exception classes and have them handled normally.
The exceptions are sub-classes of std::exception. Sometimes the exceptions may be defined in libraries (such as libpqxx) which means that exceptions are sometimes out of our control too.
Exceptions are thrown using something like:
throw exception_class( exception_arguments );
And are caught using:
catch ( std::exception &e ) {
// handler code
}
Is there some special compiler option needed to get this working? Do we need to switch to throw exceptions via throw new exception_class( args ) (we don't really want to do this)?
|
Assuming your using gcc -
Append -Wl,-E when you build the executable calling dlload(). This exports all type info symbols from the executable, which should allow the RTTI (when catching the exception) to work properly.
VC++ uses string compares to match typeinfo, results in slower dynamic_cast<> etc but smaller binaries. g++ uses pointer compares.
I encountered the same problem when attempting to use pure virtual interfaces classes implemented in a run-time loaded .so.
There are a few articles relating to the subject floating around on the net as well.
hope that helps,
Hayman.
|
1,005,318
| 1,005,372
|
Migrating Borland C++ to C#
|
I have to execute project where I need to migrate Borland C++ code to C#,
what are the important steps I need to follow for smooth migration of code?
and please suggest any kind of Tips and Tricks?
|
That actually means a complete re-write. If I were you, I'd try C++/CLI instead of C#. This way, you can acutally gradually rewrite your code and transform it to managed code.
Things to consider, wether you migrate to C# or C++/CLI:
Partition your software in modules with clean interfaces (using n-tier architectures, MVC, ...). If each partition is a COM-object, you can even try to migrate only parts and use the COM objects in .NET.
Identify the libraries you depend on and check how you can replace them in .NET
Determine where you use pointers and check how you can transform this code in C++
Check where you use RAII-objects and find a way to get the same result in .NET.
I can't give you more detailed advice as I don't know what type of program you want to migrate and for what reason.
|
1,005,476
| 1,007,175
|
How to detect whether there is a specific member variable in class?
|
For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code:
template<int> struct TT {typedef int type;};
template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; }
struct P1 {int x; };
struct P2 {float X; };
// it also could be struct P3 {unknown_type X; };
int main()
{
P1 p1 = {1};
P2 p2 = {1};
Check_x(p1); // must return true
Check_x(p2); // must return false
return 0;
}
But it does not compile in Visual Studio, while compiling in the GNU C++. With Visual Studio I could use the following template:
template<class P> bool Check_x(P p, typename TT<&P::x==&P::x>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<&P::X==&P::X>::type b = 0) { return false; }
But it does not compile in GNU C++. Is there universal solution?
UPD: Structures P1 and P2 here are only for example. There are could be any classes with unknown members.
P.S. Please, do not post C++11 solutions here because they are obvious and not relevant to the question.
|
Another way is this one, which relies on SFINAE for expressions too. If the name lookup results in ambiguity, the compiler will reject the template
template<typename T> struct HasX {
struct Fallback { int x; }; // introduce member name "x"
struct Derived : T, Fallback { };
template<typename C, C> struct ChT;
template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];
template<typename C> static char (&f(...))[2];
static bool const value = sizeof(f<Derived>(0)) == 2;
};
struct A { int x; };
struct B { int X; };
int main() {
std::cout << HasX<A>::value << std::endl; // 1
std::cout << HasX<B>::value << std::endl; // 0
}
It's based on a brilliant idea of someone on usenet.
Note: HasX checks for any data or function member called x, with arbitrary type. The sole purpose of introducing the member name is to have a possible ambiguity for member-name lookup - the type of the member isn't important.
|
1,005,685
| 1,005,709
|
C++ static initialization order
|
When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.
Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.
Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.
One possibility is the trick with the static function member:
Type& globalObject()
{
static Type theOneAndOnlyInstance;
return theOneAndOnlyInstance;
}
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
Update: Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it...
|
You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.
Read the C++ FAQ items starting from https://isocpp.org/wiki/faq/ctors#static-init-order
|
1,005,780
| 1,005,859
|
Scoping rules when inheriting - C++
|
I was reading the C++0x FAQ by Stroustrup and got stuck with this code. Consider the following code
struct A
{
void f(double)
{
std::cout << "in double" << std::endl;
}
};
struct B : A
{
void f(int)
{
std::cout << "in int" << std::endl;
}
};
int main()
{
A a; a.f(10.10); // as expected, A.f will get called
B b; b.f(10.10); // This calls b.f and we lose the .10 here
return 0;
}
My understanding was when a type is inherited, all protected and public members will be accessible from the derived class. But according to this example, it looks like I am wrong. I was expecting the b.f will call base classes f. I got the expected result by changing the derived class like
struct B : A
{
using A::f;
void f(int)
{
std::cout << "in int" << std::endl;
}
};
Questions
Why was it not working in the first code?
Which section in the C++ standard describes all these scoping rules?
|
The first code works as c++ is designed to work.
Overloading resolution follows a very complicated set of rules. From Stroustrup's c++ bible 15.2.2 "[A]mbiguities between functions from different base classes are not resolved based on argument types."
He goes on to explain the use of "using" as you have described.
This was a design decision in the language.
I tend to follow the Stroustrup book rather than the standard, but I'm sure it is in there.
[Edit]
Here it is (from the standard):
Chapter 13
When two or more different declarations are specified for a single name in the same scope, that name is said to be
overloaded.
And then:
13.2 Declaration matching
1 Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations (13.1). A function member of a derived class is not in the same scope as a function member of
the same name in a base class.
|
1,006,147
| 1,007,484
|
How do I detect desktop transition effects?
|
I want to minimise my application, take a screenshot of the current desktop and return my application back to its original state.
This has been working fine under windows XP, however under testing on different Vista machines the minimise time of 200 milliseconds is no longer valid.
Is there a way to ask the operating system when it has finished these fancy effects or lookup how long it has been given to perform the operation?
|
The closest I can find is SPI_GETUIEFFECTS, which tells you if such effects are enabled at all.
If enabled, you could of course use SPI_SETUIEFFECTS to turn them off. But that's a rather shotgun method - how would you restore them? It's probably better to temporarily turn off the ones that bother you most.
|
1,006,172
| 1,006,206
|
Pointer arithmetic on string type arrays, how does C++ handle this?
|
I am learning about pointers and one concept is troubling me.
I understand that if you have a pointer (e.g.'pointer1') of type INT that points to an array then you can fill that array with INTS. If you want to address a member of the array you can use the pointer and you can do pointer1 ++; to step through the array. The program knows that it is an array of INTs so it knows to step through in INT size steps.
But what if the array is of strings whcih can vary in length. How does it know what to do when you try to increment with ++ as each element is a different length?
Similarly, when you create a vector of strings and use the reserve keyword how does it know how much to reserve if strings can be different lengths?
This is probably really obvious but I can't work it out and it doesn't fit in with my current (probably wrong) thinking on pointers.
Thanks
|
Quite simple.
An array of strings is different from a vector of strings.
An array of strings (C-style pointers) is an array of pointers to an array of characters, "char**". So each element in the array-of-strings is of size "Pointer-to-char-array", so it can step through the elements in the stringarray without a problem. The pointers in the array can point at differently size chunks of memory.
With a vector of strings it is an array of string-objects (C++ style). Each string-object has the same object size, but contains, somewhere, a pointer to a piece of memory where the contents of the string are actually stored. So in this case, the elements in the vector are also identical in size, although different from "just a pointer-to-char-array", allowing simple element-address computation.
|
1,006,214
| 1,006,238
|
Why the below piece of code is not crashing , though i have deleted the object?
|
class object
{
public:
void check()
{
std::cout<<"I am doing ok..."<<std::endl;
}
};
int main()
{
object *p = new object;
p->check();
delete p;
p->check();
delete p;
p->check();
}
EDIT:
Gurus, i am confused by many of the statements "it may crash or may not".. why isnt there a standard to say, this how we deal with a block of memory that is deleted using 'delete operator'..? Any inputs ?
|
Because what it actually looks like after the compiler has had its way, is something like this:
object::check( object* this )
{
// do stuff without using this
}
int main()
{
object *p = new object;
object::check( p );
delete p;
object::check( p );
delete p;
object::check( p );
}
Since you're not touching "this", you don't actually access any bad memory.
Although, deleting p twice should be able to cause a crash:
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.2
|
1,006,364
| 1,006,399
|
minimal cross-platform gui lib?
|
I'm looking for a minimal and easy to learn C or C++ cross platform gui library.
In a nutshell I only need the following functionality:
application window
menu bar
some simple dialogs, File-open and save. Maybe a user-written one.
user canvas where I can draw lines an circles on.
some kind of message/event loop mechanism.
Target platforms would be Win32 and linux. MacOS would be nice to have but is not important at the moment.
Why am I looking for something minimal? I don't want to spend much time to learn a big and full blown abstraction system for a really small application. The easier and leaner, the better.
Any suggestions?
|
If you need something small, try FLTK libs: I used them at work (embedded development) and I think it's a valid option. Maybe apps are not as "cool" as QT-based ones, but developing with FLTK libs is fast and easy.
|
1,006,543
| 1,006,566
|
A lightweight XML parser efficient for large files?
|
I need to parse potentially huge XML files, so I guess this rules out DOM parsers.
Is out there any good lightweight SAX parser for C++, comparable with TinyXML on footprint?
The structure of XML is very simple, no advanced things like namespaces and DTDs are needed. Just elements, attributes and cdata.
I know about Xerces, but its sheer size of over 50mb gives me shivers.
Thanks!
|
If you are using C, then you can use LibXML from the Gnome project. You can choose from DOM and SAX interfaces to your document, plus lots of additional features that have been developed over years. If you really want C++, then you can use libxml++, which is a C++ OO wrapper around LibXML.
The library has been proven again and again, is high performance, and can be compiled on almost any platform you can find.
|
1,006,767
| 1,006,826
|
Fast method to read and store serialized objects with pointers and pointers to pointers in C++
|
I'm needing a fast method to read and store objects with pointers and pointers to pointers in xml files in c++ . Every object has it's own id , name , and class type.
|
You should build a map of pointers to IDs as you serialise your data.
|
1,007,054
| 1,012,391
|
Why can't I befriend a template parameter?
|
When researching an answer to a question (based on this answer) I tried to do the following:
template <class T>
class friendly {
friend class T;
};
friendly<string> howdy;
This fails to compile with the following error:
error: template parameter "T" may not be used in an
elaborated type specifier
friend class T;
From what I can understand from my good friend Google this is so that I won't accidentally try to instantiate friendly<int> but why should this be an error when compiling the template? Should't it be an error when instantiating the template with an invalid type (such as had I written int f() { return T::foo(); })
|
A bit more googleling brought up Extended friend Declarations (PDF) for C++0x.
This document contains the following:
template <typename T> class R {
friend T;
};
R<C> rc; // class C is a friend of R<C>
R<int> ri; // OK: “friend int;” is ignored
Which goes even further than what I thought (ignoring illegal friend decelerations rather than failing during instantiation). So I guess the answer is that there isn't a good reason and it's being rectified.
|
1,007,348
| 1,008,555
|
Ms Sitelock 1.15 and VS 2005
|
I'm trying to implement the MS Sitelock template into one of my Active-X Controls. I've downloaded the sitelock 1.15 sdk and I'm stuck on the very first step.
Including the sitelock.h header file causes a bunch of compile errors that have to do with the sal.h header file. It looks to me like sitelock.h wants to use attribute sal but that sal.h is only defining declspec sal. I'm using VS 2005, but the sitelock 1.5 documentation says that vs 2005 is supported. Is there something I need to do to reference attribute sal? I do have the Vista platform sdk installed. I'm including the sitelock.h in the header file of my active-x object. Perhaps that's not the place to do it?
See compile errors below:
....\public\sitelock.h(308) : error C2061: syntax error : identifier '_In_opt_count_'
..\..\public\sitelock.h(605) : see reference to class template instantiation 'CSiteLock<T>' being compiled
\public\sitelock.h(308) : error C2059: syntax error : ')'
...\public\sitelock.h(310) : error C2143: syntax error : missing ')' before '{'
...\public\sitelock.h(401) : error C2061: syntax error : identifier '_In_z_'
..\public\sitelock.h(401) : error C2059: syntax error : ')'
..\public\sitelock.h(402) : error C2143: syntax error : missing ')' before '{'
C2061: syntax error : identifier '_Inout_z_count_'
....\public\sitelock.h(451) : error C2059: syntax error : ')'
...\public\sitelock.h(452) : error C2143: syntax error : missing ')' before '{'
..\public\sitelock.h(520) : error C2061: syntax error : identifier '_In_z_'
..\public\sitelock.h(520) : error C2059: syntax error : ')'
...\public\sitelock.h(521) : error C2143: syntax error : missing ')' before '{'
...\public\sitelock.h(555) : error C2061: syntax error : identifier '_In_z_'
|
New SAL.H is included in the Windows server 2008 SDK, not the Vista one.
I'm still using the Vista SDK and have gotten by my compiler errors by translating the attribute sal macros to declspec sal macros in sitelock.h.
Used the notes in the following url to do the translation:
http://blogs.msdn.com/sdl/archive/2009/06/11/a-declspec-sal-to-attribute-sal-rosetta-stone.aspx
|
1,007,390
| 1,008,183
|
Is it possible to make pointers to distinct template types convertible?
|
I have a template class that will bundle some information with a type:
template <typename T>
class X
{
int data[10]; // doesn't matter what's here really
T t;
public:
// also not terribly relevant
};
Then lets say we have a Base class and Derived class:
class Base {};
class Derived : public Base {};
I'd like to be able to do something like this (but don't think I can):
void f(shared_ptr<X<Base> > b);
shared_ptr<X<Derived> > d(new X<Derived>);
f(d);
Is there a way that I can make pointers to X<T> convertible to pointers of X<Y> if T* is convertible to Y*?
|
Rephrasing the question to a more general: is it possible to convert pointers from unrelated types if the unrelated types are themselves convertible?, the answer is not. And different template instantiations define different unrelated types.
You can implicitly convert (see note below) a pointer to a derived object to a pointer of the base object (some restrictions apply due to access or ambiguity) or you can make an explicit conversion from a base pointer to a derived pointer (again with some restrictions). You can also convert back and forth to void*, but converting to an unrelated type ends up with undefined behavior.
There are clear reasons for pointers not being convertible from unrelated types. The first of which is that converting one pointer type to another pointer type will not convert the pointed memory. That is, you can convert an int to a double, but converting a pointer to an int to a pointer to double would make the compiler believe that there are 8 bytes of memory at the pointed address while in fact only 4 bytes are present (assuming 32 or 64 bit architecture with 32 bit integers and 64 bit doubles). Dereferencing the pointer will surely end bad.
Notes from the standard:
Section 4.10 of the standard deals with pointer conversions, first paragraph deals with null-pointer conversions, second paragraph with void pointer conversions. The third paragraph states that you can convert a pointer to type D to a pointer of type B as long as B is a base class of D. No other pointer conversion is defined there. In Section 5.4 where explicit conversions are specified, paragraph 7 deals with pointer conversions and only adds the possible explicit conversion from B* to D* in several situations as long as B is a base of B.
|
1,007,571
| 1,008,054
|
Getting svn diff to show C++ function during commit
|
Whenever I do a commit cycle in svn, I examine the diff when writing my comments. I thought it would be really nice to show the actual function that I made the modifications in when showing the diff.
I checked out this page, which mentioned that the -p option will show the C function that the change is in. When I tried using the -p option with some C++ code, however, it usually returns the access specifier (private, public, protected, etc), which isn't terribly handy.
I did notice that there is a -F option for diff that does the same as -p, but takes a user-specified regex. I was wondering: is there a simple regex to match a C++ function? It seems like that would be all that is necessary to get this to work.
I'd spend some time looking at this myself, but work is in crunch-mode and this seemed like something that a lot of people would find useful, so I figured I'd post it here.
EDIT: I'm not looking for something that's a slam-dunk catch-all regex, but something that would simply find the nearest function definition above the area diff would show. The fact that it would be nowhere near perfect, and somewhat buggy is okay with me. Just as long as it works right maybe like 60% of the time would be a significant productivity improvement IMHO.
|
Is there a simple regex to match a C++ function? No.
Is there a (complex) regex to match a C++. Maybe or could be possible to write one.
But I would say regular expressions neither are easily up to such a task (given you want some kind of excat match) nor are they the right tool for such a task.
Just think about case like this one. How would you handle this stuff.
void (*function(int, void (*)(int)))(int);
func1(int), func2(double); double func3(int);
The only real solution is to use a parser using yacc/lex. Which for your use case of course does nothing.
So either hack together some incomplete regex which fits most functions signatures in your code
|
1,007,585
| 1,007,903
|
Getting Loki Singleton to work in DLLs in VS 2008 C++
|
I'm pretty sure this problem isn't new, and pretty sure it's hard to solve. Hopefully I'm wrong about the latter.
I'm trying to use the Loki::Singleton from Modern C++ Design in a program of mine.
However, I can't seem to get it to work across DLLs. I think I know why this is happening: the templated code gets instantiated in every source module, so instead of there being one global variable, each module has its own.
Obviously, this makes the Singleton very much non-single.
Is there any way to get around this behavior?
|
I see in the Loki source directory that they have a specific SingletonDLL directory under test, looks like they use an exported, explicitly instantiated template (which would work). Hopefully that contains the code you want.
|
1,007,597
| 1,007,669
|
STL vector allocations
|
I was wondering why the vector templates perform two allocations, when only one seems to be
necessary.
For example this:
#include <vector>
#include <iostream>
class A {
public:
A(const A &a) {
std::cout << "Calling copy constructor " << this << " " << &a << "\n";
}
A() {
std::cout << "Calling default constructor " << this << "\n";
}
~A() {
std::cout << "Calling destructor " << this << "\n";
}
};
int main(int argc, char **argv)
{
std::vector <A> Avec;
std::cout << "resize start\n";
Avec.resize(1);
std::cout << "resize end\n";
return 0;
}
Outputs:
resize start
Calling default constructor 0x7fff9a34191f
Calling copy constructor 0x1569010 0x7fff9a34191f
Calling destructor 0x7fff9a34191f
resize end
|
It isn't performing two allocations, it is creating an object by the default constructor to pass into resize, then copying that object into the new position, then destructing the argument.
If you look at the arguments to resize:
void resize(n, t = T())
It has as a defaulted argument a default constructed object of type T (this is the default constructor being called in your output). Then, within the function, it copies this into the correct position (this is the copy constructor). After the resize function ends, destroys the argument (the destructor call in the output).
|
1,007,938
| 1,007,991
|
Qt - creating QPainter
|
I'm trying to rewrite method paintEvent in my programm and change it.
void MainWindow::paintEvent(QPaintEvent *event)
{
QRegion reg = this->bgPixmapHandle->rect();
QPainter painter(this);
painter.setClipRegion(reg);
painter.drawImage(bgPixmapHandle->rect(), bgPixmapHandle);
painter.end();
}
Here I try to change my bg image. But I got an error on line: QPainter painter(this);
Error: Variable 'QPainter painter' is
initialized, though the type is
incomplete
|
Include QPainter header file. QPainter class is only forward declared in one of the Qt headers you're including in that translation unit.
|
1,008,019
| 1,008,289
|
C++ Singleton design pattern
|
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way?
|
In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
Singleton: How should it be used
See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems
See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?
See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I
|
1,008,119
| 1,008,170
|
Boost library setup for Codeblocks
|
How to use boost libraries with Codeblocks(Windows) ? What i need to do after downloading the library from boost site ? Any idea, suggestions, pointers ?
|
Here are the instructions for setting up Boost with Code::Blocks
|
1,008,272
| 1,008,300
|
How to avoid explicitly calling a constructor when passing temporary object by reference in C++?
|
Let's say I have a class:
class String
{
public:
String(char *str);
};
And two functions:
void DoSomethingByVal(String Str);
void DoSomethingByRef(String &Str);
If I call DoSomethingByVal like this:
DoSomethingByVal("My string");
the compiler figures out that it should create a temporary String object and call the char* constructor.
However, if I try to use DoSomethingByRef the same way, I get a "Can't convert parameter from 'char *' to 'String &'" error.
Instead, I have to explicitly create an instance:
DoSomethingByRef(String("My string"));
which can get preety annoying.
Is there any way to avoid this?
|
You need to pass by const reference:
For:
void DoSomethingByVal(String Str);
In this situation the compiler first creates a temporary variable. Then the temporary variable is copy constructed into the parameter.
For:
void DoSomethingByRef(String const& Str);
In this situation the compiler creates a temporary variable. But temporary variables can not be bound to a reference they can only be bound to a const reference so your original function can not be called. Note the std::string objects constructor takes a const reference is the parameter to the copy constructor and that is why the first version works as the temporary is bound to the const reference parameter of the copy constructor only.
|
1,008,326
| 1,009,053
|
COM event with binary data in arguments
|
I am trying to develop a COM object using C++ and ATL to be used by both C++ and C# Windows Mobile clients. The COM object wraps up all of the logic to connect to our server and send/receive data using our proprietary protocol. I am having some difficulty coming up with an OnReceive event that works correctly with C# and C++.
I have defined the event function like this:
HRESULT OnReceive(BYTE* pBuffer, LONG lSize);
But when I look at the function in C# or Object Browser, it comes out as:
OnReceive(ref byte pBuffer, int lSize);
How would I treat "ref byte" as a pointer in C#? How can I pass binary data to OnReceive and allow both C++ and C# clients to access the binary data?
|
You basically have two options: use a SAFEARRAY of BYTEs or stuff the data into a BSTR. The latter, although ugly, used to be the default hack to pass binary data to VB6 components. Although I have never tried it, I guess it should work for .Net, too.
|
1,008,343
| 1,008,439
|
Boost.Python and Python exceptions
|
How can I make boost.python code python exceptions aware?
For example,
int test_for(){
for(;;){
}
return 0;
}
doesn't interrupt on Ctrl-C, if I export it to python. I think other exceptions
won't work this way to.
This is a toy example. My real problem is that I have a C function that may take hours to compute. And I want to interrupt it, if it takes more that hour for example. But I don't want to kill python instance, within the function was called.
Thanks in advance.
|
In your C or C++ code, install a signal handler for SIGINT that sets a global flag and have your long-running function check that flag periodically and return early when the flag is set. Alternatively, instead of an early return, you can raise a Python exception using the Python C API: see PyErr_SetInterrupt here.
|
1,008,449
| 1,008,470
|
What does this mean?
|
This:
typedef HRESULT (*PFN_HANDLE)(ClassName&);
It's used like this:
DWORD ClassName::Wait(PFN_HANDLE pfnh_foo)
{
while (!done) {
waitCode = WaitForMultipleObjects(paramA, paramB, paramC, paramD)
if (waitCode == WAIT_OBJECT_0)
{
pfnh_foo(*this);
}
else
done;
}
return waitCode;
}
It appears that Wait does nothing except block when it gets to WaitForMultipleObjects and then after that does this strange pfnh_foo thing and either loops back around to wait again or exits
|
Your wait() function basically waits for multiple objects and then invoke function using function pointer PFN_HANDLE if the wait is successful ( indicated by return value WAIT_OBJECT_0).
pfnh_foo(*this);
This calls the function pointed by pfnh_foo with argument *this.
Lets say we have function:
HRESULT someFunction(ClassName& myClassInstance)
{
//blah .. blah
}
Wait will be invoked like this:
PFN_HANDLE pfnh_foo = &someFunction; //function pointer to someFunction
wait(pfnh_foo);
|
1,008,514
| 1,188,838
|
On closing a Qt 4.5 application, Visual Studio reports that it has detected memory leaks
|
I am building a Qt 4.5 application on Windows using Visual Studio 2008. Whenever I run my application in Debug mode and then close it, Visual Studio prints the following to the output pane:
Detected memory leaks!
Dumping objects ->
{696512} normal block at 0x01981AB0, 24 bytes long.
Data: < > 00 CD CD CD 00 00 00 00 00 00 00 00 00 00 00 00
{696511} normal block at 0x02E59B70, 12 bytes long.
Data: < U2g U2g> B0 1A 98 01 E8 55 32 67 E8 55 32 67
And the output reports hundreds of such blocks. I have noticed this particularly when using Qt 4's Model/View framework. Does Qt in fact have memory leaks, or are there circumstances under which Visual Studio misreports leaks?
|
I had a chance to profile my project using DevPartner. The surprising thing is that it reports memory leaks in QtGuid4.dll and QtCored4.dll; however, after manually looking at each case, I discovered that they were all false positives.
As a side note, there were no memory leaks reported in the code using Qt.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.