question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,907,402 | 2,907,424 | Noob boost::bind member function callback question | #include <boost/bind.hpp>
#include <iostream>
using namespace std;
using boost::bind;
class A {
public:
void print(string &s) {
cout << s.c_str() << endl;
}
};
typedef void (*callback)();
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void main() {
A a;
B b;
string s("message");
b.set_callback(bind(A::print, &a, s));
b.do_callback();
}
So what I'm trying to do is to have the print method of A stream "message" to cout when b's callback is activated. I'm getting an unexpected number of arguments error from msvc10. I'm sure this is super noob basic and I'm sorry in advance.
| replace typedef void (*callback)(); with typedef boost::function<void()> callback;
A bound function doesn't produce an ordinary function, so you cannot just store it in a regular function pointer. However, boost::function is able to handle anything as long as it is callable with the correct signature, so that's what you want. It will work with a function pointer, or a functor created with bind.
After a few corrections to your code, I came up with this:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
// i prefer explicit namespaces, but that's a matter of preference
class A {
public:
// prefer const refs to regular refs unless you need to modify the argument!
void print(const std::string &s) {
// no need for .c_str() here, cout knows how to output a std::string just fine :-)
std::cout << s << std::endl;
}
};
// holds any arity 0 callable "thing" which returns void
typedef boost::function<void()> callback;
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void regular_function() {
std::cout << "regular!" << std::endl;
}
// the return type for main is int, never anything else
// however, in c++, you may omit the "return 0;" from main (and only main)
// which will have the same effect as if you had a "return 0;" as the last line
// of main
int main() {
A a;
B b;
std::string s("message");
// you forget the "&" here before A::print!
b.set_callback(boost::bind(&A::print, &a, s));
b.do_callback();
// this will work for regular function pointers too, yay!
b.set_callback(regular_function);
b.do_callback();
}
|
2,907,432 | 2,907,477 | C++ friend class std::vector | Is it possible to do the following portably:
struct structure {
structure() {}
private:
// only allow container copy construct
structure(const structure&) {}
// in general, does not work because allocator (not vector) calls copy construct
friend class std::vector<structure>;
};
example message trying to compile above:
In member function void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&)
[with _Tp = kernel_data<const double*>::block]:
...
/usr/include/c++/4.3/ext/new_allocator.h:108: error: within this context
Thanks
I do have workaround, but I am curious as how this could be possible
| No. vector (more precisely, the allocator passed into vector) can delegate the task of construction to a free function or another class, making the friendship useless.
Even if you pass your own allocator, it may be rebound to a class internal to the implementation. Then the constructor for your class may be accessed from that class, not your allocator. So if that's your workaround, it's not guaranteed. (Although looking at GCC's implementation, it does scrupulously use the un-rebound allocator to construct such subobjects.)
In GCC's libstdc++, no STL container template constructs the contained objects in the scope of a standard class or function.
|
2,907,473 | 2,907,480 | A simple question about type coercion in C++ | Given a function prototype, and a type definition:
int my_function(unsigned short x);
typedef unsigned short blatherskite;
Is the following situation defined by standard:
int main(int argc, char** argv) {
int result;
blatherskite b;
b=3;
result = my_function(b);
}
Do I get type coercion predictably via the function prototype?
| If your question is really about whether the types of the argument and the parameter match, then the answer is yes. typedef does not introduce a new type, it only creates alias for an existing one. Variable b has type unsigned int, just like the parameter, even though b is declared using typedef-name blatherskite.
Your example is not very good for demonstrating that though. All integral types are convertible to each other in C++, so (ignoring range issues) the code would have defined behavior even if blatherskite designated a different type (a new type). But it doesn't. So this is also perfectly valid
void foo(unsigned int* p);
...
blatherskite *pb = 0;
foo(pb); // <- still valid
|
2,907,500 | 2,907,534 | Can C++ and C# be used for applications for iPhone | Can I write applications for iPhone in C++ or C#?
Where can I find simulators for iPhone for testing my apps.
How to write them?
| You need at least a small Objective C stub to hook into the system and deal with provided services (including getting input), but your program can be primarily in C++ if you would like. Apple seems to disallow C#; tools such as MonoTouch appear to be banned by the current developer agreement.
With a Macintosh, you go to Apple's developer website and download the tools and SDKs for free. They only run on the Mac.
|
2,907,580 | 2,907,760 | How do i return a template class from a template function? | How do i pull off something that would make the last commented line compile? How would i have to change this code to make it work?
#include<iostream>
using namespace std;
template <int x>
class someclass{
public:
int size;
int intarr[x];
someclass():size(x){}
};
template<int x, int y>
int somefunc(someclass<x> A, someclass<y> B){
return ( A.size > B.size ? A.size : B.size);
}
template<int x, int y, int z>
someclass<x> anotherfunc(someclass<y> A, someclass<z> B){
return ( A.size > B.size ? A : B);
}
int main(){
someclass<5> A;
someclass<10> B;
cout << "SIZE = " << somefunc(A,B) << endl;
//cout << "SIZE = " << (anotherfunc(A,B)).size << endl; //THIS DOES NOT COMPILE
return 0;
}
| How is it supposed to know what x is from outside the function? (It can't look into the body, because in which body of which function it looks depends on what value x gets!). Also you cannot write that ?: because both your branches yield totally unrelated types that can't possibly get to a common type. But that operator requires to have a common type for both branches that it evaluates to.
And then the other problem you have that size is not a compile time constant is already elaborated by another post.
I think this should work:
template<int y, int z>
someclass<sizeof (char[+(y >= z)]) * y> anotherfunc(someclass<y> A, someclass<z> B){
return A;
}
template<int y, int z>
someclass<sizeof (char[+(y < z)]) * z> anotherfunc(someclass<y> A, someclass<z> B){
return B;
}
Now when calling it, y and z are deduced by the parameters, and then the parameters are substituted into the return type. The sizeof(char[1 or 0]) will test whether y or z is greater. In the respective template that evaluates this to sizeof(char[1]) (which yields 1) we will multiply by the value that is greater (or equal). If the respective template yields sizeof(char[0]) this is a deduction failure (an array can't be of zero size!) and the template won't get selected by overload resolution (known as SFINAE).
The unary + yields 1 or 0 as int instead of true or false, which could cause compiler warnings for some compilers.
There is also the "clean" way with enable_if. It's not doing hideous sizeof tricks, but rather using the general established enable_if pattern. Boost has an implementation of it
template<int y, int z>
typename boost::enable_if_c<(y >= z), someclass<y> >::type
anotherfunc(someclass<y> A, someclass<z> B){
return A;
}
template<int y, int z>
typename boost::enable_if_c<(y < z), someclass<z> >::type
anotherfunc(someclass<y> A, someclass<z> B){
return B;
}
This may at first sight look more noisy, but should be easier to understand and faster to follow to folks that are already used to enable_if (the _c variant of boost's implementation accepts plain booleans, as above).
|
2,907,797 | 2,907,817 | Where does the compiler store methods for C++ classes? | This is more a curiosity than anything else...
Suppose I have a C++ class Kitty as follows:
class Kitty
{
void Meow()
{
//Do stuff
}
}
Does the compiler place the code for Meow() in every instance of Kitty?
Obviously repeating the same code everywhere requires more memory. But on the other hand, branching to a relative location in nearby memory requires fewer assembly instructions than branching to an absolute location in memory on modern processors, so this is potentially faster.
I suppose this is an implementation detail, so different compilers may perform differently.
Keep in mind, I'm not considering static or virtual methods here.
| I believe the standard way for instance methods is to be implemented like any static method, only once, but having the this pointer passed on a specific register or on the stack to perform the call.
|
2,907,859 | 2,909,575 | Mingling C++ classes with Objective C classes | I am using the iphone SDK and coding primarily in C++ while using parts of the SDK in obj-c. Is it possible to designate a C++ class in situations where an obj-c class is needed? For instance:
1) when setting delegates to obj-c objects.
I cannot make a C++ class derive from a Delegate protocol so this and possibly other reasons prevent me from making my C++ class a delegate for various obj-c objects. What I do as a solution is create an obj-c adapter class that contains a ptr to the C++ class and is used as the delegate (notifying the C++ class when it is called). It feels cumbersome to write these every time I need to get delegate notifications to a C++ class.
2) when setting selectors
This goes hand in hand with item 1. Say I want to set a callback to fire when something is done, like a button press or a setAnimationDidStopSelector in the UIView animation functionality. It would be nice to be able to designate a C++ function along with the relevant delegate for setAnimationDelegate.
Well, I suspect this isn't readily possible, but if anyone has any suggestions on how to do it if it is, or on how to write such things more easily, I would love to hear them. Thanks.
| The sad news is that you can't get completely around the adapters, but you can ease the job. By using the Objective-C runtime libraries you can reduce the clutter by generating the adapters for you with a declarative approach.
The Objective-C runtime allows you to construct classes at runtime for which you can set the implementation function for the methods. Using templates, you can thus generate an Objective-C class from a type-oriented declaration by generating the trampoline functions that invoke the C++ methods that you want.
I started a prototype a while back and the state mentioned there might be sufficient in your case. It is possible to do this better and support properties and Distributed Objects cleanly too, but i haven't found the time yet to implement a better version.
|
2,907,929 | 2,907,973 | How to solve this error that is shown on Windbg? | I've loaded a .exe and it gave this error:
Microsoft (R) Windows Debugger Version 6.12.0002.633 X86
Copyright (c) Microsoft Corporation. All rights reserved.
CommandLine: "C:\Users\Public\SoundLog\Code\Código Python\SoundLog\dist\SoundLog.exe"
Symbol search path is: *** Invalid ***
****************************************************************************
* Symbol loading may be unreliable without a symbol search path. *
* Use .symfix to have the debugger choose a symbol path. *
* After setting your symbol path, use .reload to refresh symbol locations. *
****************************************************************************
Executable search path is:
ModLoad: 00400000 0061c000 image00400000
ModLoad: 771a0000 772dc000 ntdll.dll
ModLoad: 76e10000 76ee4000 C:\Windows\system32\kernel32.dll
ModLoad: 75460000 754aa000 C:\Windows\system32\KERNELBASE.dll
ModLoad: 76550000 76619000 C:\Windows\system32\USER32.dll
ModLoad: 76b30000 76b7e000 C:\Windows\system32\GDI32.dll
ModLoad: 77310000 7731a000 C:\Windows\system32\LPK.dll
ModLoad: 76ef0000 76f8d000 C:\Windows\system32\USP10.dll
ModLoad: 75650000 756fc000 C:\Windows\system32\msvcrt.dll
ModLoad: 65ee0000 65f83000 C:\Windows\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_508ed732bcbc0e5a\MSVCR90.dll
(c8.704): Break instruction exception - code 80000003 (first chance)
eax=00000000 ebx=00000000 ecx=0012fb0c edx=771e64f4 esi=fffffffe edi=00000000
eip=7723e60e esp=0012fb28 ebp=0012fb54 iopl=0 nv up ei pl zr na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246
*** ERROR: Symbol file could not be found. Defaulted to export symbols for ntdll.dll -
ntdll!LdrVerifyImageMatchesChecksum+0x633:
7723e60e cc int 3
0:000> g
Then I pressed F5 and while executing the program gave me this error (this one is what I need to solve):
ModLoad: 6f980000 6ff11000 C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll
ModLoad: 6f8e0000 6f97b000 C:\Windows\WinSxS\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4927_none_d08a205e442db5b5\MSVCR80.dll
ModLoad: 752f0000 752fb000 C:\Windows\system32\profapi.dll
ModLoad: 6e670000 6f168000 C:\Windows\assembly\NativeImages_v2.0.50727_32\mscorlib\8c1770d45c63cf5c462eeb945ef9aa5d\mscorlib.ni.dll
ModLoad: 03d90000 03dac000 SoundLogC++WrapperDLL.dll
ModLoad: 03db0000 03dcc000 SoundLogC++WrapperDLL.dll
ModLoad: 6afa0000 6affb000 C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorjit.dll
ModLoad: 04dd0000 04e13000 msvcm90.dll
ModLoad: 04e20000 04e63000 msvcm90.dll
ModLoad: 76aa0000 76b23000 C:\Windows\system32\CLBCatQ.DLL
ModLoad: 75280000 752df000 C:\Windows\system32\sxs.dll
ModLoad: 60340000 60348000 C:\Windows\Microsoft.NET\Framework\v2.0.50727\culture.dll
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): CLR exception - code e0434f4d (first chance)
(b78.9c8): CLR exception - code e0434f4d (first chance)
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): C++ EH exception - code e06d7363 (first chance)
(b78.9c8): CLR exception - code e0434f4d (!!! second chance !!!)
eax=0012e2a4 ebx=e0434f4d ecx=00000001 edx=00000000 esi=0012e32c edi=002bada0
eip=75469617 esp=0012e2a4 ebp=0012e2f4 iopl=0 nv up ei pl nz ac po nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000212
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\system32\KERNELBASE.dll -
KERNELBASE!RaiseException+0x54:
75469617 c9 leave
Can anyone tell me what is this and how can I solve it?
| Your first issue is that you do not have a symbol path set. You can run ".symfix", as suggested in the message, to automatically select a symbol path using Microsoft's public symbol server. The second is an unhandled exception. You need to get proper symbols first, and then run "k" to get a stack trace that should give you more insight into what is happening.
|
2,908,057 | 2,908,351 | Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./? | My project directory looks like this:
/project
Makefile
main
/src
main.cpp
foo.cpp
foo.h
bar.cpp
bar.h
/obj
main.o
foo.o
bar.o
What I would like my makefile to do would be to compile all .cpp files in the /src folder to .o files in the /obj folder, then link all the .o files in /obj into the output binary in the top-level folder /project.
I have next to no experience with Makefiles, and am not really sure what to search for to accomplish this.
Also, is this a "good" way to do this, or is there a more standard approach to what I'm trying to do?
| Makefile part of the question
This is pretty easy, unless you don't need to generalize
try something like the code below (but replace space indentation with tabs near g++)
SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...
main.exe: $(OBJ_FILES)
g++ $(LDFLAGS) -o $@ $^
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
Automatic dependency graph generation
A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:
CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)
And as guys mentioned already, always have GNU Make Manual around, it is very helpful.
|
2,908,076 | 8,379,375 | How to fix this exception shown in windbg execution? | after running the .exe thought WinDBG, this was the exception information provided by pressing "k" when the exception occured:
ChildEBP RetAddr
0012e2f4 6f9fbb1c KERNELBASE!RaiseException+0x58
0012e354 6fba88f4 mscorwks!RaiseTheExceptionInternalOnly+0x2a8
0012e36c 6fba8966 mscorwks!RaiseTheException+0x4e
0012e394 6fba8997 mscorwks!RaiseTheException+0xc0
0012e3c0 6fba89a5 mscorwks!RealCOMPlusThrow+0x30
0012e3d0 6fac7ffe mscorwks!RealCOMPlusThrow+0xd
0012e8c8 6fa9d308 mscorwks!MethodTable::DoRunClassInitThrowing+0x44c
0012e914 6f9f8b9b mscorwks!DomainFile::Activate+0x226
0012e920 6f9cc537 mscorwks!DomainFile::DoIncrementalLoad+0xb4
0012e9a4 6f9cc43e mscorwks!AppDomain::TryIncrementalLoad+0x97
0012e9f4 6f9cd449 mscorwks!AppDomain::LoadDomainFile+0x19d
0012ea6c 6fb40e1a mscorwks!AppDomain::LoadDomainAssembly+0x116
0012eab0 6fb148c4 mscorwks!AppDomain::LoadExplicitAssembly+0x43
0012ed24 6fb167be mscorwks!ExecuteDLLForAttach+0x109
0012edd4 6fb16e9b mscorwks!ExecuteDLL+0x197
0012ee20 704c71f8 mscorwks!CorDllMainForThunk+0x8d
0012ee38 704ca1fe MSCOREE!CorDllMainWorkerForThunk+0x50
0012ee48 704bb2dc MSCOREE!VTableBootstrapThunkInitHelper+0x1b
0012eec8 7726519a MSCOREE!VTableBootstrapThunkInitHelperStub+0xc
WARNING: Stack unwind information not available. Following frames may be wrong.
0012eed0 7726517e ntdll!RtlpNtMakeTemporaryKey+0x43d6
0012eed4 770116fc ntdll!RtlpNtMakeTemporaryKey+0x43ba
0012ef10 77227d96 RPCRT4!DG_CCALL::DispatchPacket+0x1e3
0012ef14 014b1628 ntdll!RtlTimeToElapsedTimeFields+0xe902
0012ef18 00000000 0x14b1628
Does anyone knows what does this mean? And how can I solve it?
| If it is a 3.5 or lower .NET then you have to load sos by calling ".loadby sos mscorwks". If it is a 4.0 then you have to use ".loadby sos clr".
|
2,908,135 | 2,908,148 | Compilation problem in the standard x86_64 libraries | I am having trouble compiling a program I have written. I have two different files with the same includes but only one generates the following error when compiled with g++
/usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../../../lib/crt1.o: In function `_start':
/build/buildd/eglibc-2.10.1/csu/../sysdeps/x86_64/elf/start.S:109: undefined reference to `main'
collect2: ld returned 1 exit status
The files I am including in my header are as follows:
#include <google/sparse_hash_map>
using google::sparse_hash_map;
#include <ext/hash_map>
#include <math.h>
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
using std::priority_queue;
using std::stack;
using std::vector;
using __gnu_cxx::hash_map;
using __gnu_cxx::hash;
using namespace std;
Searching the internet for those two lines hasn't resulted in anything to help me. I would be very grateful for any advice. Thank you
| You need a main function and you don't have one. If you do have a main function, show more code please.
|
2,908,244 | 2,908,270 | why no implicit conversion from pointer to reference to const pointer | I'll illustrate my question with code:
#include <iostream>
void PrintInt(const unsigned char*& ptr)
{
int data = 0;
::memcpy(&data, ptr, sizeof(data));
// advance the pointer reference.
ptr += sizeof(data);
std::cout << std::hex << data << " " << std::endl;
}
int main(int, char**)
{
unsigned char buffer[] = { 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, };
/* const */ unsigned char* ptr = buffer;
PrintInt(ptr); // error C2664: ...
PrintInt(ptr); // error C2664: ...
return 0;
}
When I run this code (in VS2008) I get this: error C2664: 'PrintInt' : cannot convert parameter 1 from 'unsigned char *' to 'const unsigned char *&'. If I uncomment the "const" comment it works fine.
However shouldn't pointer implicitly convert into const pointer and then reference be taken? Am I wrong in expecting this to work? Thanks!
| If the pointer gets converted to a const pointer, as you suggest, then the result of that conversion is a temporary value, an rvalue. You cannot attach a non-const reference to an rvalue - it is illegal in C++.
For example, this code will not compile for a similar reason
int i = 42;
double &r = i;
Even though type int is convertible to type double, it still doesn't mean that you can attach a double & reference to the result of that conversion.
However, a const reference (i.e. a reference of reference-to-const type) can be attached to an rvalue, meaning that this code will compile perfectly fine
int i = 42;
const double &r = i;
In your case if you declare your function as
void PrintInt(const unsigned char* const& ptr) // note the extra `const`
the code will compile.
|
2,908,275 | 2,908,314 | Are reference attributes destroyed when class is destroyed in C++? | Suppose I have a C++ class with an attribute that is a reference:
class ClassB {
ClassA &ref;
public:
ClassB(ClassA &_ref);
}
Of course, the constructor is defined this way:
ClassB::ClassB(ClassA &_ref) : ref(_ref) { /* ... */ }
My question is: When an instance of class 'ClassB' is destroyed, is the object referenced by 'ClassB::ref' also destroyed?
| A reference is nothing but an alias for a variable, the alias gets destructed, not the actual variable. You could consider it some kind of pointer, but there are reasons to refrain from this kind of (evil) thoughts :).
|
2,908,477 | 2,908,507 | When do I need to deallocate memory? | I am using this code inside a class to make a webbrowser control visit a website:
void myClass::visitWeb(const char *url)
{
WCHAR buffer[MAX_LEN];
ZeroMemory(buffer, sizeof(buffer));
MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, url, strlen(url), buffer, sizeof(buffer)-1);
VARIANT vURL;
vURL.vt = VT_BSTR;
vURL.bstrVal = SysAllocString(buffer);
// webbrowser navigate code...
VariantClear(&vURL);
}
I call visitWeb from another void function that gets called on the handlemessage() for the app.
Do I need to do some memory deallocation here?, I see vURL is being deallocated by VariantClear but should I deallocate memory for buffer?
I've been told that in another bool I have in the same app I shouldn't deallocate anything because everything clear out when the bool return true/false, but what happens on this void?
| I think you have some fundamental problems with your understanding of memory management. In this case, no, you don't need to explicitly free any memory. You didn't ever call new, so you don't need to call delete. buffer exists only on the stack, and will vanish when this method returns.
|
2,908,603 | 2,908,615 | TerminateProcess and deadlocks | Is it real that the TerminateProcess function in Windows could hang because the threads inside the process were stuck in a deadlock?
Example: Process A is running under Process B's control, now Process A gets into a deadlock and Process B detects this and decides to 'Kill' process A using TerminateProcess.
Would it be successful in killing the hung Process A?
| Yes, all kernel objects held by the process will be released, including locks.
The main problem with TerminateProcess is that the process has no say in the matter: if it's holding on to any global state (files, shared memory, etc) then you have no guarantee those things are in a consistent state after the process is terminated.
|
2,908,607 | 2,908,707 | Fun with casting and inheritance | NOTE: This question is written in a C# like pseudo code, but I am really going to ask which languages have a solution. Please don't get hung up on syntax.
Say I have two classes:
class AngleLabel: CustomLabel
{
public bool Bold; // Just upping the visibility to public
// code to allow the label to be on an angle
}
class Label: CustomLabel
{
public bool Bold; // Just upping the visibility to public
// Code for a normal label
// Maybe has code not in an AngleLabel (align for example).
}
They both decend from this class:
class CustomLabel
{
protected bool Bold;
}
The bold field is exposed as public in the descended classes.
No interfaces are available on the classes.
Now, I have a method that I want to beable to pass in a CustomLabel and set the Bold property. Can this be done without having to 1) find out what the real class of the object is and 2) cast to that object and then 3) make seperate code for each variable of each label type to set bold. Kind of like this:
public void SetBold(customLabel: CustomLabel)
{
AngleLabel angleLabel;
NormalLabel normalLabel;
if (angleLabel is AngleLabel )
{
angleLabel= customLabel as AngleLabel
angleLabel.Bold = true;
}
if (label is Label)
{
normalLabel = customLabel as Label
normalLabel .Bold = true;
}
}
It would be nice to maybe make one cast and and then set bold on one variable.
What I was musing about was to make a fourth class that just exposes the bold variable and cast my custom label to that class.
Would that work?
If so, which languages would it work for? (This example is drawn from an old version of Delphi (Delphi 5)). I don't know if it would work for that language, (I still need to try it out) but I am curious if it would work for C++, C# or Java.
If not, any ideas on what would work? (Remember no interfaces are provided and I can not modify the classes.)
Any one have a guess?
| It would work in Delphi. Code in the same unit as the classes it uses have implicit access to protected (but not strict protected) members, even those members declared in another unit. You'de declare the property protected in CustomLabel:
type
CustomLabel = class
private
FBold: Boolean;
protected
property Bold: Boolean read FBold write FBold;
end;
The bold-setting procedure, in another unit, would have its own CustomLabel descendant:
type
TAccessCustomLabel = class(CustomLabel);
procedure SetBold(customLabel: CustomLabel)
begin
TAccessCustomLabel(customLabel).Bold := True;
end;
You can't use an as cast on that because the actual parameter will never be an instance of TAccessLabel. It will be an instance of AngleLabel or NormalLabel, but since the portions inherited from CustomLabel by all three classes are common, the Bold property is the same in all of them. That remains true even after the property has been publicized or published in a descendant:
type
AngleLabel = class(CustomLabel)
public
property Bold;
end;
You can change the visibility of properties, but not fields. If you try the same thing with a field, you'll be declaring a new field with the same name that hides the inherited field.
You can do something similar in C++, but it's not as commonly done as it is in Delphi, so it's likely to draw some ire, especially if you intend to write portable code.
Declare a fourth class, like in Delphi. C++ isn't as loose with member access as Delphi is, but it has the concept of friendship, which works just as well in this case.
class AccessCustomLabel: public CustomLabel
{
friend void SetLabel(CustomLabel* customLabel);
};
That function now has full access to the class's members:
void SetLabel(CustomLabel* customLabel)
{
// Not allowed:
// customLabel->bold = true
// Not ordinarily allowed; requires friendship
reinterpret_cast<AccessCustomLabel*>(customLabel)->bold = true;
}
That's technically undefined behavior because we've type-casted an object to a type that it doesn't really have. We're relying on all descendants of CustomLabel to have the same layout, in particular for the bold member of an AccessCustomLabel to reside at the same relative position as the bold member of any other CustomLabel descendant.
The type casting in the Delphi and C++ code performs type punning. You're not going to get away with that in C# or Java; they check the results of their casts, so if customLabel doesn't really hold an instance of AccessCustomLabel, you'll get an exception. You'll have to use reflection to access the protected members of unrelated classes in those languages. Demonstrating that is beyond my depth.
|
2,908,632 | 2,908,695 | Why does DestroyWindow close my application? | I'v created a window after creating my main one but calling DestroyWindow on its handle closes the entire application, how can I simply get rid of it?
it looks like this:
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
HWND fakehandle;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_EX_LAYERED,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
fakehandle = CreateWindow(szWindowClass, "FAKE WINDOW", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd || !fakehandle)
{
return FALSE;
}
//some code
DestroyWindow(fakehandle);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
how can I destroy this window without destroying my main one? I'm creating a dummy window to check for multisampling in OpenGL.
Thanks
| I've just found this comment:
If the specified window is a parent or owner window, DestroyWindow automatically destroys the associated child or owned windows when it destroys the parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window.
on the DestroyWindow MSDN page.
Could this have some bearing on your problem? Could you be setting the parent of hWnd where you've got //some code?
|
2,908,673 | 2,914,595 | Is it possible to load a file full of binary data into GDB when GDB is debugging a core file? | I am debugging a crash using GDB and a core file. A large portion of the memory space is mmapped into the process. That portion of the memory is not saved into the core file. I have a file that contains all the data in that mmapped memory.
I would like to find a way to load the data from that file into GDB at a certain offset so that I can display datastructures within that address space. Is this possible?
Note that I have tried the 'restore' command in GDB but it only works when debugging a running process.
Perhaps there are tools that allow a core file to have additional data appended to it? I am experimenting with objcopy to see if I can augment the core file with this binary data, but I have not been successful yet.
| The only way that I was able to get this to work was to modify the core file itself to have an additional program header/section that contained the new data.
In theory, I believe that objcopy should be able to do this, but after a lot of testing I was unable to get it to work. Instead, I resorted to writing a perl script that modified the core file.
Here is the script for those of you stuck in a similar situation (note that this is for ELF core files on an i386 arch):
#!/usr/bin/perl
my @elfHeader = (
[ident => 'A16'],
[e_type => 'v'],
[e_machine => 'v'],
[e_version => 'V'],
[e_entry => 'V'],
[e_phoff => 'V'],
[e_shoff => 'V'],
[e_flags => 'V'],
[e_ehsize => 'v'],
[e_phentsize => 'v'],
[e_phnum => 'v'],
[e_shentsize => 'v'],
[e_shnum => 'v'],
[e_shstrndx => 'v']
);
my @progHeader = (
[ptype => 'V'],
[poffset => 'V'],
[pvaddr => 'V'],
[ppaddr => 'V'],
[pfilesz => 'V'],
[pmemsz => 'V'],
[pflags => 'V'],
[palign => 'V'],
);
my ($core, $dataFile, $outFile) = @ARGV;
main();
sub main {
my @stat = stat($core);
my $coreSize = $stat[7];
@stat = stat($dataFile);
my $dfSize = $stat[7];
my ($in, $out, $df);
open($in, "", $outFile) || die("Couldn't open $outFile: $!");
my $buf;
my $bytes = sysread($in, $buf, 52);
my $hdr = unpackStruct(\@elfHeader, $buf);
# Fix the elf header to have an additional program header
my $phNum = $hdr->{e_phnum};
$hdr->{e_phnum}++;
# Fix the header to point to a new location for the program headers (at the end of the file)
my $phOff = $hdr->{e_phoff};
$hdr->{e_phoff} = $coreSize;
# Read in the full program header table
my $phTable;
sysseek($in, $phOff, 0);
my $readSize = $hdr->{e_phentsize} * $phNum;
$bytes = sysread($in, $phTable, $readSize);
# Add an additional entry to the end of the ph table
my $entry = packStruct(\@progHeader, {ptype => 1,
poffset => $coreSize + $hdr->{e_phentsize} * $hdr->{e_phnum},
pvaddr => 0x80f95000,
ppaddr => 0,
pfilesz => $dfSize,
pmemsz => $dfSize,
pflags => 7,
palign => 4096});
$phTable .= $entry;
# Form the new elf header
my $elf = packStruct(\@elfHeader, $hdr);
# Output the new header
syswrite($out, $elf, length($elf));
# Copy the full core file after the header
sysseek($in, 52, 0);
copyData($in, $out, $coreSize - 52);
# Output the new program table
syswrite($out, $phTable, length($phTable));
# Add the data on the end
copyData($df, $out, $dfSize);
}
sub copyData {
my ($in, $out, $numBytes) = @_;
my $buf;
while ($numBytes > 0) {
my $readBytes = sysread($in, $buf, 8192);
syswrite($out, $buf, $readBytes);
$numBytes -= $readBytes;
}
}
sub unpackStruct {
my ($fields, $data) = @_;
my $unpack;
map {$unpack .= $_->[1]} @{$fields};
my @vals = unpack($unpack, $data);
my %res;
foreach my $field (@{$fields}) {
$res{$field->[0]} = shift(@vals);
}
return \%res;
}
sub packStruct {
my ($fields, $data) = @_;
my $pack;
map {$pack .= $_->[1]} @{$fields};
my @vals;
foreach my $field (@{$fields}) {
push(@vals, $data->{$field->[0]})
}
my $res = pack($pack, @vals);
return $res;
}
|
2,908,834 | 2,908,853 | Why was the definition of a variable changed during the development of C++11? | n3035 says:
A variable is introduced by the declaration of an object. The variable's name denotes the object.
n3090 says:
A variable is introduced by the declaration of a reference other than a non-static data member or of an object. The variable's name denotes the reference or object.
I wonder what motivated this change. Does it have to do with rvalue references?
| The change was in response to CWG defect 633. The list of changes related to this can be found in n2993:
The goal of these changes is to expand the meaning of "variable" to encompass both named objects and references, and to apply the term consistently wherever feasible.
|
2,908,928 | 2,909,107 | Coupling an MFC CListCtrl and CTreeCtrl to get a view of the whole tree, not just one node at a time | Consider Windows Explorer (or regedit or similar). To the left side, there is a tree view, and to the right, a list view. In all cases I know of, the contents of the right view reflect the attributes of the selected node from the left pane. This is all well and good... but just not what I want.
The nodes of the tree I want to display have a very few attributes (2-3) associated with each node - a reasonable amount to display horizontally as a row in a table. Rather than waste all that list view space on a single node with very few properties, I would like to have my list view display a table of the whole tree's properties (as the part of the tree currently expanded). So the nth line in the left view (tree) will correspond directly to the nth line in the right view (list/table), and I will get a decent overview of the properties of my tree.
Does anyone know of code that does this? I am guessing that slaving a CListCtrl to a CTreeCtrl would be the way to go, and somehow overriding the vertical scrolling functions so that they are locked together. I'm just not sure that it is possible to lock the scrolls together like this... among other things! All advice gratefully welcomed :-)
| You are probably looking for Coumn Tree Control
|
2,909,213 | 2,909,236 | How to add custom line endings in text file (e.g. I want to add a line ending after all periods) | I have a bunch of text files where I want to add a line ending after each period.
I'm wondering if there is a way to do this by doing replacing all periods with a \n\n, assuming I have the right encoding (unix).
Anyone know how I would do this? Replace .'s with .\n\n and then save as a different file?
Thanks!
| perl -pne 's/\./\.\n/g' < input_file > output_file
|
2,909,250 | 2,976,254 | Disable MSBuild output of "Processing /ORDER options..." | The output file from our project build has gone from 6MB to over 75MB in text.
Diff'ing the last good build and the first time it blew up, there's a section in the output file like this in the latest:
Processing /ORDER options
External code objects not listed in the /ORDER file:
?onCallDisconnected@CallStateConnected@CallImpl@space@@UAEXV?$shared_ptr@VCallImpl@space@@@boost@@V?$shared_ptr@VGenericCall@space@@@5@K@Z ; framework.lib(CallStates.obj)
??_DBoolSetting@space@@QAEXXZ ; framework.lib(SettingValueImpl.obj)
...... continues for ~50MB
??$?0U?$pair@$$CBV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@J@std@@@?$allocator@U_Node@?$_Tree_nod@V?$_Tmap_traits@V?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@JU?$less@V?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@J@std@@@2@$0A@@std@@@std@@@std@@QAE@ABV?$allocator@U?$pair@$$CBV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@J@std@@@1@@Z ; CallStatistics.obj
Finished processing /ORDER options
I'm not sure how this got in there, but anyone know how to turn it off?
| I turned of VERBOSE linking and set it to none. Now I have zip spitting out.
|
2,909,427 | 2,909,445 | C++ floating point precision |
Possible Duplicate:
Floating point inaccuracy examples
double a = 0.3;
std::cout.precision(20);
std::cout << a << std::endl;
result: 0.2999999999999999889
double a, b;
a = 0.3;
b = 0;
for (char i = 1; i <= 50; i++) {
b = b + a;
};
std::cout.precision(20);
std::cout << b << std::endl;
result: 15.000000000000014211
So.. 'a' is smaller than it should be.
But if we take 'a' 50 times - result will be bigger than it should be.
Why is this?
And how to get correct result in this case?
| To get the correct results, don't set precision greater than available for this numeric type:
#include <iostream>
#include <limits>
int main()
{
double a = 0.3;
std::cout.precision(std::numeric_limits<double>::digits10);
std::cout << a << std::endl;
double b = 0;
for (char i = 1; i <= 50; i++) {
b = b + a;
};
std::cout.precision(std::numeric_limits<double>::digits10);
std::cout << b << std::endl;
}
Although if that loop runs for 5000 iterations instead of 50, the accumulated error will show up even with this approach -- it's just how floating-point numbers work.
|
2,909,515 | 2,909,699 | Access cost of dynamically created objects with dynamically allocated members | I'm building an application which will have dynamic allocated objects of type A each with a dynamically allocated member (v) similar to the below class
class A {
int a;
int b;
int* v;
};
where:
The memory for v will be allocated in the constructor.
v will be allocated once when an object of type A is created and will never need to be resized.
The size of v will vary across all instances of A.
The application will potentially have a huge number of such objects and mostly need to stream a large number of these objects through the CPU but only need to perform very simple computations on the members variables.
Could having v dynamically allocated could mean that an instance of A and its member v are not located together in memory?
What tools and techniques can be used to test if this fragmentation is a performance bottleneck?
If such fragmentation is a performance issue, are there any techniques that could allow A and v to allocated in a continuous region of memory?
Or are there any techniques to aid memory access such as pre-fetching scheme? for example get an object of type A operate on the other member variables whilst pre-fetching v.
If the size of v or an acceptable maximum size could be known at compile time would replacing v with a fixed sized array like int v[max_length] lead to better performance?
The target platforms are standard desktop machines with x86/AMD64 processors, Windows or Linux OSes and compiled using either GCC or MSVC compilers.
| If you have a good reason to care about performance...
Could having v dynamically allocated could mean that an instance of A and its member v
are not located together in memory?
If they are both allocated with 'new', then it is likely that they will be near one another. However, the current state of memory can drastically affect this outcome, it depends significantly on what you've been doing with memory. If you just allocate a thousand of these things one after another, then the later ones will almost certainly be "nearly contiguous".
If the A instance is on the stack, it is highly unlikely that its 'v' will be nearby.
If such fragmentation is a performance issue, are there any techniques that could
allow A and v to allocated in a continuous region of memory?
Allocate space for both, then placement new them into that space. It's dirty, but it should typically work:
char* p = reinterpret_cast<char*>(malloc(sizeof(A) + sizeof(A::v)));
char* v = p + sizeof(A);
A* a = new (p) A(v);
// time passes
a->~A();
free(a);
Or are there any techniques to aid memory access such as pre-fetching scheme?
Prefetching is compiler and platform specific, but many compilers have intrinsics available to do it. Mind- it won't help a lot if you're going to try to access that data right away, for prefetching to be of any value you often need to do it hundreds of cycles before you want the data. That said, it can be a huge boost to speed. The intrinsic would look something like __pf(my_a->v);
If the size of v or an acceptable maximum size could be known at compile time
would replacing v with a fixed sized array like int v[max_length] lead to better
performance?
Maybe. If the fixed size buffer is usually close to the size you'll need, then it could be a huge boost in speed. It will always be faster to access one A instance in this way, but if the buffer is unnecessarily gigantic and largely unused, you'll lose the opportunity for more objects to fit into the cache. I.e. it's better to have more smaller objects in the cache than it is to have a lot of unused data filling the cache up.
The specifics depend on what your design and performance goals are. An interesting discussion about this, with a "real-world" specific problem on a specific bit of hardware with a specific compiler, see The Pitfalls of Object Oriented Programming (that's a Google Docs link for a PDF, the PDF itself can be found here).
|
2,909,590 | 2,909,672 | Strange error with CreateCompatibleDC | Maybe this is a foolish question, I can't see why I can not get a DC created in the following code :
HBITMAP COcrDlg::LoadClippedBitmap(LPCTSTR pathName,UINT maxWidth,UINT maxHeight)
{
HBITMAP hBmp = (HBITMAP)::LoadImage(NULL, pathName, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION);
if (!hBmp)
return NULL;
HDC hdc = (HDC)GetDC();
HDC hdcMem = CreateCompatibleDC(hdc);
if (!hdcMem)
{
DWORD err = GetLastError();
}
...
...
...
The bitmap hBmp is loaded fine and hdc has a valid value. But the call to CreateCompatibleDC() returns a NULL pointer. Then, GetLastError() returns 0 !
Anybody can guess what's going on here , please ?
PS : There are no memory allocations or GDI routines called before this one...so I think memory leaks should be ruled out.
| You are improperly casting the result of GetDC() to an HDC. GetDC() returns a pointer to a CDC object.
To do what you want you can do either of the following. The first choice fits more into how MFC likes to do things, but both work just fine:
CDC *pDC = GetDC();
// Option 1
CDC memDC;
memDC.CreateCompatibleDC(pDC);
// Option 2
HDC hMemDC = CreateCompatibleDC((HDC)(*pDC));
It is important to note that option 2 does not do the same thing that you're currently doing wrong. The CDC class has an operator HDC() member that allows it to be converted to an HDC, but this does NOT apply to the pointer. You must dereference it first.
|
2,909,604 | 2,909,748 | Bona fide transiant windows with WinAPI? | I want to create a Window like when a context menu pops up or clicking the menubar. I want a Window that will be like this and that I can take over its paint event. Sort of like what is created when you select a sub tool in Photoshop.
EDIT:I want to know how to create controls like the one that comes when you select a sub tool in Photoshop, these do not seem to have a parent window. Those little description popups are a good example of this type of window, and menu items, those rectangles have no parent window.
Thanks
EDIT2: see this: http://cdn-viper.demandvideo.com/media/CB3C805F-421E-45AE-8359-39D59D8F0165/jpeg/20412728-192C-462A-AF8E-1F30BA77AE05_2.jpg
You will notice the window for the sub tools, it is not constrained to a parent window.
|
But how do they get a nice shadow
around it, and how does it still stay
with the main window without a parent?
That's your real question.
There are several ways of getting the shadow. One is that the window is actually two windows, the "shadow" plus the "main" window.
When you create the flyout window (that's what it's called), you position it near the toolbar. If the toolbar gets a WM_MOVE message, it's your responsibility to call MoveWindow() on the flyout to keep it lined up.
Edited to add
The dwExStyle parameter of CreateWindowEx() should include WS_EX_LAYERED and probably WS_EX_TRANSPARENT, because the 'shadow' will use alpha blending. The hWndParent parameter is the application's main window. The x and y parameters must be calculated as an offset of whatever button the window is to be associated with.
|
2,909,746 | 2,909,806 | weird performance in C++ (VC 2010) | I have this loop written in C++, that compiled with MSVC2010 takes a long time to run. (300ms)
for (int i=0; i<h; i++) {
for (int j=0; j<w; j++) {
if (buf[i*w+j] > 0) {
const int sy = max(0, i - hr);
const int ey = min(h, i + hr + 1);
const int sx = max(0, j - hr);
const int ex = min(w, j + hr + 1);
float val = 0;
for (int k=sy; k < ey; k++) {
for (int m=sx; m < ex; m++) {
val += original[k*w + m] * ds[k - i + hr][m - j + hr];
}
}
heat_map[i*w + j] = val;
}
}
}
It seemed a bit strange to me, so I did some tests then changed a few bits to inline assembly: (specifically, the code that sums "val")
for (int i=0; i<h; i++) {
for (int j=0; j<w; j++) {
if (buf[i*w+j] > 0) {
const int sy = max(0, i - hr);
const int ey = min(h, i + hr + 1);
const int sx = max(0, j - hr);
const int ex = min(w, j + hr + 1);
__asm {
fldz
}
for (int k=sy; k < ey; k++) {
for (int m=sx; m < ex; m++) {
float val = original[k*w + m] * ds[k - i + hr][m - j + hr];
__asm {
fld val
fadd
}
}
}
float val1;
__asm {
fstp val1
}
heat_map[i*w + j] = val1;
}
}
}
Now it runs in half the time, 150ms. It does exactly the same thing, but why is it twice as quick? In both cases it was run in Release mode with optimizations on. Am I doing anything wrong in my original C++ code?
| I suggest you try different floating-point calculation models supported by the compiler - precise, strict or fast (see /fp option) - with your original code before making any conclusions. I suspect that your original code was compiled with some overly restrictive floating-point model (not followed by your assembly in the second version of the code), which is why the original is much slower.
In other words, if the original model was indeed too restrictive, then you were simply comparing apples to oranges. The two versions didn't really do the same thing, even though it might seem so at the first sight.
Note, for example, that in the first version of the code the intermediate sum is accumulated in a float value. If it was compiled with precise model, the intermediate results would have to be rounded to the precision of float type, even if the variable val was optimized away and the internal FPU register was used instead. In your assembly code you don't bother to round the accumulated result, which is what could have contributed to its better performance.
I'd suggest you compile both versions of the code in /fp:fast mode and see how their performances compare in that case.
|
2,909,953 | 2,909,959 | Is there any way to use VC++ 2010 without including stdafx.h? | I've successfully installed M$ VC2010 and start writing simple programs using it.
I am very annoyed from the #include<stdafx.h>, So is there any way to compile and run programs without it???
| It's for pre-compiled headers. Don't use pre-compiled headers, don't include it.
|
2,909,957 | 2,915,522 | Why this base64 function stop working when increasing max length? | I am using this class to encode/decode text to base64.
It works fine with MAX_LEN up to 512 but if I increase it to 1024 the decode function returns and empty var.
This is the function:
char* Base64::decode(char *src)
{
unsigned six, dix;
unsigned int d_len = MAX_LEN;
memset(dst,'\0', MAX_LEN);
unsigned s_len = strlen(src);
dix = 0;
for (six = 0; six < s_len; six += 4)
{
unsigned long sr;
unsigned ix;
sr = 0;
for (ix = 0; ix < 4; ++ix)
{
int sextet;
if (six+ix >= s_len)
return NULL;
if ((sextet = tlu(*(src+six+ix))) < 0)
break;
sr <<= 6;
sr |= (sextet & 0x3f);
}
switch (ix)
{
case 0: // end of data, no padding
return 0;
case 1: // can't happen
return NULL;
case 2: // 1 result byte
sr >>= 4;
if (dix > d_len) return NULL;
*(dst+dix) = (sr & 0xff);
++dix;
break;
case 3: // 2 result bytes
sr >>= 2;
if (dix+1 > d_len) return NULL;
*(dst+dix+1) = (sr & 0xff);
sr >>= 8;
*(dst+dix) = (sr & 0xff);
dix += 2;
break;
case 4: // 3 result bytes
if (dix+2 > d_len) return NULL;
*(dst+dix+2) = (sr & 0xff);
sr >>= 8;
*(dst+dix+1) = (sr & 0xff);
sr >>= 8;
*(dst+dix) = (sr & 0xff);
dix += 3;
break;
}
}
return dst;
}
Why could be causing this?
| Odds are dst is not sized correctly to hold all 1024 bytes. Without seeing dst's declaration there is no way to be sure.
|
2,909,991 | 2,910,102 | Compiling cpp code in netbeans produce errors, how to solve it? | i use the netbeans with MinGW and MYSY make /debugger but when i compile a basic cpp code in it and run it it produces two erorrs
this is the code runned and the output![alt text][1] box
#include <iostream>
void main()
{
cout << "Hello World!" << endl;
cout << "Welcome to C++ Programming" << endl;
}
output is
/usr/bin/make -f nbproject/Makefile-Debug.mk SUBPROJECTS= .build-conf
make[1]: Entering directory `/d/Users/Home/Documents/NetBeansProjects/newApp'
/usr/bin/make -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/newapp.exe
make[2]: Entering directory `/d/Users/Home/Documents/NetBeansProjects/newApp'
mkdir -p dist/Debug/MinGW-Windows
g++.exe -o dist/Debug/MinGW-Windows/newapp build/Debug/MinGW-Windows/newmain.o build/Debug/MinGW-Windows/newfile.o build/Debug/MinGW-Windows/main.o
build/Debug/MinGW-Windows/newfile.o: In function `main':
D:/Users/Home/Documents/NetBeansProjects/newApp/newfile.cpp:5: multiple definition of `main'
build/Debug/MinGW-Windows/newmain.o:D:/Users/Home/Documents/NetBeansProjects/newApp/newmain.c:15: first defined here
build/Debug/MinGW-Windows/main.o: In function `main':
D:/Users/Home/Documents/NetBeansProjects/newApp/main.cpp:13: multiple definition of `main'
build/Debug/MinGW-Windows/newmain.o:D:/Users/Home/Documents/NetBeansProjects/newApp/newmain.c:15: first defined here
collect2: ld returned 1 exit status
make[2]: *** [dist/Debug/MinGW-Windows/newapp.exe] Error 1
make[2]: Leaving directory `/d/Users/Home/Documents/NetBeansProjects/newApp'
make[1]: *** [.build-conf] Error 2
make[1]: Leaving directory `/d/Users/Home/Documents/NetBeansProjects/newApp'
make: *** [.build-impl] Error 2
BUILD FAILED (exit value 2, total time: 1s)
how can i solve this ?
| I can see three things here, the first two have been pointed out by Xavier and jwismar, but to consolidate:
Both D:/Users/Home/Documents/NetBeansProjects/newApp/newfile.cpp and D:/Users/Home/Documents/NetBeansProjects/newApp/main.cpp define a main(). You'll need to remove one of these from your project.
You'll need to be using std::cout and using std::endl.
main() should always return an int.
|
2,910,157 | 2,910,180 | Can't inherit from auto_ptr without problems | What I want to do is this:
#include <memory>
class autostr : public std::auto_ptr<char>
{
public:
autostr(char *a) : std::auto_ptr<char>(a) {}
autostr(autostr &a) : std::auto_ptr<char>(a) {}
// define a bunch of string utils here...
};
autostr test(char a)
{
return autostr(new char(a));
}
void main(int args, char **arg)
{
autostr asd = test('b');
return 0;
}
(I actually have a copy of the auto_ptr class that handles arrays as well, but the same error applies to the stl one)
The compile error using GCC 4.3.0 is:
main.cpp:152: error: no matching function for call to `autostr::autostr(autostr)'
main.cpp:147: note: candidates are: autostr::autostr(autostr&)
main.cpp:146: note: autostr::autostr(char*)
I don't understand why it's not matching the autostr argument as a valid parameter to autostr(autostr&).
| The autostr that is returned from the function is a temporary. Temporary values can only be bound to references-to-const (const autostr&), but your reference is non-const. (And "rightly so".)
This is a terrible idea, almost none of the standard library is intended to be inherited from. I already see a bug in your code:
autostr s("please don't delete me...oops");
What's wrong with std::string?
|
2,910,318 | 2,910,749 | Global variable not stable after platform changed | Our embedded system is built on a hw/sw platform made by enea. After the platform updated recently, we found some operations on the global variable keep crashing the system.
For example, we have a global map structure holding some data. We can insert/iterate the map once or twice, then the address of the elements in the map suddenly changed to some forbidden addresses like 0x0 or 0x1d, the system just crash.
The only different before/after the platform update is :
1) sw part: It's a c++ software and We changed the compiler from diab cc to gcc.
2) hw part: we have a new board, but the cpu is still powerpc405s.
I tried every possible way but still can't figure out the reason. Any thoughts?
| A known issue with globals is order of initialization. This order is generally not defined. As a result, you may see crashes if the ctor of one global tries to use another global. In your case, the problem may be that GCC has decided to initialize the map later, after the point where you're using it.
A quick solution can be to replace the global with a singleton:
MyClass& MyClass::instance() {
static MyClass singleton;
return singleton;
}
singleton is created before the function returns, and therefore certainly before it's used.
|
2,910,377 | 2,910,392 | Get home directory in Linux | I need a way to get user home directory in C++ program running on Linux. If the same code works on Unix, it would be nice. I don't want to use HOME environment value.
AFAIK, root home directory is /root. Is it OK to create some files/folders in this directory, in the case my program is running by root user?
| You need getuid to get the user id of the current user and then getpwuid to get the password entry (which includes the home directory) of that user:
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
Note: if you need this in a threaded application, you'll want to use getpwuid_r instead.
|
2,910,428 | 2,910,438 | Switch/Case statements in C++ | Regarding the switch/case statement in the C++ code below: "Case 1" is obviously false, so how/why does it enter the do-while loop?
#include <iostream>
using namespace std;
int main() {
int test = 4;
switch(test) {
case 1: do {
case 2: test++;
case 3: test++;
case 4: cout << "How did I get inside the do-while loop?" << endl; break;
case 5: test++;
} while(test > 0);
cout << test << endl;
}
}
| This is Duff's Device, which is an old, clever technique for jumping into the middle of a loop.
|
2,910,557 | 2,911,355 | Eliminating inherited overlong MACRO | I have inherited a very long set of macros from some C algorithm code.They basically call free on a number of structures as the function exits either abnormally or normally. I would like to replace these with something more debuggable and readable. A snippet is shown below
#define FREE_ALL_VECS {FREE_VEC_COND(kernel);FREE_VEC_COND(cirradCS); FREE_VEC_COND(pixAccum).....
#define FREE_ALL_2D_MATS {FREE_2D_MAT_COND(circenCS); FREE_2D_MAT_COND(cirradCS_2); }
#define FREE_ALL_IMAGES {immFreeImg(&imgC); immFreeImg(&smal.....
#define COND_FREE_ALLOC_VARS {FREE_ALL_VECS FREE_ALL_2D_MATS FREE_ALL_IMAGES}
What approach would be best? Should I just leave well alone if it works? This macro set is called twelve times in one function. I'm on Linux with gcc.
| If they are broken then fix them by converting to functions.
If they're aren't broken then leave them be.
If you are determined to change them, write unit-tests to check you don't inadvertently break something.
|
2,910,587 | 2,910,694 | delete vs NULL vs free in c++ | what is the difference between deleting a pointer, setting it to null, and freeing it.
delete ptr;
vs.
ptr=NULL;
vs.
free(ptr);
| Your question suggests that you come from a language that has garbage collection. C++ does not have garbage collection.
If you set a pointer to NULL, this does not cause the memory to return to the pool of available memory. If no other pointers point to this block of memory, you now simply have an "orphaned" block of memory that remains allocated but is now unreachable -- a leak. Leaks only cause a program to crash if they build up to a point where no memory is left to allocate.
There's also the converse situation, where you delete a block of memory using a pointer, and later try to access that memory as though it was still allocated. This is possible because calling delete on a pointer does not set the pointer to NULL -- it still points to the address of memory that previously was allocated. A pointer to memory that is no longer allocated is called a dangling pointer and accessing it will usually cause strange program behaviour and crashes, since its contents are probably not what you expect -- that piece of memory may have since been reallocated for some other purpose.
[EDIT] As stinky472 mentions, another difference between delete and free() is that only the former calls the object's destructor. (Remember that you must call delete on an object allocated with new, and free() for memory allocated with malloc() -- they can't be mixed.) In C++, it's always best to use static allocation if possible, but if not, then prefer new to malloc().
|
2,910,836 | 2,911,350 | How do I read long lines from a text file in C++? | I am using the following code for reading lines from a text-file. What is the best method for handling the case where the line is greater than the limit SIZE_MAX_LINE?
void TextFileReader::read(string inFilename)
{
ifstream xInFile(inFilename.c_str());
if(!xInFile){
return;
}
char acLine[SIZE_MAX_LINE + 1];
while(xInFile){
xInFile.getline(acLine, SIZE_MAX_LINE);
if(xInFile){
m_sStream.append(acLine); //Appending read line to string
}
}
xInFile.close();
}
| Don't use istream::getline(). It deals with naked character buffers and is therefor prone to errors. Better use std::getline(std::istream&,std::string&, char='\n') from the <string> header:
std::string line;
while(std::getline(xInFile, line)) {
m_sStream.append(line);
m_sStream.append('\n'); // getline() consumes '\n'
}
|
2,910,979 | 2,913,870 | How does `is_base_of` work? | How does the following code work?
typedef char (&yes)[1];
typedef char (&no)[2];
template <typename B, typename D>
struct Host
{
operator B*() const;
operator D*();
};
template <typename B, typename D>
struct is_base_of
{
template <typename T>
static yes check(D*, T);
static no check(B*, int);
static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes);
};
//Test sample
class Base {};
class Derived : private Base {};
//Expression is true.
int test[is_base_of<Base,Derived>::value && !is_base_of<Derived,Base>::value];
Note that B is private base. How does this work?
Note that operator B*() is const. Why is it important?
Why is template<typename T> static yes check(D*, T); better than static yes check(B*, int); ?
Note: It is reduced version (macros are removed) of boost::is_base_of. And this works on wide range of compilers.
| If they are related
Let's for a moment assume that B is actually a base of D. Then for the call to check, both versions are viable because Host can be converted to D* and B*. It's a user defined conversion sequence as described by 13.3.3.1.2 from Host<B, D> to D* and B* respectively. For finding conversion functions that can convert the class, the following candidate functions are synthesized for the first check function according to 13.3.1.5/1
D* (Host<B, D>&)
The first conversion function isn't a candidate, because B* can't be converted to D*.
For the second function, the following candidates exist:
B* (Host<B, D> const&)
D* (Host<B, D>&)
Those are the two conversion function candidates that take the host object. The first takes it by const reference, and the second doesn't. Thus the second is a better match for the non-const *this object (the implied object argument) by 13.3.3.2/3b1sb4 and is used to convert to B* for the second check function.
If you would remove the const, we would have the following candidates
B* (Host<B, D>&)
D* (Host<B, D>&)
This would mean that we can't select by constness anymore. In an ordinary overload resolution scenario, the call would now be ambiguous because normally the return type won't participate in overload resolution. For conversion functions, however, there is a backdoor. If two conversion functions are equally good, then the return type of them decides who is best according to 13.3.3/1. Thus, if you would remove the const, then the first would be taken, because B* converts better to B* than D* to B*.
Now what user defined conversion sequence is better? The one for the second or the first check function? The rule is that user defined conversion sequences can only be compared if they use the same conversion function or constructor according to 13.3.3.2/3b2. This is exactly the case here: Both use the second conversion function. Notice that thus the const is important because it forces the compiler to take the second conversion function.
Since we can compare them - which one is better? The rule is that the better conversion from the return type of the conversion function to the destination type wins (again by 13.3.3.2/3b2). In this case, D* converts better to D* than to B*. Thus the first function is selected and we recognize the inheritance!
Notice that since we never needed to actually convert to a base class, we can thereby recognize private inheritance because whether we can convert from a D* to a B* isn't dependent on the form of inheritance according to 4.10/3
If they are not related
Now let's assume they are not related by inheritance. Thus for the first function we have the following candidates
D* (Host<B, D>&)
And for the second we now have another set
B* (Host<B, D> const&)
Since we cannot convert D* to B* if we haven't got a inheritance relationship, we now have no common conversion function among the two user defined conversion sequences! Thus, we would be ambiguous if not for the fact that the first function is a template. Templates are second choice when there is a non-template function that is equally good according to 13.3.3/1. Thus, we select the non-template function (second one) and we recognize that there is no inheritance between B and D!
|
2,911,154 | 2,911,438 | Custom (pool) allocator with boost shared_ptr | I want objects managed by a shared_ptr to be allocated from a pool, say Boost's Pool interface, how can this be achieved?
| Here's the code to do what you want (probably won't compile as I don't have boost on hand and I'm writing it from memory):
class YourClass; // your data type, defined somewhere else
boost::object_pool<YourClass> allocator;
void destroy(YourClass* pointer)
{
allocator.destroy(pointer);
}
boost::shared_ptr<YourClass> create()
{
// usage of object_pool<??>::construct requires that you have a
// YourClass::YourClass(void) defined. If you need to pass arguments
// to the new instance, you need to do that separately.
//
// for example using a YourClass::Initialize(your,parameters,here) method
// before returning from this function
return boost::shared_ptr<YourClass>( allocator.construct(), &destroy );
}
// usage:
boost::shared_ptr<YourClass> newObject = create();
I implemented this twice, in two different projects. In both, the create and destroy functions were synchronized (you can add a boost::mutex lock around the use of allocator) and they were members of a factory class (and the destroy's signature was modified to void (YourClass*) through the usage of boost::bind).
You can also avoid writing two extra functions (the destroy and create) by binding object_pool<YourClass>::destroy dirrectly in the boost::shared_ptr constructor.
I'm too lazy to write all that now :).
Edit (moved my answer comment in here for the code formatting):
To bind the destroy function:
class ClassFactory
{
boost::object_pool<YourClass> allocator;
public:
boost::shared_ptr<YourClass> create()
{
return boost::shared_ptr<YourClass>(
allocator.construct(),
boost::bind(&ClassFactory::destroy, this, _1) );
}
void destroy(YourClass* pointer)
{
allocator.destroy(pointer);
}
};
ClassFactory should have a longer lifetime than the shared_ptr (if the ClassFactory instance is deleted, the this pointer passed to the shared_ptr instance will be invalid - and crash your app when the shared_ptr deletes the YourClass instance).
|
2,911,318 | 2,911,329 | Find the "name" of a library (-L -l switches) | Being fairly new to C++ I have a question bascially concerning the g++ compiler and especially the inclusion of libraries. Consider the following makefile:
CPPFLAGS= -I libraries/boost_1_43_0-bin/include/ -I libraries/jpeg-8b-bin/include/
LDLIBS= libraries/jpeg-8b-bin/lib/libjpeg.a
# LDLIBS= -L libraries/jpeg-8b-bin/lib -llibjpeg
all: main
main: main.o
c++ -o main main.o $(LDLIBS)
main.o: main.cpp
c++ $(CPPFLAGS) -c main.cpp
clean:
rm -rf *.o main
As you can see I declared the LDLIBS variable twice. My code is compiling and working if I use the makefile above. But if I deactivate the first LDLIBS entry and active the second one I get ld: library not found for -llibjpeg. I assume my libjpeg.a is just not called libjpeg but bears some different name.
Is there a way to find out the name of a given "libraryfile" libsomething.a or libsomething.dyn?
Ok, thanks for all your answers, it is working now.
One little question remains: Is it a convention to simply leave out "lib" or is there a standardized way to find out the name?
| You don't need the lib part if you use the -l switch.
LDLIBS=-Llibraries/jpeg-8b-bin/lib -ljpeg
# ^^^^
Whenever you write -lxxx, the linker will look for a library with filename libxxx.<ext> in all supplied library paths. This is the standard convention of ld, and should be true for most UNIX-based linkers.
|
2,911,442 | 2,911,504 | Access variable value using string representing variable's name in C++ | If the title was not clear, I will try to clarify what I am asking:
Imagine I have a variable called counter, I know I can see its current value by doing something like:
std::cout << counter << std::endl;
However, assume I have lots of variables and I don't know which I'm going to want to look at until runtime.
Does anyone know a way I can fetch the value of a variable by using its name, for example:
std::cout << valueOf("counter") << std::endl;
I feel being able to do this might make debugging large complex projects easier.
Thanks in advance for your time.
Update: All the answers provided are valid and useful, however the main point is that reflection does not exist in C++ (and after reading the link recommended it is clear why).
| As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
|
2,911,448 | 2,914,348 | structures, inheritance and definition | i need to help with structures, inheritance and definition.
//define struct
struct tStruct1{
int a;
};
//definition
tStruct1 struct1{1};
and inheritance
struct tStruct2:tStruct1{
int b;
};
How can I define it in declaration line?
tStruct2 struct2{ ????? };
One more question, how can i use inheritance for structures defined with typedef struct?
| First off, the typedef for a structure doesn't change anything, it only introduces an alternative name for the type. You can still inherit from it as usual.
The Type identifier{params} syntax for definitions is C++0x syntax for the new uniform initialization. In pre-C++0x you have two choices for initialization of user-defined types.
Aggregate Initialization
Aggregates are POD types and arrays of PODs or built-in types. They can be initialized using initializer lists with curly braces:
struct A {
int i;
};
struct B {
A j;
int k;
};
B b = {{1}, 2 };
This is covered in more detail in this InformIT article.
As noted this only works for POD-types and thus doesn't work when inheritance comes into play. In that case you have to use
User-defined constructors
They allow you to initialize your custom types rather freely by defining special member functions:
struct A {
int i;
A(int number) : i(number) {}
};
struct B : A {
int j;
B(int number1, number2) : A(number1), j(number2) {}
};
B b(1, 2);
Constructors are covered in more detail in this InformIT article.
|
2,911,482 | 2,911,520 | Better name needed for applying a function on elements of a container | I have a container class (containing a multi-index container) for which I have a public "foreach" member-function, so users can pass a functor to apply on all elements.
While implementing, I had a case where the functor should only be applied to some elements of a range in the container, so I overloaded the foreach, to pass some valid range.
Now, in some cases, it was worthwhile to stop on a certain condition, so practically, I let the foreach stop based on the return-value of the function.
I'm pleased with how the system works, but I have one concern:
How should a "foreach" on a range, with stop conditions be called?
Anyone knows a generic, clear and concise name?
| Based on your description, i'd go for apply_until().
|
2,911,639 | 2,911,669 | Interrupt mechanism in C,C++ | Hey I was writing a udp client server in which a client waits for packets from server.But I want to limit this wait for certain time.After client don't get response for a certain moment in raise an alarm,basically it comes out and start taking remedy steps.So what are the possible solution for it.I think writing a wrapper around recv will work but how exactly this has to be done,I mean how will make recv raise alarm for you after that time limit.
Any Help in this regard will be appreciated.
Thanks!
| If you want to do socket communications with timeouts, then select is the way to go.
You basically set up arrays of file descriptors for various events such as read-ready or write-able, then call select with a timeout. If one of the events is valid, you will be notified and you can perform your actions.
If none of the events occurs before the timeout, you'll still be notified and can take whatever remedial action you see fit.
See here for the gory details, expanded on below.
Alternatively, you can use setsockopt with the SO_RCVTIMEO:
struct timeval tv;
tv.tv_sec = 5;
tv.tv_used = 0;
setsockopt (socket_id, SOL_SOCKET, SO_RCVTIMEO,
&tv, sizeof(struct timeval));
For details on select, you use the FD_ZERO and FD_SET macros to construct a set of file descriptors (fdsets) of interest to you. You can have three sets, one indicating whether one or more fds has data to read, one indicating whether one or more is ready for writing to, and one indicating errors. You may not necessarily have all three, it depends on what your code is doing.
Once you've set up the fdsets, you pass them, along with the number of fds and a timeout, to select which weaves its magic and returns to you. Before you do this, make a copy (FD_COPY) of the fdsets for later recovery.
On return, there's either been an error, timeout or an event pertaining to one of the fds of interest. In that latter case, the fdsets have been modified to only have the fds set for those with an event and you can use FD_ISSET to detect which ones.
Then, once you've handled all the events, use FD_COPY to restore the original fdsets (they were modified by select, remember) and call select again. Continue for as long as you need to.
Keep in mind that an error return from select is not necessarily fatal. You can get (in errno) EAGAIN for a temporary resource shortage or EINTR if a signal was handled. For that second case, you can just re-enter the select call. For the first, I'd implement a retry loop in case it was just a temporary thing.
|
2,911,703 | 2,919,167 | crash when using stl vector at instead of operator[] | I have a method as follows (from a class than implements TBB task interface - not currently multithreading though)
My problem is that two ways of accessing a vector are causing quite different behaviour - one works and the other causes the entire program to bomb out quite spectacularly (this is a plugin and normally a crash will be caught by the host - but this one takes out the host program as well! As I said quite spectacular)
void PtBranchAndBoundIterationOriginRunner::runOrigin(int origin, int time) const // NOTE: const method
{
BOOST_FOREACH(int accessMode, m_props->GetAccessModes())
{
// get a const reference to appropriate vector from member variable
// map<int, vector<double>> m_rowTotalsByAccessMode;
const vector<double>& rowTotalsForAccessMode = m_rowTotalsByAccessMode.find(accessMode)->second;
if (origin != 129) continue; // Additional debug constrain: I know that the vector only has one non-zero element at index 129
m_job->Write("size: " + ToString(rowTotalsForAccessMode.size()));
try {
// check for early return... i.e. nothing to do for this origin
if (!rowTotalsForAccessMode[origin]) continue; // <- this works
if (!rowTotalsForAccessMode.at(origin)) continue; // <- this crashes
} catch (...) {
m_job->Write("Caught an exception"); // but its not an exception
}
// do some other stuff
}
}
I hate not putting in well defined questions but at the moment my best phrasing is : "WTF?"
I'm compiling this with Intel C++ 11.0.074 [IA-32] using Microsoft (R) Visual Studio Version 9.0.21022.8 and my implementation of vector has
const_reference operator[](size_type _Pos) const
{ // subscript nonmutable sequence
#if _HAS_ITERATOR_DEBUGGING
if (size() <= _Pos)
{
_DEBUG_ERROR("vector subscript out of range");
_SCL_SECURE_OUT_OF_RANGE;
}
#endif /* _HAS_ITERATOR_DEBUGGING */
_SCL_SECURE_VALIDATE_RANGE(_Pos < size());
return (*(_Myfirst + _Pos));
}
(Iterator debugging is off - I'm pretty sure) and
const_reference at(size_type _Pos) const
{ // subscript nonmutable sequence with checking
if (size() <= _Pos)
_Xran();
return (*(begin() + _Pos));
}
So the only difference I can see is that at calls begin instead of simply using _Myfirst - but how could that possibly be causing such a huge difference in behaviour?
UPDATE:
The index is within range - the size is printed out as 377 and the index is constrained to 129.
The member variable has an entry corresponding to accessMode
The entire thing has been wrapped in the following to clarify @nikko suggestion:
map<int, vector<double>>::const_iterator it = m_rowTotalsByAccessMode.find(accessMode);
if (it != m_rowTotalsByAccessMode.end())
{
...
UPDATE I've upgraded my compiler to the latest version 11.1.065 and this is no longer happening. Looks like it was weirdness somewhere.
| I hate answering my own questions but this seems to be a situation where it is required. As it says in the update, I downloaded and installed the latest intel c++ compiler and recompiled from scratch which seems to have fixed the problem. I've also rebuilt the entire project from scratch using the 11.0.074 compiler to rule out a corruption of one of the binaries; even a clean build results in the crash!
I'm going to follow this up on the Intel forums, thanks to everyone who put in some time and effort to this problem.
|
2,911,798 | 5,995,994 | FFMpeg encoding RGB images to H264 | I'm developing a DirectShow filter which has 2 input pins (1 for audio, 1 for video). I'm using libavcodec/libavformat/libavutil of FFMpeg for encoding the video to H264, audio to AAC and mux it/stream using RTP. So far I was able to encode video and audio correctly using libavcodec but now I see that FFMpeg seems to support RTP muxing too. Unfortunatelly, I can't find any example code which shows how to perform H264 encoding and RTP muxing. Does anybody know good samples?
| Try checking out the code in HandBrake. Specifically, this file muxmp4.c, which was a jem I found working with FFMpeg / RTP. Be sure and use av_interleaved_write_frame() and the extradata fields correctly. Those were some key differences I remember for RTP.
Still, I had some stability issues with RTP/RTSP with FFMpeg, (I'm sure it's getting better). I had much better luck with live555, and you can look at the code in VLC and MPlayer for good examples on how to use it.
|
2,911,932 | 2,928,803 | CRXIR2 doesn't work with VS2010 on Windows 7 nor on Vista | We're upgrading from VS2005 to VS2010.
We are almost there but there is a problem with Crystal Reports.
We use the RDC (COM-based) component within our C++ application.
On Windows 7 or on VISTA, I can't get the viewer nor the designer controls working.
I get Access Violations when the control is activated:
// from atlhost.h (line 2208)
hr = m_spOleObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, spClientSite, 0, m_hWnd, &m_rcPos);
The strange thing is that when I run the same exe on a XP machine, it seems to work.
We basically use "AtlAxWin100" window class to host the Crystal report control ("CrystalReports11.ActiveXReportViewer.1") in.
I'm using the SP6 version of Crystal reports so that's the latest version.
Also, when I compile the same code with VS2005 and run it on Windows7 or Vista everything works out just fine.
Does anybody have any idea about what might cause the problem, or ideas for further investigations?
| it looks like it has something to do with DEP.
If we turn off the DEP completely on the system with
bcdedit /set Nx AlwaysOff
and then reboot of course,
the Viewer works!
Unfortunately this is a system global turn off.
We tried to turn off DEP for our exe alone before, but then we got a message from Windows that we were not allowed to turn off DEP for our exe...
|
2,912,037 | 2,912,108 | Strange realloc behaviour | i'm developing an array structure just for fun.
This structure, generalized by a template parameter, pre allocates a given number of items at startup, then, if "busy" items are more than available ones, a function will realloc the inner buffer .
The testing code is :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
template <typename T> struct darray_t {
size_t items;
size_t busy;
T *data;
};
#define DARRAY_REALLOC_ITEMS_STEP 10
#define da_size(da) (da)->busy
template <typename T>
void da_init( darray_t<T> *da, size_t prealloc ){
da->items = prealloc;
da->busy = 0;
da->data = (T *)malloc( sizeof(T) * prealloc );
}
template <typename T> T *da_next( darray_t<T> *da ){
if( da->busy >= da->items ){
da->data = (T *)realloc( da->data, sizeof(T) * DARRAY_REALLOC_ITEMS_STEP );
da->items += DARRAY_REALLOC_ITEMS_STEP;
}
return &da->data[ da->busy++ ];
}
int main(){
darray_t<int> vi;
int *n;
da_init( &vi, 100 );
for( int i = 0; i < 101; ++i ){
n = da_next(&vi);
*n = i;
}
for( int i = 0; i < da_size(&vi); ++i ){
if( vi.data[i] != i ){
printf( "!!! %d != %d\n", i, vi.data[i] );
}
}
return 0;
}
As you can see, i prealloc 100 integer pointers at the beginning and then i realloc them with 10 more pointers at time.
In the main function, i perform a for loop to check items integrity and, if an array item is not as i expect, i print its value and ... you know what ?
I have the following message :
!!! 11 != 135121
In fact, item at index 11, that should be '11', is 135121 !!!! :S
Can you tell me if my code is not correct?
Thanks
NOTE
I perfectly know that mixing C and C++ this way is ugly, and i know too that this structure would screw up if used, for instance :
darray_t<std::string>
This is just a test for int pointers.
| realloc does not automatically grow the piece of memory - you'll have to do that. Do e.g.:
da->data=(T*)realloc(da->data, sizeof(T)*(da->items+DARRAY_REALLOC_ITEMS_STEP));
(and you should handle realloc returning NULL)
|
2,912,266 | 2,912,524 | What does this C++ code mean | I was trying to understand how webkit parses urls, and I'm having a hard time making heads or tails of this:
Vector<char, 4096> buffer(fragmentEnd * 3 + 1);
This line is on line 1214 (you can see it here: http://trac.webkit.org/browser/trunk/WebCore/platform/KURL.cpp#L1214). I get that it's making a vector of type char, with each entry being an array of char 4096 bytes large, but I don't get the buffer(fragmentEnd * 3 + 1) part.
I think that it confuses me most b/c I can't find where the buffer variable is instantiated anywhere (shouldn't it be something more like Vector<char, 4096> buffer = new Vector<char, 4096>(...)?
Thanks in advance
| The buffer variable is constructed exactly on that line:
Vector<char, 4096> buffer(fragmentEnd * 3 + 1);
Walking through the steps that the compiler takes, it first ensures that there are sizeof(Vector<char, 4096>) bytes of space on the stack into which it can construct the Vector<char, 4096> buffer object. It then calls a Vector<char, 4096> constructor that can take an int (because fragmentEnd * 3 + 1 is an int) on the storage in the stack.
In the current Vector sources, there is no constructor that takes an int. However, there is a constructor that takes a size_t (an unsigned int), so the compiler will statically cast the result fragmentEnd * 3 + 1 to a size_t and invoke that constructor.
|
2,912,404 | 2,912,453 | How does py2exe actually -and simply explained- work? :) | I have a c++ app that calls another python one (bundled into an exe with py2exe)
So I have 2 apps.
So I was wondering: What if my c++ did what py2exe does?
i.e. embed the python app in the c++ one. This way I won't depend on py2exe and its
configurations nighmares (yes, it has some)
Hence my questions:
how does py2exe work (so I can do its job with my c++ app)
What about just embedding the whole python app with the c++? I read the python doc about embedding, did an example (a very simple one that does PyRun_SimpleString) but what about a whole python app with tons of modules? (zipimport maybe?)
I'd love to hear how you'd do that.
Thanks a lot! :)
| http://www.py2exe.org/index.cgi/FAQ
Basically, it packages up your python install and redistributes it. It still runs your Python as Python on a Python interpreter. The exe it creates just kicks everything off.
The Python website has some methods on integrating with C++.
|
2,912,445 | 2,912,454 | How to discard const in c++ | This is what I'm trying to do and I can't:
#include <string>
using namespace std;
class A {
public:
bool has() const { return get().length(); }
string& get() { /* huge code here */ return s; }
private:
string s;
};
The error I'm getting is:
passing ‘const A’ as ‘this’ argument of
‘std::string& A::get()’ discards qualifiers
I understand what the problem is, but how can I fix it? I really need has() to be const. Thanks.
| Add a second overload of get():
string const & get() const { return s; }
That will be called on a const typed object of class A.
In practice, I prefer adding only const-typed accessors, and then keeping modifications entirely internal to the class or even avoid them entirely. For example, that means having a method DoUpdateLabel(){/*do something with s*/} rather than expose the internals. That has the nice side effect that you can avoid duplicating accessors in many cases.
If you absolutely must have modification via accessors and you also don't want an extra const wrapper, you can use const_cast<>:
bool has() const { return const_cast<A*>(this)->get().length(); }
However, if get() has side-effects and has() is declared const, it's questionable whether this is behavior you really want.
|
2,912,481 | 2,912,536 | How should I compile boost library in a small project? | I have a small project where I need just part of boost library, boost::regex in particular. This is what I've done so far:
/include
/boost
/regex
/math
.. 189 dirs, files, etc.
/lib
/boost-regex
c_regex_traits.cpp
cpp_regex_traits.cpp
.. ~20 .cpp files
myprog.cpp
In my Makefile I compile all boost-regex .cpp files one by one, producing .obj files. Next, I'm building my project by means of compiling myprog.cpp together with all that .obj files from /lib/boost/regex.
The question is whether I'm doing everything correct? The size of my output file is rather big (~3.5Mb), while my code is extremely small (10 lines).
ps. My compiler:
$ c++ —version
i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659)
| Why not build regex library as a static lib and use it's features in your code by writing #include <boost/regex.hpp>?
This shouldn't affect the final size of your application, because compiler will take only those functions that are actually used in your app.
Also, precompiled boost libraries for different platforms can be found in the internet if you don't want to build them yourself. In that case what you have to do is just take the appropriate library and include the appropriate header.
|
2,912,520 | 2,912,614 | Read file-contents into a string in C++ |
Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?
In scripting languages like Perl, it is possible to read a file into a variable in one shot.
open(FILEHANDLE,$file);
$content=<FILEHANDLE>;
What would be the most efficient way to do this in C++?
| Like this:
#include <fstream>
#include <string>
int main(int argc, char** argv)
{
std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
return 0;
}
The statement
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
can be split into
std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
which is useful if you want to just overwrite the value of an existing std::string variable.
|
2,912,588 | 2,955,316 | Generating XML Documents from XML Schemas in C++ | Is there any easy way to create at least a template XML file using XML Schema? My main interest is bounded by C++, but discussions of other programming languages are also welcome.By the way I also use QT framework.
| You may have to write this yourself. There is no one way of getting an XML file from a Schema. If you can make domain-specific assumptions (e.g. how to populate data items, which items to choose in case of a choice, how often to insert domain-specific elements) then you will get a better instance document.
If you are working with C++, note that Xerces C++ allows you to load a schema and access its model (i.e. access it properly, not just load the schema as an XML document). I suggest you download it an check out the SCMPrint Sample. It will show you how to traverse a schema. You can then modify that to print out a sample XML file instead.
|
2,912,658 | 2,912,945 | C++0x: memory ordering | The current C++0x draft states on section 29.3.9 and 29.3.10, pages 1111-1112 that in the following example:
// Thread 1
r1 = y.load(memory_order_relaxed);
x.store(1, memory_order_relaxed);
// Thread 2
r2 = x.load(memory_order_relaxed);
y.store(1, memory_order_relaxed);
The outcome r1 = r2 = 1 is possible since the operations of each thread are relaxed and to unrelated addresses. Now my question is about the possible outcomes of the following (similar) example:
// Thread 1
r1 = y.load(memory_order_acquire);
x.store(1, memory_order_release);
// Thread 2
r2 = x.load(memory_order_acquire);
y.store(1, memory_order_release);
I think that in this case the outcome r1 = r2 = 1 is not possible. If it was possible, the load of y would synchronize-with (thus happen-before) the store to y. Similar to x, the load of x would happen-before the store to x. But the load of y is sequenced before (thus also happens-before) the store to x. This creates a cyclic happens-before relation which I think is not allowed.
| If we take time (or, instruction sequences if you like) to flow downward, just like reading code, then my understanding is that
An acquire fence allows other memory accesses to move downwards past the fence, but not upwards past the fence
A release fence allows other memory accesses to move upwards past the fence, but not downwards past the fence
In other words, if you have code like
acquire
// other stuff
release
then memory accesses may move from outside the acquire/release pair to the inside, but not the other way around (and they may not skip the acquire/release pair completely either).
With the relaxed consistency semantics in your first example in the question, the hardware can reorder memory accesses such that the stores enter the memory system before the loads, thus allowing r1=r2=1. With the acquire/release semantics in the second example, that reordering is prevented, and thus r1=r2=1 is not possible.
|
2,912,683 | 2,912,783 | SysRc enum values in c c++ | i am working on a project where i am using SysRc values as return values from some function like SUCCESS and FAILURE ond sum enums .
Now i want to know how to get them print?
| Building on top of Neil's post:
A switch statement is usually the way to go with enum values in C++. You could save some writing work by using #define-macros, but I personally avoid them.
enum E { foo, bar };
const char * ToStr( E e ) {
switch(e) {
case foo: return "foo";
case bar: return "bar";
};
throw std::runtime_error("unhandled enum-value"); // xxx
}
gcc will warn you about unhandled case values.
|
2,912,759 | 2,914,299 | How to design properly a hierarchy of classes using pointers in C++ | I am trying to improve my knowledge on program architecture and recently arised a question to me which is related with this pointers issues I posted recently.
The thing is that in a simple hierarchy in which you have Class A with a pointers to Class B and the last to Class C. Do not confuse the with the inheritage property of the Object Oriented programming but basically what I am saying is that Class C is the child of Class B and Class B is the child of Class A.
The point is that I want to be able to access directly from Class A to Class C (the grandson in the analogy) with pointers. Some other members pointed out this is poor design, basically because if a delete an instance of class C from class B collection would leave a pointer to "nothing" in the Class A collection. Then, how is this modelled properly?
Thank you a lot!
Julen.
| Instead of making class A aware of every class C, consider using the Composite Pattern:
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <stdexcept>
//------------------------------------------------------------------------------
class Component
{
public:
typedef boost::ptr_vector<Component> Children;
virtual void print() = 0;
// Other operations
virtual bool isLeaf() {return true;}
virtual Children& children()
{throw std::logic_error("Leaves can't have children");}
};
//------------------------------------------------------------------------------
class Composite : public Component
{
public:
void print()
{
BOOST_FOREACH(Component& child, children_)
{
child.print();
}
}
bool isLeaf() {return false;}
Children& children() {return children_;}
private:
Children children_;
};
//------------------------------------------------------------------------------
class Nut : public Component
{
public:
Nut(std::string info) : info_(info) {}
void print() {std::cout << info_ << std::endl;}
private:
std::string info_;
};
//------------------------------------------------------------------------------
class Bolt : public Component
{
public:
Bolt(std::string info) : info_(info) {}
void print() {std::cout << info_ << std::endl;}
private:
std::string info_;
};
//------------------------------------------------------------------------------
class Wheel : public Composite
{
public:
Wheel(std::string info) : info_(info) {}
void print()
{
std::cout << info_ << std::endl;
Composite::print();
}
private:
std::string info_;
};
//------------------------------------------------------------------------------
class Vehicle : public Composite
{
public:
Vehicle(std::string info) : info_(info) {}
void print()
{
std::cout << info_ << std::endl;
Composite::print();
std::cout << "\n\n";
}
private:
std::string info_;
};
//------------------------------------------------------------------------------
int main()
{
Wheel* wheel1 = new Wheel("Wheel1");
wheel1->children().push_back(new Nut("Nut11"));
wheel1->children().push_back(new Nut("Nut12"));
wheel1->children().push_back(new Bolt("Bolt11"));
wheel1->children().push_back(new Bolt("Bolt12"));
Wheel* wheel2 = new Wheel("Wheel2");
wheel2->children().push_back(new Nut("Nut21"));
wheel2->children().push_back(new Nut("Nut22"));
wheel2->children().push_back(new Bolt("Bolt21"));
wheel2->children().push_back(new Bolt("Bolt22"));
Vehicle bike("Bike");
bike.children().push_back(wheel1);
bike.children().push_back(wheel2);
bike.print();
}
This program outputs:
Bike
Wheel1
Nut11
Nut12
Bolt11
Bolt12
Wheel2
Nut21
Nut22
Bolt21
Bolt22
Note that when bike.print() is called, print is called recursively on all children. This is how you can perform operations on all children without the grand-parent knowing about all its children.
The Visitor Pattern works very well with the Composite pattern, so I suggest you read up on that one too. Especially if you have many operations that can be implemented in terms of more basic ones.
|
2,912,767 | 2,912,905 | Is it possible to cast object of class to void *? | I am trying to use qsort from STL to sort array of edge:
struct edge
{
int w,v,weight;
};
by weight. What I am trying is:
int compare_e(const void *a, const void *b)
{
return ( *(edge *)a->weight - *(edge *)b->weight );
};
But I get:
`const void*' is not a
pointer-to-object type
EDIT:
Ok thx, now my code is compiled but sort seems don't work 100%...
#include <cstdlib>
#include <iostream>
struct edge
{
int w,v,weight;
};
struct edge_ID:edge
{
int id;
};
int compare_e(const void *a, const void *b)
{
return ( ((edge *)a)->weight > ((edge *)b)->weight );
};
int main()
{
using namespace std;
edge *tab = new edge[100];
for(int i = 0; i < 100; i++)
{
tab[i].weight = rand() % 100;
cout << i << " => " << tab[i].weight << endl;
}
qsort(tab, 100, sizeof(edge), compare_e);
cout << "AFTER:" << endl;
for(int i = 0; i < 100; i++)
{
cout << i << " => " << tab[i].weight << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
I have some number in wrong place...
| struct less_by_weight
{
bool operator()(const edge& lhs, const edge& rhs) const
{
return lhs.weight < rhs.weight;
}
};
int main()
{
const std::size_t size = 100;
edge *tab = new edge[size];
for(int i = 0; i < size; ++i)
{
tab[i].weight = rand() % size;
std::cout << i << " => " << tab[i].weight << '\n';
}
std::sort( tab, tab+size, less_by_weight() );
std::cout << "AFTER:" << '\n';
for(int i = 0; i < size; ++i)
{
std::cout << i << " => " << tab[i].weight << '\n';
}
return EXIT_SUCCESS;
}
|
2,912,958 | 2,913,014 | c++ inheritance not recognized | Is there some solution or I have to keep exactly class types?
//header file
Class Car {
public:
Car();
virtual ~Car();
};
class Bmw:Car {
public:
Bmw();
virtual ~Bmw();
};
void Start(Car& mycar) {};
//cpp file
Car::Car(){}
Car::~Car() {}
Bmw::Bmw()
:Car::Car(){}
Bmw::~Bmw() {}
int main() {
Car myCar;
Bmw myBmw;
Start(myCar); //works
Start(myBmw); //!! doesnt work
return 0;
}
| C++ defaults to private inheritance, so, you need to declare Bmw as:
class Bmw:public Car
Also, to be completely accurate, you should really have Start as a virtual method of Car and override it as needed in descendant classes. :)
|
2,912,979 | 2,913,239 | Even lighter than SQLite | I've been looking for a C++ SQL library implementation that is simple to hook in like SQLite, but faster and smaller. My projects are in games development and there's definitely a cutoff point between needing to pass the ACID test and wanting some extreme performance. I'm willing to move away from SQL string style queries, allowing it to be code driven, but I haven't found anything out there that provides SQL-like flexibility while also preferring performance over the ACID test.
I don't want to go re-inventing the wheel, and the idea of implementing an SQL library on my own is quite daunting, even if it's only going to be a simple subset of all the calls you could make.
I need the basic commands (SELECT, MODIFY, DELETE, INSERT, with JOIN, and WHERE), not data operations (like sorting, min, max, count) and don't need the database to be atomic, or even enforce consistency (I can use a real SQL service while I'm testing and debugging).
| Are you sure that you have obtained the maximum speed available from SQLITE? Out of the box, SQLITE is extremely safe, but quite slow. If you know what you are doing, and are willing to risk db corruption on a disk crash, then there are several optimizations you can do that provide spectacular speed improvements.
In particular:
Switch off synchronization
Group writes into transactions
Index tables
Use database in memory
If you have not explored all of these, then you are likely running many times slower than you might.
|
2,913,006 | 2,917,613 | How can I keep an event from being delivered to the GUI until my code finished running? | I installed a global mouse hook function like this:
mouseEventHook = ::SetWindowsHookEx( WH_MOUSE_LL, mouseEventHookFn, thisModule, 0 );
The hook function looks like this:
RESULT CALLBACK mouseEventHookFn( int code, WPARAM wParam, LPARAM lParam )
{
if ( code == HC_ACTION ) {
PMSLLHOOKSTRUCT mi = (PMSLLHOOKSTRUCT)lParam;
// .. do interesting stuff ..
}
return ::CallNextHookEx( mouseEventHook, code, wParam, lParam );
}
Now, my problem is that I cannot control how long the 'do interesting stuff' part takes exactly. In particular, it might take longer than the LowLevelHooksTimeout defined in the Windows registry. This means that, at least on Windows XP, the system no longer delivers mouse events to my hook function. I'd like to avoid this, but at the same time I need the 'do interesting stuff' part to happen before the target GUI receives the event.
I attempted to solve this by doing the 'interesting stuff' work in a separate thread so that the mouseEventHookFn above can post a message to the worker thread and then do a return 1; immediately (which ends the hook function but avoids that the event is handed to the GUI). The idea was that the worker thread, when finished, performs the CallNextHookEx call itself.
However, this causes a crash inside of CallNextHookEx (in fact, the crash occurs inside an internal function called PhkNextValid. I assume it's not safe to call CallNextHookEx from outside a hook function, is this true?
If so, does anybody else know how I can run code (which needs to interact with the GUI thread of an application) before the GUI receives the event and avoid that my hook function blocks too long?
|
assume it's not safe to call CallNextHookEx from outside a hook function, is this true?
I believe this is true.
Since there is a finite number of operations that you can receive through your low-level mouse hook, you could just put them onto a queue to be re-posted to the receiving window once your long-running operation has finished. If you put your long-running on another thread, you'll not 'lock up' the UI, but merely 'eat' or 'defer' the user actions. Return 1 to prevent other hooks happening. Use a boolean flag to signify whether you're collecting events (because your long-running operation has to run yet) or re-posting them (and thus shouldn't hook them).
There aren't likely to be (m)any other low-level hooks in the system that you're cancelling, but you should test this mechanism thoroughly in your situation. I have used it only to block operations before (kill right-mouse-click) rather than defer them.
|
2,913,206 | 2,913,269 | A follow up on type coercion in C++, as it may be construed by type conversion | This is a follow up to my previous question.
Consider that I write a function with the following prototype:
int a_function(Foo val);
Where foo is believed to be a type defined unsigned int. This is unfortunately not verifiable for lack of documentation.
So, someone comes along and uses a_function, but calls it with an unsigned int as an argument.
Here the story takes a turn. Foo turns out to actually be a class, which can take an unsigned int as a single argument of unsigned int in an explicit constructor.
Is it a standard and reliable behavior for the compiler to render the function call by doing a type conversion on the argument. I.e. is the compiler supposed to recognize the mismatch and insert the constructor? Or should I get a compile time error reporting the type mismatch.
| In case when Foo has a constructor for unsigned int implicit conversion will take place unless Foo is not declared explicit.
The first case:
class Foo { public: Foo(unsigned int) {} };
// ...
a_function( 1 ); // OK
Second case:
class Foo { public: explicit Foo(unsigned int) {} };
// ..
a_function( 1 ); // error
According to C++ Standard only one user-defined implicit conversion is allowed.
|
2,913,386 | 2,913,604 | Quicksort / vector / partition issue | I have an issue with the following code :
class quicksort {
private:
void _sort(double_it begin, double_it end)
{
if ( begin == end ) { return ; }
double_it it = partition(begin, end, bind2nd(less<double>(), *begin)) ;
iter_swap(begin, it-1);
_sort(begin, it-1);
_sort(it, end);
}
public:
quicksort (){}
void operator()(vector<double> & data)
{
double_it begin = data.begin();
double_it end = data.end() ;
_sort(begin, end);
}
};
However, this won't work for too large a number of elements (it works with 10 000 elements, but not with 100 000).
Example code :
int main()
{
vector<double>v ;
for(int i = n-1; i >= 0 ; --i)
v.push_back(rand());
quicksort f;
f(v);
return 0;
}
Doesn't the STL partition function works for such sizes ? Or am I missing something ?
Many thanks for your help.
| I see a couple of problems. I wouldn't include the pivot in your partitioning so I would use this line instead:
double_it it = partition(begin + 1, end, bind2nd(less<double>(), *begin)) ;
Also, I wouldn't continue to include the pivot in your future sorts so I would do
_sort(begin, it - 2);
instead, but you need to be careful that it - 2 isn't less than begin so check that it - 1 != begin first. There is no need to continually sort the pivot - it is already in the correct spot. This will just add a lot of extra needless recursion.
You can certainly still have stack overflow problems with this code even after the changes. For instance, if you sort an already sorted array with this code, the performance will be O(N^2) and if N is very large then you will get a stack overflow. Using a randomly chosen pivot will essentially eliminate that for the sorted array problem, but you can still have problems if the array is all the same element. In that case, you need to alter your algorithm to use Bentley-McIlroy partitioning or the like. Or you could change it to an introsort and change to heapsort when the recursion depth gets very deep.
|
2,913,562 | 2,913,826 | How to get only first words from several C++ strings? | I have several C++ strings with some words. I need to get the first word from every string. Then I have to put all of them into a char array. How can I do it?
| Here is one way of doing it...
// SO2913562.cpp
//
#include <iostream>
#include <sstream>
using namespace std;
void getHeadWords(const char *input[]
, unsigned numStrings
, char *outBuf
, unsigned outBufSize)
{
string outStr = "";
for(unsigned i = 0; i<numStrings; i++)
{
stringstream ss(stringstream::in|stringstream::out);
ss<<input[i];
string word;
ss>>word;
outStr += word;
if(i < numStrings-1)
outStr += " ";
}
if(outBufSize < outStr.size() + 1)//Accomodate the null terminator.
//strncpy omits the null terminator if outStr is of the exact same
//length as outBufSize
throw out_of_range("Output buffer too small");
strncpy(outBuf, outStr.c_str(), outBufSize);
}
int main ()
{
const char *lines[] = {
"first sentence"
, "second sentence"
, "third sentence"
};
char outBuf[1024];
getHeadWords(lines, _countof(lines), outBuf, sizeof(outBuf));
cout<<outBuf<<endl;
return 0;
}
But note the above code has marginal error checking and may have security flaws. And needless to say my C++ is a bit rusty. Cheers.
|
2,914,027 | 2,914,244 | Multi-process builds in Visual Studio 2010: Worth it? | I've started testing our C++ software with VS2010 and the build times are really bad (30-45 minutes, about double the VS2005 times). I've been reading about the /MP switch for multi-process compilation. Unfortunately, it is incompatible with some features that we use quite a bit like #import, incremental compilation, and precompiled headers.
Have you had a similar project where you tried the /MP switch after turning off things like precompiled headers? Did you get faster builds?
My machine is running 64-bit Windows 7 on a 4 core machine with 4 GB of RAM and a fast SSD storage. Virus scanner disabled and a pretty minimal software environment.
Edit: Martin and jdehaan pointed out that MP is not incompatible with precompiled headers. Details are here.
| Definitely YES. I worked on a large application which took around 35 minutes to build when something was modified (In Visual Studio). We used IncrediBuild for that (to speed up the compilation process, from 35 minutes to 5 minutes) - to be truly distributed. In your case it is possible that /MP switch will make some difference - but not that much compared to distcc (unix or compatible environment) or IncrediBuild.
|
2,914,081 | 6,448,225 | C++ member function template in derived class, how to call it from base class? | As my prveious question sounded confusing, I think it's best to clearly state what I want to achieve.
I have (ignore the inheritance for now and focus on X):
class Base {};
class X : public Base {
private:
double m_double;
public:
template<class A> friend
void state( A& a, const X& x ) {
data( a, x.m_double, "m_double" );
}
};
I can now introduce arbitrary new classes that performs different actions based on how the data function is overloaded, we will refer to these as Accessors in the following:
class XmlArchive {...}; //One Accessor
template<class T>
void data( XmlArchive& a, const T& t, const std::string& str ) {
//read data and serialize it to xml Archive
}
class ParameterList {...}; //Another Accessor
template<class T>
void data( ParameterList& a, const T& t, const std::string& str ) {
//put data in a parameter list
}
I can then write:
X myX;
XmlArchive myArchive;
state( myArchive, myX );
ParameterList myParameters;
state( myParameters, myX );
Fantastic, code reuse! :D However the following (clearly) fails:
Base* basePtr = new X; //This would come from factory really, I should not know the type X
state( myParameters, *basePtr ); //Error
The goal is to make this last call succed. What I have considered (and why it is not acceptable):
First option: make all Accessors inherit from a common base class, say AccessorBase, then write in Base
virtual state( AccessorBase& a ) const = 0;
and implement the required code in X (the syntax to call state will be marginally different but this can be fixed).
The problem is that AccessorBase will need to have a virtual function for every possible type which comes as second argument in the data function(s). As these types can be user-defined classes (see case of class composition, X which has Y as data member) I do not see how to make this strategy can work.
Second option: create a virtual function in Base for every Accessor. This violates the open/close principle as adding a new Accessor class (say TxtArchive) will require modification of the base class.
I understand why virtual member function cannot be templated (possible different vtbls in different compilation units).
However it seemes to me that there should be a solution to this problem... Base knows that it really is of type X, and the type of the Accessor is always explicit, so it is a matter of finding a way of calling (for Accessor of type XmlArchive):
state( xmlArchive, x ); //xmlArchive of type XmlArchive, x of type X
which will yield the result.
To sum-up I would like the call:
state( myParameters, *basePtr );
to succeed if basePtr is pointing to a derived class with a function template compatible with the call and to throw an exception otherwise.
It seemes to me that boost::serialize does something similar but I cannot figure out how (it may be it is re-implemnting inheritance relationships in C++ via templates, I see a This() funcion returning the most derived pointer but it gets really confusing...)
Thank you again in advance for your help!
| You could use the vistor pattern for this:
class IVisitor
{
public:
virtual void on_data( double, const char * )=0;
virtual void on_data( std::string, const char * )=0;
};
class Base
{
public:
virtual void visit( IVisitor * v )=0;
};
class X : public Base
{
private:
double m_double;
std::string m_string;
public:
void visit( IVisitor * v)
{
v->on_data( m_double, "m_double" );
v->on_data( m_string, "m_string" );
}
};
Base * base = ...;
XmlArchive ar; // This must derive from IVisitor
base->visit(&ar);
ParameterList pl; // This must derive from IVisitor
base->visit(pl);
If you dislike the need to implement each of the different on_data types in the IVisitor, you can use a boost::any - but in my experience the branching required in the implementations of that function are not worth it.
|
2,914,090 | 2,914,103 | What's the benefit of declaring class functions separately from their actual functionality? | In C++, what's the benefit of having a class with functions...
say
class someClass{
public:
void someFunc(int arg1);
};
then having the function's actual functionality declared after int main
int main()
{ return 0; }
void someClass::someFunc(int arg1)
{ cout<<arg1; }
Furthermore, what's the benefit of declaring the class in a .h header file, then putting the functionality in a .cpp file that #includes the .h file?
| Dependency management. Users of the class only need to include the header file, so they don't depend on the implementation.
Another use is breaking circular dependencies.
Both issues may look like a waste of time with toy programs, but they start to grow into a really bad problem as the program grows.
|
2,914,150 | 2,914,294 | Implement a multithreading environment | I want to implement a multithreading environment using Qt4. The idea is as follows in c++-alike pseudo-code:
class Thread : public QThread {
QList<SubThread*> threads_;
public:
void run() {
foreach(SubThread* thread : threads) {
thread.start();
}
foreach(SubThread* thread : threads) {
thread.wait();
}
}
void abort() {
foreach(SubThread* thread : threads) {
thread.cancel();
}
}
public slots:
// This method is called from the main-thread
// (sometimes via some signal-slot-connection)
void changeSomeSettings() {
abort();
// change settings
start();
}
}
class SubThread : public QThread {
bool isCancelled_;
public:
void run() {
while(!isCancelled or task completed) {
// something that takes some time...
}
}
void cancel() {
if(isRunning() {
isCancelled_ = true;
}
}
}
The purpose is that the slot changeSomeSettings() kills all running threads, commits its changes and restarts it. What I want to achieve is that once this method has been started, it calls "abort" and then waits until all threads have terminated. Using mutexes in a wrong way:
void Thread::changeSomeSettings() {
mutex1.lock();
abort();
mutex2.lock();
start();
mutex1.unlock();
}
void Thread::run() {
foreach(Thread* thread : threads) {
thread.start();
}
foreach(Thread* thread : threads) {
thread.wait();
}
mutex2.unlock();
}
This actually works in Qt under MacOSX, yet according to the documentation mutex2 must be unlocked in the same thread (and in Windows I get an error). What is the best way to achieve my goal without running into racing conditions and deadlocks? Is there a better design than the one I have proposed here?
| You probably want to use a condition variable instead of a mutex for this situation. A condition variable is a way for one thread to signal another. QT's implementation appears to be the QTWaitCondition:
I might have the child thread's periodically check the state of the condition variable. This can be done with QTWaitCondition::wait() with a short/0 timeout. If it is being signaled, then lock a shared memory area containing updated data and access the data that needs to be updated. Then that thread can safely restart itself accordingly.
It's usually not a good idea to just abort a thread. You may end up leaking memory/resources/handles/locks/etc. You don't know where that thread is in it's call stack, and there may be no guarantees that the stack will be "unwound" for you and all destructors are called. This is another reason for the child threads checking a condition variable periodically for updated data and having them restart themselves safely with the new data.
|
2,914,202 | 2,914,421 | How to concatenate 2 LPOLESTR | i want to concatenate 2 strings in c++, i can't use char*.
I tried the following but doesn't work:
#define url L"http://domain.com"
wstring s1 = url;
wstring s2 = L"/page.html";
wstring s = s1 + s2;
LPOLESTR o = OLESTR(s);
I need a string with s1 and s2 concatenated. Any info or website that explain more about this ? Thanks.
| OLESTR("s") is the same as L"s" (and OLESTR(s) is Ls), which is obviously not what you want.
Use this:
#define url L"http://domain.com"
wstring s1 = url;
wstring s2 = L"/page.html";
wstring s = s1 + s2;
LPCOLESTR o = s.c_str();
This gives you a LPCOLESTR (ie. a const LPOLESTR). If you really need it to be non-const, you can copy it to a new string:
...
wstring s = s1 + s2;
LPOLESTR o = new wchar_t[s.length() + 1];
wcscpy(o, s.c_str()); //wide-string equivalent of strcpy is wcscpy
//Don't forget to delete o!
Or, to avoid wstring's altogether (not recommended; it would be better to convert your application to using wstring's everywhere than to use LPOLESTR's):
#define url L"http://domain.com"
LPCOLESTR s1 = url;
LPCOLESTR s2 = L"/page.html";
LPOLESTR s = new wchar_t[wcslen(s1) + wcslen(s2) + 1];
wcscpy(s, s1); //wide-string equivalent of strcpy is wcscpy
wcscat(s, s2); //wide-string equivalent of strcat is wcscat
//Don't forget to delete s!
|
2,914,209 | 2,914,255 | What happens to class members when malloc is used instead of new? | I'm studying for a final exam and I stumbled upon a curious question that was part of the exam our teacher gave last year to some poor souls. The question goes something like this:
Is the following program correct, or not? If it is, write down what the program outputs. If it's not, write down why.
The program:
#include<iostream.h>
class cls
{ int x;
public: cls() { x=23; }
int get_x(){ return x; } };
int main()
{ cls *p1, *p2;
p1=new cls;
p2=(cls*)malloc(sizeof(cls));
int x=p1->get_x()+p2->get_x();
cout<<x;
return 0;
}
My first instinct was to answer with "the program is not correct, as new should be used instead of malloc". However, after compiling the program and seeing it output 23 I realize that that answer might not be correct.
The problem is that I was expecting p2->get_x() to return some arbitrary number (whatever happened to be in that spot of the memory when malloc was called). However, it returned 0. I'm not sure whether this is a coincidence or if class members are initialized with 0 when it is malloc-ed.
Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this?
What would your answer to my teacher's question be? (besides forgetting to #include <stdlib.h> for malloc :P)
|
Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this?
No, p2->x can be anything after the call to malloc. It just happens to be 0 in your test environment.
What would your answer to my teacher's question be? (besides forgetting to #include for malloc :P)
What everyone has told you, new combines the call to get memory from the freestore with a call to the object's constructor. Malloc only does half of that.
Fixing it: While the sample program is wrong. It isn't always wrong to use "malloc" with classes. It is perfectly valid in a shared memory situation you just have to add an in-place call to new:
p2=(cls*)malloc(sizeof(cls));
new(p2) cls;
|
2,914,356 | 2,914,719 | Problem with boost::find_format_all, boost::regex_finder and custom regex formatter (bug boost 1.42) | I have a code that has been working for almost 4 years (since boost 1.33) and today I went from boost 1.36 to boost 1.42 and now I have a problem.
I'm calling a custom formatter on a string to format parts of the string that match a REGEX.
For instance, a string like: "abc;def:" will be changed to "abc\2Cdef\3B" if the REGEX contains "([;:])"
boost::find_format_all( mystring, boost::regex_finder( REGEX ), custom_formatter() );
The custom formatter looks like this:
struct custom_formatter()
{
template< typename T >
std::string operator()( const T & s ) const
{
std::string matchStr = s.match_results().str(1);
// perform substitutions
return matchStr;
}
}
This worked fine but with boost 1.42 I know have "non initialized" s.match_results() which yield to boost::exception_detail::clone_implINS0_::error_info_injectorISt11logic_errorEEEE
- Attempt to access an uninitialzed boost::match_results<> class.
This means that sometimes I am in the functor to format a string but there is no match.
Am I doing something wrong? Or is it normal to enter the functor when there is no match and I should check against something?
for now my solution is to try{}catch(){} the exception and everything works fine, but somehow that doesn't feel very good.
EDIT1
Actually I have a new empty match at the end of each string to parse.
EDIT2 : one solution inspired by ablaeul
template< typename T >
std::string operator()( const T & s ) const
{
if( s.begin() == s.end() ) return std::string();
std::string matchStr = s.match_results().str(1);
// perform substitutions
return matchStr;
}
EDIT3 Seems to be a bug in (at least) boost 1.42
| The struct find_regexF seems to be the culprit. As you can see, it returns an empty result with a uninitialized match_results(). Looking through SO found me the following solution:
struct custom_formatter()
{
template< typename T >
std::string operator()( const T & s ) const
{
std::string matchStr;
for (typename T::const_iterator i = Match.begin();
i != Match.end();
i++) {
// perform substitutions via *i
}
return matchStr;
}
}
EDIT: Looking at how Boost uses the formatter here is another solution:
template<typename InputIteratorT>
std::string operator()(
const regex_search_result<InputIteratorT>& Replace ) const
{
if ( Replace.empty() )
{
return std::string();
}
else
{
std::string matchStr = s.match_results().str(1);
// perform substitutions
return matchStr;
}
}
|
2,914,597 | 2,914,618 | Seeking References To MSVC 9.0's C++ Standards Compliance | I "know" (hopefully) that MSVC 9.0 Implements C++ 2003 (ISO/IEC 14882:2003). I am looking for a reference to this fact, and I am also looking for any research that has been done in to how compliant MSVC 9.0 is with that version of the Standard.
I have searched for and not been able to find a specific reference from MicroSoft that actually says something to the effect that MSVC implements C++ 2003. Some of the out-of-date documentation says things like "this release achieves roughly 98% compliance" (when referring to MSVC .NET 2003's conformance to C++ 1997). But I want a link to a document from MS that says "MSVC 9.0 implements blah," and another link to an independent group that has tested the conformance of MSVC 9.0.
Do you know of any such links?
| Nonstandard Behavior . Short summary
Compiler Limits
10.3 (Paragraph 5) Covariant Return Types
14 export Keyword on a Template
14.6.2 Dependent Names
15.4 Function Exception Specifiers
16.3.2 The # Operator
21.1.1 Character Traits Requirements
Storage Location of Objects
|
2,914,631 | 2,914,788 | How do I use foreach with QDomNodeList in Qt? | I'm new to Qt and I'm learning something new every day.
Currently, I'm developing a small application for my Nokia N900 in my free time.
Everything is fine, I am able to compile and run Maemo applications on the device.
I've just learned about the foreach keyword in Qt. (I know it is not in C++, so I didn't think about it until I accidentally stumbled upon a Qt doc that mentioned it.)
So, I decided to change my quite annoying and unreadable loops to foreach, but I failed with this:
QDomNodeList list = doc.lastChild().childNodes().at(1).firstChild().childNodes();
for (int x = 0; x < list.count(); x++)
{
QDomElement node = list.at(x).toElement();
// Do something with node
}
This is how I tried:
foreach (QDomElement node, doc.lastChild().childNodes().at(1).firstChild().childNodes())
{
// Do something with node
}
For some reason the above code doesn't even compile. I get cryptic error messages from the compiler.
Could someone please explain to me how to get it right?
If the foreach loop doesn't support QDomNodeList, is there a way to handle XML files which supports foreach?
EDIT:
To clarify, // Do something with node is the following in this case:
EveCharacter chr;
chr.setName(node.attribute(EVE_NAME));
chr.setId(node.attribute(EVE_CHARACTER_ID).toInt());
acc->addCharacter(chr);
Where acc is of type EveAccount, which stores data in a QList<EveCharacter>.
The uppercase symbols are compile-time constant strings.
(I'm creating a client for the EVE Online API. This is from the method that receives the account characters XML and interprets it.)
This is how I create doc:
QDomDocument doc;
doc.setContent(reply->readAll());
Note that reply is a QNetworkReply* which is sent back from a QNetworkAccessManager.
However, as the EVE API works with XML, I do a lot of XML parsing very similar to this in many places in my application.
Most of the XMLs can be several hundred lines long and can contain quite non-regular data patterns, such as this one.
| foreach only supports the container classes, so you cannot use it with a QDomNodeList.
I'm not sure of you actual goal, but I find the QXmlSimpleReader and QXmlStreamReader to be the easiest way to deal with XML.
Edit to match question edit:
What you are trying to do looks like a prime candidate for XPath or XQuery. Take a look at the QtXmlPatterns module this will give you a set of character nodes without having to loop through all the other nodes.
|
2,914,651 | 2,914,714 | have you and how do you do C++ autotest? | As far as autotest is concerned, how do you do autotest for C++ programs? are there any autotest framework that can be utilized to do unit test and integration test?
| You can use NUnit to achieve this, but there may be better ways. With NUnit you are writing test classes in managed C++/CLI which is calling your C++ code, which presumably runs as unmanaged. So for this option, some of your C++ code now runs as managed just for the sake of using NUnit. One may debate the "purity" of this approach. Another problem with this is attaching a debugger to NUnit (of course with both managed/native enabled) and trying to step through the managed C++/CLI bits in a sensible manner. Despite this, our office has been using NUnit for C++ unit and integration testing for a while now.
Just saw @Patrick's answer about CPPUnit, I will have to look at that.
|
2,914,666 | 3,612,613 | Boost.Thread throws bad_alloc exception in VS2010 | Upon including <boost/thread.hpp> I get this exception:
First-chance exception at 0x7c812afb in CSF.exe: Microsoft C++ exception:
boost::exception_detail::clone_impl<boost::exception_detail::bad_alloc_> at memory location 0x0012fc3c..
First-chance exception at 0x7c812afb in CSF.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000..
I can't catch it, breaking at the memory location brings me to kernel32.dll and at this point I cannot say what's going on but it appears that the exception is thrown after the program ends and VS is capable of catching it.
The testcase:
#include <boost/thread.hpp>
int main()
{
return 0;
}
Compiler command line:
/I"I:\SophisPal\boost-1_43_0-vc10-32\include\boost-1_43" /Zi /nologo /W3 /WX- /O2 /Oi /Oy- /GL /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm- /EHsc /GS /Gy /fp:precise /Zc:wchar_t /Zc:forScope /Fp"Release\Client.pch" /Fa"Release\" /Fo"Release\" /Fd"Release\vc100.pdb" /Gd /analyze- /errorReport:queue
Linker command line:
/OUT:"C:\Documents and Settings\user\my documents\visual studio 2010\Projects\CSF\Release\Client.exe" /INCREMENTAL:NO /NOLOGO "I:\SophisPal\boost-1_43_0-vc10-32\lib\libboost_system-vc100-mt-1_43.lib" "I:\SophisPal\boost-1_43_0-vc10-32\lib\libboost_date_time-vc100-mt-1_43.lib" "I:\SophisPal\boost-1_43_0-vc10-32\lib\libboost_regex-vc100-mt-1_43.lib" "I:\SophisPal\boost-1_43_0-vc10-32\lib\libboost_thread-vc100-mt-1_43.lib" "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /MANIFEST /ManifestFile:"Release\Client.exe.intermediate.manifest" /ALLOWISOLATION /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:"C:\Documents and Settings\user\my documents\visual studio 2010\Projects\CSF\Release\Client.pdb" /SUBSYSTEM:CONSOLE /OPT:REF /OPT:ICF /PGD:"C:\Documents and Settings\user\my documents\visual studio 2010\Projects\CSF\Release\Client.pgd" /LTCG /TLBID:1 /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:QUEUE
| This was by design in boost 1.43 but has been since fixed. See this thread for the details.
|
2,914,856 | 2,914,898 | Thread-local storage segfaults on NetBSD only? | Trying to run a C++ program, I get segmentation
faults which appear to be specific to NetBSD. Bert Hubert wrote the
simple test program (at the end of this message) and, indeed, it crashes only on NetBSD.
% uname -a
NetBSD golgoth 5.0.1 NetBSD 5.0.1 (GENERIC) #0: Thu Oct 1 15:46:16 CEST 2009
+stephane@golgoth:/usr/obj/sys/arch/i386/compile/GENERIC i386
% g++ --version
g++ (GCC) 4.1.3 20080704 prerelease (NetBSD nb2 20081120)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% gdb thread-local-storage-powerdns
GNU gdb 6.5
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386--netbsdelf"...
(gdb) run
Starting program: /home/stephane/Programmation/C++/essais/thread-local-storage-powerdns
Program received signal SIGSEGV, Segmentation fault.
0x0804881b in main () at thread-local-storage-powerdns.cc:20
20 t_a = new Bogo('a');
(gdb)
On other Unix, it works fine. Is there a known issue in NetBSD with
C++ thread-local storage?
#include <stdio.h>
class Bogo
{
public:
explicit Bogo(char a)
{
d_a = a;
}
char d_a;
};
__thread Bogo* t_a;
int main()
{
t_a = new Bogo('a');
Bogo* b = t_a;
printf("%c\n", b->d_a);
}
| NetBSD does not support thread-local storage. Most of the other BSDs do however.
|
2,914,932 | 2,914,975 | Boost test: catch user defined exceptions | If I have user defined exceptions in my code, I can't get Boost test
to consider them as failures.
For example,
BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(MyTest,1)
BOOST_AUTO_TEST_CASE(MyTest)
{
// code which throws user defined exception, not derived from std::exception.
}
I get a generic message:
Caught exception: ....
unknown location(0):....
It does not recognize this error as a failure since it is not a std::exception.
So it does not honor the expected_failures clause.
How do I enforce that the piece of code should always throw an exception?
THis seems to be a useful thing to want. In case future code changes cause the code
to pass and the exception is not thrown, I want to know that.
| The EXPECTED_FAILURES are referring to failures against BOOST_REQUIRE or other assertions. The documentation clearly states:
The feature is not intended to be used to check for expected functionality failures. To check that a particular input is causing an exception to be thrown use BOOST_CHECK_THROW family of testing tools.
Emphasis was mine.
The expected failures are meant to be used as a temporary workaround during testing when an assertion is failing but you want to temporarily ignore it.
Taking a snippet from their expected failures spec:
BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( my_test1, 1 )
BOOST_AUTO_TEST_CASE( my_test1 )
{
BOOST_CHECK( 2 == 1 );
}
will result in output of
test.cpp(10): error in "my_test1": check 2 == 1 failed
Test suite "example" passed with:
1 assertions out of 1 failed
1 failures expected
1 test case out of 1 passed
As you can see, in spite of assertions failing, the test case still passed due to the use of expected failures.
So if you need to verify that something is throwing an exception, you use code like the following:
BOOST_AUTO_TEST_CASE(invalid_operation_should_throw_custom_exception)
{
MyObj obj;
BOOST_REQUIRE_THROW(obj.invalid_operation(), CustomException);
}
|
2,914,971 | 2,932,390 | Image/"most resembling pixel" search optimization? | The situation:
Let's say I have an image A, say, 512x512 pixels, and image B, 5x5 or 7x7 pixels.
Both images are 24bit rgb, and B have 1bit alpha mask (so each pixel is either completely transparent or completely solid).
I need to find within image A a pixel which (with its' neighbors) most closely resembles image B, OR the pixel that probably most closely resembles image B.
Resemblance is calculated as "distance" which is sum of "distances" between non-transparent B's pixels and A's pixels divided by number of non-transparent B's pixels. Here is a sample SDL code for explanation:
struct Pixel{
unsigned char b, g, r, a;
};
void fillPixel(int x, int y, SDL_Surface* dst, SDL_Surface* src, int dstMaskX, int dstMaskY){
Pixel& dstPix = *((Pixel*)((char*)(dst->pixels) + sizeof(Pixel)*x + dst->pitch*y));
int xMin = x + texWidth - searchWidth;
int xMax = xMin + searchWidth*2;
int yMin = y + texHeight - searchHeight;
int yMax = yMin + searchHeight*2;
int numFilled = 0;
for (int curY = yMin; curY < yMax; curY++)
for (int curX = xMin; curX < xMax; curX++){
Pixel& cur = *((Pixel*)((char*)(dst->pixels) + sizeof(Pixel)*(curX & texMaskX) + dst->pitch*(curY & texMaskY)));
if (cur.a != 0)
numFilled++;
}
if (numFilled == 0){
int srcX = rand() % src->w;
int srcY = rand() % src->h;
dstPix = *((Pixel*)((char*)(src->pixels) + sizeof(Pixel)*srcX + src->pitch*srcY));
dstPix.a = 0xFF;
return;
}
int storedSrcX = rand() % src->w;
int storedSrcY = rand() % src->h;
float lastDifference = 3.40282347e+37F;
//unsigned char mask =
for (int srcY = searchHeight; srcY < (src->h - searchHeight); srcY++)
for (int srcX = searchWidth; srcX < (src->w - searchWidth); srcX++){
float curDifference = 0;
int numPixels = 0;
for (int tmpY = -searchHeight; tmpY < searchHeight; tmpY++)
for(int tmpX = -searchWidth; tmpX < searchWidth; tmpX++){
Pixel& tmpSrc = *((Pixel*)((char*)(src->pixels) + sizeof(Pixel)*(srcX+tmpX) + src->pitch*(srcY+tmpY)));
Pixel& tmpDst = *((Pixel*)((char*)(dst->pixels) + sizeof(Pixel)*((x + dst->w + tmpX) & dstMaskX) + dst->pitch*((y + dst->h + tmpY) & dstMaskY)));
if (tmpDst.a){
numPixels++;
int dr = tmpSrc.r - tmpDst.r;
int dg = tmpSrc.g - tmpDst.g;
int db = tmpSrc.g - tmpDst.g;
curDifference += dr*dr + dg*dg + db*db;
}
}
if (numPixels)
curDifference /= (float)numPixels;
if (curDifference < lastDifference){
lastDifference = curDifference;
storedSrcX = srcX;
storedSrcY = srcY;
}
}
dstPix = *((Pixel*)((char*)(src->pixels) + sizeof(Pixel)*storedSrcX + src->pitch*storedSrcY));
dstPix.a = 0xFF;
}
This thing is supposed to be used for texture generation.
Now, the question:
The easiest way to do this is brute force search (which is used in example routine). But it is slow - even using GPU acceleration and dual core cpu won't make it much faster. It looks like I can't use modified binary search because of B's mask. So, how can I find desired pixel faster?
Additional Info:
It is allowed to use 2 cores, GPU acceleration, CUDA, and 1.5..2 gigabytes of RAM for the task.
I would prefer to avoid some kind of lengthy preprocessing phase that will take 30 minutes to finish.
Ideas?
| Answering to my own question.
Short answer:
I was able to drop alpha channel, so I've decided to use image pyramids (see pyramid and gaussian pyramid on the net). It gave huge speed improvement.
Long answer:
My initial goal was texture synthesis. Alpha was used to generating pixels that weren't filled yet, and B represented a portion of already generated image. (I.e. A was sample pattern, and B was generated image)
After a bit of researching I've found that either there is no quick way to do a search in N-dimensional space (for example, 3x3 pixel area is basically an 24 component vector (center pixel excluded), while 7x7 wlil be 144-component, searching for such area will be 24-dimensional or 144-dimensional search). Well, there are ways (for example, paper named "I-COLLIDE: an interactive and exact collision detection system for large-scale environments" uses 3 sorted arrays (each sorted on different dimension) to do 3 dimensional search), but they obviously will work better for floats and lower number of dimensions.
Suggestion to use motion detection wasn't useful, because (it seems) motion detection assumes that pixels represent moving objects (not true in my case), and at least some optimization relies on that.
In the end I've found paper named "Fast Texture Synthesis using Tree-structured Vector Quantization" (Li-Yi Wei, Marc Levoy, Stanford University), which uses technique based on algorithm similar to the one I used. Image to be searched is downsampled several times (similar to mip-map generation), search performed on the lowest level first, and then on the next. It may not be the best way to do actual image search for other application, but it perfect for my purposes. The paper is relatively old but it works for me.
The same paper mentions a few techniques for accelerating search even further. One of them is "Tree-structured vector quantization (TSVQ)", although I can't give more info about it (haven't checked it - current texture generator works with acceptable speed on my hardware, so I probably won't look into further optimizations).
|
2,914,986 | 2,919,948 | Boost Mersenne Twister: how to seed with more than one value? | I'm using the boost mt19937 implementation for a simulation.
The simulation needs to be reproducible, and that means storing and potentially reusing the RNG seeds later. I'm using the windows crypto api to generate the seed values because I need an external source for the seeds and not because of any particular guarantees of randomness. The output of any simulation run will have a note including the RNG seed - so the seed needs to be reasonably short. On the other hand, as part of the analysis of the simulation, I'll be comparing several runs - but to be sure that these runs are actually different, I'll need to use different seeds - so the seed needs to be long enough to avoid accidental collisions.
I've determined that 64-bits of seeding should suffice; the chance of a collision will reach 50% after about 2^32 runs - that probability is low enough that the average error caused by it is negligible to me. Using just 32-bits of seed is tricky; the chance of a collision reaches 50% already after 2^16 runs; and that's a little too likely for my tastes.
Unfortunately, the boost implementation either seeds with a full state vector - which is far, far too long - or a single 32-bit unsigned long - which isn't ideal.
How can I seed the generator with more than 32-bits but less than a full state vector? I tried just padding the vector or repeating the seeds to fill the state vector, but even a cursory glance at the results shows that that generates poor results.
| Your assumptions are mistaken. For a simulation, you don't need cryptographically strong seeds. In fact, using seeds 1,2,3,4, etcetera is often a better idea. The output values of the Mersenne Twister will be uncorrelated, yet nobody will question whether you cherry-picked your seeds to get desired simulation outputs.
For other people who do have a real need, one easy way is to discard the first (seed>>32) values generated. This gives you about log2(seed>>32) extra bits of state. However, it only works efficiently if you need a few extra bits. Adding 32 bits this way is probably too slow.
A faster algorithm is to generate the full state vector for the good random generator. The solutions mentioned in the question (repeating or padding) aren't so good due to the limited randomness in the resulting state vector. But if you fill the initial state vector from the output of mersenne_twister(seed1) ^ mersenne_twister(seed2), this is not an issue at all.
|
2,915,049 | 2,915,096 | better understanding of getline() and cin | Trying to get some basic understanding of console functionalities. I am having issues so consider the following...
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
void MultiplicationTable(int x);
int main()
{
int value = 0;
printf("Please enter any number \n\n");
getline(cin, value);
MultiplicationTable(value);
getchar();
return 0;
}
I actually based this off code from http://www.cplusplus.com/doc/tutorial/basic_io/ . My IDE is not recognizing getline() so of course when I compile the application. I get an error
'getline': identifier not found
Now take a look at this code
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
void MultiplicationTable(int x);
int main()
{
int value = 0;
printf("Please enter any number \n\n");
cin>>value;
MultiplicationTable(value);
getchar();
return 0;
}
When I execute this line of code the console window opens and immediately closes. I think I a missing something about cin. I do know that it delimits spaces but I don't know what else. what should I use for input to make my life easier.
| The function getline() is declared in the string header. So, you have to add #include <string>.
It is defined as istream& getline ( istream& is, string& str );, but you call it with an int instead of a string object.
About your second question:
When I execute this line of code the console window opens and immediately closes
There is probably still a '\n' character from your input in the stream, when your program reaches the function getchar() (which I assume you put there so your window doesn't close). You have to flush your stream. An easy fix is, instead of getchar(), add the line
int c;
while((c = getchar()) != '\n'){}
This will flush your stream until the next line-break.
Remark: conio.h is not part of the c++ standard and obsolete.
|
2,915,071 | 2,915,210 | Set clipping rectangle for OpenGL? | I'm making a drawing application with WINAPI and OpenGL. To make things more efficient I only redraw the region needed so I invalidateRect(hwnd,myRect,false).
I know OpenGL does self clipping but I want to do that for my rect. I want it to clip itself for the region I invalidated to make things even more efficient. Thanks
| If I understood correctly, what you want is the scissor test. Enable it with glEnable(GL_SCISSOR_TEST); and set the scissor rectangle with glScissor(x, y, width, height);
|
2,915,075 | 2,915,107 | Derived template override return type of member function C++ | I am writing matrix classes. Take a look at this definition:
template <typename T, unsigned int dimension_x, unsigned int dimension_y>
class generic_matrix
{
...
generic_matrix<T, dimension_x - 1, dimension_y - 1>
minor(unsigned int x, unsigned int y) const
{ ... }
...
}
template <typename T, unsigned int dimension>
class generic_square_matrix : public generic_matrix<T, dimension, dimension>
{
...
generic_square_matrix(const generic_matrix<T, dimension, dimension>& other)
{ ... }
...
void foo();
}
The generic_square_matrix class provides additional functions like matrix multiplication.
Doing this is no problem:
generic_square_matrix<T, 4> m = generic_matrix<T, 4, 4>();
It is possible to assign any square matrix to M, even though the type is not generic_square_matrix, due to the constructor. This is possible because the data does not change across children, only the supported functions. This is also possible:
generic_square_matrix<T, 4> m = generic_square_matrix<T, 5>().minor(1,1);
Same conversion applies here. But now comes the problem:
generic_square_matrix<T, 4>().minor(1,1).foo(); //problem, foo is not in generic_matrix<T, 3, 3>
To solve this I would like generic_square_matrix::minor to return a generic_square_matrix instead of a generic_matrix. The only possible way to do this, I think is to use template specialisation. But since a specialisation is basically treated like a separate class, I have to redefine all functions. I cannot call the function of the non-specialised class as you would do with a derived class, so I have to copy the entire function.
This is not a very nice generic-programming solution, and a lot of work.
C++ almost has a solution for my problem: a virtual function of a derived class, can return a pointer or reference to a different class than the base class returns, if this class is derived from the class that the base class returns. generic_square_matrix is derived from generic_matrix, but the function does not return a pointer nor reference, so this doesn't apply here.
Is there a solution to this problem (possibly involving an entirely other structure; my only requirements are that the dimensions are a template parameter and that square matrices can have additional functionality).
Thanks in advance,
Ruud
| You could just implement the function in the derived class without making it virtual. This will "hide" the base class implementation and may be desirable for your use despite the general aversion to hiding member functions.
A better method might be to just use a different name, although that may upset the "purity" of your interface.
Finally- could minor() be implemented as a free function instead of a member function? Then you could provide overloads as appropriate, and the correct function would be called at compile time. This is the closest to the method hiding case I opened with, but I suspect it would be more generally accepted as "good practice."
|
2,915,332 | 2,951,546 | Detect aborted connection during Boost.Asio request |
Possible Duplicate:
How to check if socket is closed in Boost.Asio?
Is there an established way to determine whether the other end of a TCP connection is closed in the asio framework without sending any data?
Using Boost.asio for a server process, if the client times out or otherwise disconnects before the server has responded to a request, the server doesn't find this out until it has finished the request and generated a response to send, when the send immediately generates a connection-aborted error.
For some long-running requests, this can lead to clients canceling and retrying over and over, piling up many instances of the same request running in parallel, making them take even longer and "snowballing" into an avalanche that makes the server unusable. Essentially hitting F5 over and over is a denial-of-service attack.
Unfortunately I can't start sending a response until the request is complete, so "streaming" the result out is not an option, I need to be able to check at key points during the request processing and stop that processing if the client has given up.
| The key to this problem is to avoid doing request processing in the receive handler. Previously, I was doing something like this:
async_receive(..., recv_handler)
void recv_handler(error) {
if (!error) {
parse input
process input
async_send(response, ...)
Instead, the appropriate pattern is more like this:
async_receive(..., recv_handler)
void async_recv(error) {
if (error) {
canceled_flag = true;
} else {
// start a processing event
if (request_in_progress) {
capture input from input buffer
io_service.post(process_input)
}
// post another read request
async_receive(..., recv_handler)
}
}
void process_input() {
while (!done && !canceled_flag) {
process input
}
async_send(response, ...)
}
Obviously I have left out lots of detail, but the important part is to post the processing as a separate "event" in the io_service thread pool so that an additional receive can be run concurrently. This allows the "connection aborted" message to be received while processing is in progress. Be aware, however, that this means two threads must necessarily communicate with each other requiring some kind of synchronization and the input that's being processed must be kept separately from the input buffer into which the receive call is being placed, since more data may arrive due to the additional read call.
edit:
I should also note that, should you receive more data while the processing is happening, you probably do not want to start another asynchronous processing call. It's possible that this later processing could finish first, and the results could be sent to the client out-of-order. Unless you're using UDP, that's likely a serious error.
Here's some pseudo-code:
async_read (=> read_complete)
read_complete
store new data in queue
if not currently processing
if a full request is in the queue
async_process (=> process_complete)
else ignore data for now
async_read (=> read_complete)
async_process (=> process_complete)
process data
process_complete
async_write_result (=> write_complete)
write_complete
if a full request is in the queue
async_process (=> process_complete)
So, if data is received while a request is in process, it's queued up but not processed. Once processing completes and the result is sent, then we may start processing again with the data that was received earlier.
This can be optimized a bit more by allowing processing to occur while the result of the previous request is being written, but that requires even more care to ensure that the results are written in the same order as the requests were received.
|
2,915,363 | 2,915,401 | How to build boost foreach cycle | I have some abstract class called IClass (has pure virtual function). There are some classes which inherit IClass: CFirst, CSecond.
I want to add objects of classes which inherit into boost::ptr_vector:
class IClass { virtual void someFunc() = 0; };
class CFirst : public IClass { };
class CSecond : public IClass { };
boost::ptr_vector<IClass> objectsList;
objectsList.push_back(new CFirst());
objectsList.push_back(new CSecond());
And now my goal is to call function (which is declarated in IClass) from all objects in objectsList. I'd prefer to use BOOST_FOREACH:
foreach(IClass tempObj, objectsList)
{
tempObj.someFunc();
}
The problem is that IClass - abstract class, so I can't make instance of it for the foreach-cycle. What should I do?
| Use a reference to IClass instead:
foreach(IClass& tempObj, objectsList)
{
tempObj.someFunc();
}
|
2,915,483 | 2,915,523 | Can I use a static var to "cache" the result? C++ | I am using a function that returns a char*, and right now I am getting the compiler warning "returning address of local variable or temporary", so I guess I will have to use a static var for the return, my question is can I make something like if(var already set) return var else do function and return var?
This is my function:
char * GetUID()
{
TCHAR buf[20];
StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"),
someFunction());
return buf;
}
And this is what I want to do:
char * GetUID()
{
static TCHAR buf[20];
if(strlen(buf)!=0) return buf;
StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"),
someFunction());
return buf;
}
Is this a well use of static vars? And should I use ZeroMemory(&buf, 20*sizeof(char))? I removed it because if I use it above the if(strlen...) my TCHAR length is never 0, should I use it below?
| The reason you're getting a warning is because the memory allocated within your function for buf is going to be popped off the stack once the function exits. If you return a pointer to that memory address, you have a pointer to undefined memory. It may work, it may not - it's not safe regardless.
Typically the pattern in C/C++ is to allocate a block of memory and pass a pointer to that block into your function. e.g.
void GetUID( char* buf )
{
if(strlen(buf)!=0) return;
StringCchPrintf(buf, 20*sizeof(char), TEXT("%s"), someFunction());
}
If you want the function (GetUID) itself to handle caching the result, then you can use a static, a singleton (OOP), or consider thread local storage.
(e.g. in Visual C++)
__declspec(thread) TCHAR buf[20];
|
2,915,546 | 2,918,987 | Is learncpp.com good for beginners? | In my search for a good, freely available resource that will teach me C++ I stumbled on http://www.learncpp.com/.
My question is for intermediate to experienced C++ programmers...
Does this site seem to be a good resource for a beginner to learn C++ from?
I've gone through the first few section of the site, and I feel like I am starting to grasp the language, but being a beginner in C++ I really could be learning things all wrong and have no idea.
EDIT: After doing some research on this topic, and reading the answers and comments here, it seems like if I do the tutorial, read Accelerated C++, and then read Effective STL... I'll be on the right track. Of course, I'll be writing programs to solve project Euler programs and such. Do any of you have a better idea for a beginner with intentions to become competent in the language?
| The site does not look too bad.
However it really is a tutorial, in that it just explains the very basic concepts of C++.
Notably, it completely misses an introduction to the STL and the proper use of it. You barely see std::cout and std::string. There's no mention of <algorithm> that I could see of and no mention of the <vector> or <deque> or <map> which are the most commonly used containers in C++.
It may not hurt you to learn with this site, but you'll only have a very basic level when you're done with it.
|
2,915,614 | 2,916,272 | Looking for a variety of Windows Form tutorials for visual studio.NET C++ | Looking for a variety of Windows Form (winforms) tutorials for visual studio.NET C++
I found a few basic ones:
How to: Create a Windows Forms Application
Walkthrough: Retrieving Dialog Box Information Collectively Using Objects
Any others?
Thank You.
| There are many excellent books available. Maybe you are looking for videos? Start at the bottom. You are not going to find anything at all that will be specific to C++/CLI, just about nobody uses that language to create WF projects.
|
2,915,791 | 2,915,802 | Why is dereferencing a pointer called dereferencing? | Why is dereferencing called dereferencing?
I'm just learning pointers properly, and I'd like to know why dereferencing is called that. It confused me as it sounds like you are removing a reference, rather than going via the pointer to the destination.
Can anyone explain why it is called this?
To me something like destination or pointed_to_value would make more sense.
| A pointer refers to an object. Ergo, we dereference the pointer (or, get the referent of the pointer) to get the object pointed-to.
The de- prefix most likely comes from the Latin preposition meaning from; I suppose you could think of dereference as meaning "to obtain the referent (or object) from the reference."
|
2,915,825 | 2,925,828 | how to excute a simple query use sqlapi++ with oracle | here is the code:
cmd1.setCommandText("select * from lp.human_tb_meta_sex");
cmd1.Execute();
while (cmd1.FetchNext())
{
SAString sas=cmd1.Field("id").asString();
cout<<"sas id:"<
it gave me ORA-00932 error...I dont know why..?
| Presumably "id" is the primary key.
If it is defined as a NUMBER in the database, that could include fractions (eg 3.5).
If you define it as NUMBER(10,0) then it will always be an integer.
Since you are trying to pull it out as a String [.asString()] there could be a conversion issue.
|
2,915,972 | 2,916,361 | Equvalent c++0x program withought using boost threads | I have the below simple program using boost threads, what would be the changes needed to do the same in c++0X
#include<iostream>
#include<boost/thread/thread.hpp>
boost::mutex mutex;
struct count
{
count(int i): id(i){}
void operator()()
{
boost::mutex::scoped_lock lk(mutex);
for(int i = 0 ; i < 10000 ; i++)
{
std::cout<<"Thread "<<id<<"has been called "<<i<<" Times"<<std::endl;
}
}
private:
int id;
};
int main()
{
boost::thread thr1(count(1));
boost::thread thr2(count(2));
boost::thread thr3(count(3));
thr1.join();
thr2.join();
thr3.join();
return 0;
}
| No changes to speak of...
#include <iostream>
#include <thread>
std::mutex mutex;
struct count {
count(int i): id(i){}
void operator()()
{
std::lock_guard<std::mutex> lk(mutex); // this seems rather silly...
for(int i = 0 ; i < 10000 ; ++i)
std::cout << "Thread " << id << "has been called " << i
<< " Times" << std::endl;
}
private:
int id;
};
int main()
{
std::thread thr1(count(1));
std::thread thr2(count(2));
std::thread thr3(count(3));
thr1.join();
thr2.join();
thr3.join();
}
|
2,915,992 | 2,916,158 | Qt Creator / QMake Linker Libraries | I'm using SFML, and I want to use Qt Creator in conjunction with it. When I'm compiling manually, I supply the following arguments to the linker -lsfmlsystem -lsfmlwindow.
How do I do this if I'm using Qt Creator and (I think) QMake?
| Just add
LIBS += -L/path/to/sfml -lsfmlsystem -lsfmlwindow
to the .pro file.
You can open project files with QtCreator from the Projects view of the sidebar or searching for it via Ctrl-K. (BTW, the sidebar is not the list of icons down the left, it's the pane to the right of that which can be shown/hidden with Alt-0.)
|
2,916,008 | 2,916,060 | C++: Syntax for map where Data type is function? | In C#, what I want would look something like this:
IDictionary<string, action()> dict = new Dictionary<string, action()>();
How do I do this in C++? This gives compiler errors:
map<string, void()> exercises;
| Use boost::function, a polymorphous wrapper for any object that can be called with your signature (including functions, function objects etc).
map<string, function<void()>> ...;
Note that the new C++ standard has already included function in <functional>.
To explain the backgrounds: The only builtin mechanism of this kind in C++ are old C-style function pointers (void (*)()). These are extremely low-level, basically just storing the memory address of a function, and therefore far from even coming close to the power of C#'s delegates.
You can't create anonymous functions, neither can you refer to a particular object's member functions or any variables or data (closures).
Thus, one often utilizes so called functors which are classes that mimic the behaviour of a function by overloading the operator (). In combination with templates, they are used whereever ordinary function pointers can be used.
The problem is that these functors often consist of peculiar or anonymous types that can't be referred to conveniently.
The function is the coolest way to address them all - Everything that behaves like a function, including cool new lambda-style expressions.
function<void()> f = []() { cout << "Hello, World"> };
f();
|
2,916,061 | 2,916,541 | Detecting regular expression in content during parse | I am writing a simple parser for C. I was just running it with some other language files (for fun - to see the extent of C-likeness and laziness - don't wanna really write separate parsers for each language if I can avoid it).
However the parser seems to break down for JavaScript if the code being parsed contains regular expressions...
Case 1:
For example, while parsing the JavaScript code snippet,
var phone="(304)434-5454"
phone=phone.replace(/[\(\)-]/g, "")
//Returns "3044345454" (removes "(", ")", and "-")
The '(', '[' etc get matched as starters of new scopes, which may never be closed.
Case 2:
And, for the Perl code snippet,
# Replace backslashes with two forward slashes
# Any character can be used to delimit the regex
$FILE_PATH =~ s@\\@//@g;
The // gets matched as a comment...
How can I detect a regular expression within the content text of a "C-like" program-file?
| It is impossible.
Take this, for example:
m =~ s/a/b/g;
Could be both C or perl.
One minute's thinking reveals, that the number of perl style regular expressions that are also sntyctically valid C expressions is infinite.
Another example:
m+foo *bar[index]+i
The best you can get is some extreme vague guesswork. The difficulty stems from the fact that a regular expression is a sequence of characters that can be virtually everything.
You better clean up your error handling. A parser should not "break down" if some parenthesis are missing or superfluous ones are seen.
|
2,916,117 | 2,916,418 | OpenGL Nothing will Display | Why can't I get anything to display with this code?
#include <iostream>
#include "GL/glfw.h"
#ifndef MAIN
#define MAIN
#include "GL/gl.h"
#include "GL/glu.h"
#endif
using namespace std;
void display();
int main()
{
int running = GL_TRUE;
glfwInit();
if( !glfwOpenWindow( 640,480, 0,0,0,0,0,0, GLFW_WINDOW ) )
{
glfwTerminate();
return 0;
}
while( running )
{
//GL Code here
display();
glfwSwapBuffers();
// Check if ESC key was pressed or window was closed
running = !glfwGetKey( GLFW_KEY_ESC ) &&
glfwGetWindowParam( GLFW_OPENED );
}
glfwTerminate();
return 0;
}
void display()
{
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0,0,640,480);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//glTranslatef(0, 0, -2);
glBegin(GL_POLYGON);
glColor3f(1.0, 0.2, 0.2);
glVertex3f(0.25, 0.25, 0.0);
glVertex3f(0.75, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0);
glVertex3f(0.25, 0.75, 0.0);
glEnd();
glFlush();
}
| I think the issue is that when you don't specify a coordinate system
eg
void glOrtho(GLdouble left,
GLdouble right,
GLdouble bottom,
GLdouble top,
GLdouble nearVal,
GLdouble farVal);
or
void glFrustum(GLdouble left,
GLdouble right,
GLdouble bottom,
GLdouble top,
GLdouble nearVal,
GLdouble farVal);
the default coordinate system is:
-1, 1, -1, 1, -1, 1
so the glTranslate moves the object outside the coordinate system and openGL clips the object.
If you change the glTranslate() call to translate by 1.0 the object is visible.
|
2,916,191 | 2,916,250 | C/C++ - Convert 24-bit signed integer to float | I'm programming in C++. I need to convert a 24-bit signed integer (stored in a 3-byte array) to float (normalizing to [-1.0,1.0]).
The platform is MSVC++ on x86 (which means the input is little-endian).
I tried this:
float convert(const unsigned char* src)
{
int i = src[2];
i = (i << 8) | src[1];
i = (i << 8) | src[0];
const float Q = 2.0 / ((1 << 24) - 1.0);
return (i + 0.5) * Q;
}
I'm not entirely sure, but it seems the results I'm getting from this code are incorrect. So, is my code wrong and if so, why?
| You are not sign extending the 24 bits into an integer; the upper bits will always be zero. This code will work no matter what your int size is:
if (i & 0x800000)
i |= ~0xffffff;
Edit: Problem 2 is your scaling constant. In simple terms, you want to multiply by the new maximum and divide by the old maximum, assuming that 0 remains at 0.0 after conversion.
const float Q = 1.0 / 0x7fffff;
Finally, why are you adding 0.5 in the final conversion? I could understand if you were trying to round to an integer value, but you're going the other direction.
Edit 2: The source you point to has a very detailed rationale for your choices. Not the way I would have chosen, but perfectly defensible nonetheless. My advice for the multiplier still holds, but the maximum is different because of the 0.5 added factor:
const float Q = 1.0 / (0x7fffff + 0.5);
Because the positive and negative magnitudes are the same after the addition, this should scale both directions correctly.
|
2,916,201 | 2,916,225 | Why function is weightless? | Why having function in my class doesn't change size of this class? This info must be stored somewhere, but where?
| You can think of a member function as being just like any other function, except that it has an extra, hidden parameter that takes a pointer to the instance on which the member function was called.
For example, this:
class C
{
void f(int i) { }
};
might be implemented (at least conceptually) as:
void C_f(C* this, int i) { }
If it was a const member function, then the hidden parameter would have the type const C* instead. Note that the situation isn't nearly this simple for virtual member functions.
|
2,916,243 | 2,916,632 | Detect When Network Cable Unplugged | Windows knows when you have removed the network cable from your NIC. Is there a programmatic way to determine this via API in C++?
Note: I am not using .NET and this is for a closed LAN (not connected to Internet ever)
| Raymond Chen blogged about something similar recently. Here is the relevant documentation. I think the MIB_IPADDR_DISCONNECTED flag is what you are looking for.
|
2,916,279 | 2,916,408 | STLifying C++ classes | I'm trying to write a class which contains several std::vectors as data members, and provides a subset of vector's interface to access them:
class Mesh
{
public:
private:
std::vector<Vector3> positions;
std::vector<Vector3> normals;
// Several other members along the same lines
};
The main thing you can do with a mesh is add positions, normals and other stuff to it. In order to allow an STL-like way of accessing a Mesh (add from arrays, other containers, etc.), I'm toying with the idea of adding methods like this:
public:
template<class InIter>
void AddNormals(InIter first, InIter last);
Problem is, from what I understand of templates, these methods will have to be defined in the header file (seems to make sense; without a concrete iterator type, the compiler doesn't know how to generate object code for the obvious implementation of this method).
Is this actually a problem? My gut reaction is not to go around sticking huge chunks of code in header files, but my C++ is a little rusty with not much STL experience outside toy examples, and I'm not sure what "acceptable" C++ coding practice is on this.
Is there a better way to expose this functionality while retaining an STL-like generic
programming flavour? One way would be something like this:
(end list)
class RestrictedVector<T>
{
public:
RestrictedVector(std::vector<T> wrapped)
: wrapped(wrapped) {}
template <class InIter>
void Add(InIter first, InIter last)
{
std::copy(first, last, std::back_insert_iterator(wrapped));
}
private:
std::vector<T> wrapped;
};
and then expose instances of these on Mesh instead, but that's starting to reek a little of overengineering :P Any advice is greatly appreciated!
| these methods will have to be defined in the header file
They have to be defined in a header file, so that if they're used then they're available in the translation unit where the template function is instantiated. If you're worried about too many templates in header files, slowing down compilation of translation units which use Mesh but don't actually use that template function, then you could move the implementation into a separate header file. Makes life slightly more complicated for clients, deciding whether to include the "full fat" class header or not, but it's not actually difficult.
Alternatively, for this particular example you could define an output iterator for Mesh, which appends Normals. Then clients with their arbitrary iterators can do:
std::copy(first, last, mymesh.normalAdder());
The only header they need with template code in it is <algorithm>, which they quite possibly have already.
To do it yourself, the object returned by normalAdder() needs to overload operator++() and operator*(), which itself needs to return a proxy object (usually *this) which implements operator=(const &Vector3). That appends to the vector of normals. But all that is non-template code, and can be implemented in your .cpp file.
Again in this example, normalAdder() could just return std::back_inserter(this.normals);, a template from <iterator>.
As to whether you need to worry about it - I think when compilation times go skyward, it's more frequently due to unnecessary dependencies rather than due to small bits of template code in headers. Some large projects seem to need drastic measures, but personally I haven't worked with anything over about 100 files or so.
|
2,916,285 | 2,921,644 | handling pointer to member functions within hierachy in C++ | I'm trying to code the following situation:
I have a base class providing a framework for handling events. I'm trying to use an array of pointer-to-member-functions for that. It goes as following:
class EH { // EventHandler
virtual void something(); // just to make sure we get RTTI
public:
typedef void (EH::*func_t)();
protected:
func_t funcs_d[10];
protected:
void register_handler(int event_num, func_t f) {
funcs_d[event_num] = f;
}
public:
void handle_event(int event_num) {
(this->*(funcs_d[event_num]))();
}
};
Then the users are supposed to derive other classes from this one and provide handlers:
class DEH : public EH {
public:
typedef void (DEH::*func_t)();
void handle_event_5();
DEH() {
func_t f5 = &DEH::handle_event_5;
register_handler(5, f5); // doesn't compile
........
}
};
This code wouldn't compile, since DEH::func_t cannot be converted to EH::func_t. It makes perfect sense to me. In my case the conversion is safe since the object under this is really DEH. So I'd like to have something like that:
void EH::DEH_handle_event_5_wrapper() {
DEH *p = dynamic_cast<DEH *>(this);
assert(p != NULL);
p->handle_event_5();
}
and then instead of
func_t f5 = &DEH::handle_event_5;
register_handler(5, f5); // doesn't compile
in DEH::DEH()
put
register_handler(5, &EH::DEH_handle_event_5_wrapper);
So, finally the question (took me long enough...):
Is there a way to create those wrappers (like EH::DEH_handle_event_5_wrapper) automatically?
Or to do something similar?
What other solutions to this situation are out there?
Thanks.
| Instead of creating a wrapper for each handler in all derived classes (not even remotely a viable approach, of course), you can simply use static_cast to convert DEH::func_t to EH::func_t. Member pointers are contravariant: they convert naturally down the hierarchy and they can be manually converted up the hierarchy using static_cast (opposite of ordinary object pointers, which are covariant).
The situation you are dealing with is exactly the reason the static_cast functionality was extended to allow member pointer upcasts. Moreover, the non-trivial internal structure of a member function pointer is also implemented that way specifically to handle such situations properly.
So, you can simply do
DEH() {
func_t f5 = &DEH::handle_event_5;
register_handler(5, static_cast<EH::func_t>(f5));
........
}
I would say that in this case there's no point in defining a typedef name DEH::func_t - it is pretty useless. If you remove the definition of DEH::func_t the typical registration code will look as follows
DEH() {
func_t f5 = static_cast<func_t>(&DEH::handle_event_5);
// ... where `func_t` is the inherited `EH::func_t`
register_handler(5, f5);
........
}
To make it look more elegant you can provide a wrapper for register_handler in DEH or use some other means (a macro? a template?) to hide the cast.
This method does not provide you with any means to verify the validity of the handler pointer at the moment of the call (as you could do with dynamic_cast in the wrapper-based version). I don't know though how much you care to have this check in place. I would say that in this context it is actually unnecessary and excessive.
|
2,916,358 | 2,916,394 | immutable strings vs std::string | I've recent been reading about immutable strings Why can't strings be mutable in Java and .NET? and Why .NET String is immutable? as well some stuff about why D chose immutable strings. There seem to be many advantages.
trivially thread safe
more secure
more memory efficient in most use cases.
cheap substrings (tokenizing and slicing)
Not to mention most new languages have immutable strings, D2.0, Java, C#, Python, etc.
Would C++ benefit from immutable strings?
Is it possible to implement an immutable string class in c++ (or c++0x) that would have all of these advantages?
update:
There are two attempts at immutable strings const_string and fix_str. Neither have been updated in half a decade. Are they even used? Why didn't const_string ever make it into boost?
| As an opinion:
Yes, I'd quite like an immutable string library for C++.
No, I would not like std::string to be immutable.
Is it really worth doing (as a standard library feature)? I would say not. The use of const gives you locally immutable strings, and the basic nature of systems programming languages means that you really do need mutable strings.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.