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 |
|---|---|---|---|---|
1,568,807 | 1,568,830 | How to define (non-method) functions in header libraries | When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings?
When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains about redefinitions. One way around this is to make the functions static, but this reproduces the code in each translation unit (BTW, can linkers safely dereplicate these?). Furthermore, this triggers compiler warnings about the function being unused.
I was trying to look for an example of a free-floating function in Boost, but I couldn't find one. Is the trick to contain everything in a class (or template)?
| If you really want to define the function (as opposed to declaring it), you'll need to use inline to prevent linker errors.
Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.
|
1,568,949 | 1,568,964 | Why isn't the gcc 4.x.x series compilers installed by MinGW by default? | Currently, MinGW's only installs the 3.x.x series of the gcc compiler by default. However, it looks like the 4.x.x series of compilers have been out for some time, and as others have mentioned, it seems to work just fine. Is there any reason why it hasn't moved to the 4.x.x versions yet, and any reason why I shouldn't use the newer versions of gcc?
| GCC4's C++ ABI has changed from GCC3, and it includes a lot of new features (like its tree vectorization) that a lot of people still consider "experimental." There are still a few Linux distributions still using GCC3 for that reason.
|
1,569,085 | 1,569,103 | Prevent Duplicate Entry into HashTable C++ | I was wondering if i could get some help to prevent a duplicate entry into my hashtable:
bool hashmap::put(const stock& s, int& usedIndex, int& hashIndex, int& symbolHash)
{
hashIndex = this->hashStr( s.m_symbol ); // Get remainder, Insert at that index.
symbolHash = (int&)s.m_symbol;
usedIndex = hashIndex;
while ( hashTable[hashIndex].m_symbol != NULL ) // collision found
{
++usedIndex %= maxSize; // if necessary wrap index around
if ( hashTable[usedIndex].m_symbol == NULL )
{
hashTable[usedIndex] = s;
return true;
}
}
hashTable[hashIndex] = s; // insert if no collision
return true;
}
The paramater hashIndex uses a java algorithm to generate an appropriate index to insert into the table. The usedIndex paramater is where I insert into the table when a collision is found; symbolHash just gets the address of the name passed in. stock is a class object.
My question is just, how do i prevent a duplicate entry?
| Just look at the objects you're storing in that index. If you have to move the index because of a collision check those also. If they match what you're trying to store, throw an exception or something.
I'm guessing at your code so...
bool hashmap::put(const stock& s, int& usedIndex, int& hashIndex, int& symbolHash)
{
hashIndex = this->hashStr( s.m_symbol ); // Get remainder, Insert at that index.
symbolHash = (int&)s.m_symbol;
usedIndex = hashIndex;
if(hastTable[usedIndex].m_symbol == s.m_symbol){
return false;
}
while ( hashTable[hashIndex].m_symbol != NULL ) // collision found
{
++usedIndex %= maxSize; // if necessary wrap index around
if ( hashTable[usedIndex].m_symbol == NULL )
{
hashTable[usedIndex] = s;
return true;
}else if(hastTable[usedIndex].m_symbol == s.m_symbol){
return false;
}
}
hashTable[hashIndex] = s; // insert if no collision
return true;
}
|
1,569,254 | 1,569,268 | LNK2019 and LNK1120 with templated function | After having some problems with these two linker errors on SO, I have them again. However, this time the source seems to lie at another point.
compiler error shows that it cannot find a function with signature ""public: unsigned int __thiscall MyClass::myFunction<unsigned int>(int)const ".
However, moving the contents of myClass.cpp to main.cpp works. Don't know why (all other content of myClass.cpp doesn't have this problem. (other functions are not templated).
myClass.h
#ifndef X
#define X
class MyClass {
public:
template<class T>
T myFunction (int someArgument) const;
};
#endif
myClass.cpp
#include "myClass.h"
template<class T>
T MyClass::myFunction (int someArgument) const {
return T();
}
main.cpp
#include "myClass.h"
int main () {
MyClass a();
a.myFunction<unsigned int>(42);
return 0;
}
What can I do to fix this problem?
| Because in main.cpp, the compiler can find the definition of the template function.
Templates cannot be compiled, the compiler needs to be able to see the definition of the file, and it's can't see across files.
Either include myClass.cpp in myClass.h, or just define everything in the header.
|
1,569,261 | 1,569,327 | What is the difference, usage-wise, between defines/macros/structs and consts/funcs/classes? (C++) | I know that the difference between defines and constants is that constants have type, and that between macros and functions, functions are called, and typed, whereas macros are untyped inline. Not so much the difference between structs and classes, but I don't think there is one, besides the public/private default thing (and I'm taking about only C++ here, not C).
Anyways, are there any times that it would be more efficient, beneficial, or, at the very least, cleaner code to use defines/macros/structs than it would be to use the C++ versions, constants, functions, and classes?
Specifically, and because this is only one without a clear difference (at least in the final program) between them, is it ever better to use structs than classes, and if there isn't efficiency-wise, what conventions for using them do you use?
| Typically, in a C++ program I might use a struct for a simple aggregation of data, such as a Point structure that contains an x and a y. I would use a class for objects that have behaviour (member functions) associated with them.
This is just a convention of course, since the compiler treats them almost identically except for the two details mentioned above (default inheritance and default member visibility).
|
1,569,554 | 1,569,560 | Is putting a function within an if statement efficient? (C++) | I've seen statements like this
if(SomeBoolReturningFunc())
{
//do some stuff
//do some more stuff
}
and am wondering if putting a function in an if statement is efficient, or if there are cases when it would be better to leave them separate, like this
bool AwesomeResult = SomeBoolReturningFunc();
if(AwesomeResult)
{
//do some other, more important stuff
}
...?
| I'm not sure what makes you think that assigning the result of the expression to a variable first would be more efficient than evaluating the expression itself, but it's never going to matter, so choose the option that enhances the readability of your code. If you really want to know, look at the output of your compiler and see if there is any difference. On the vast majority of systems out there this will likely result in identical machine code.
|
1,569,726 | 1,569,760 | Difference: std::runtime_error vs std::exception() | What is the difference between std::runtime_error and std::exception? What is the appropriate use for each? Why are they different in the first place?
| std::exception is the class whose only purpose is to serve as the base class in the exception hierarchy. It has no other uses. In other words, conceptually it is an abstract class (even though it is not defined as abstract class in C++ meaning of the term).
std::runtime_error is a more specialized class, descending from std::exception, intended to be thrown in case of various runtime errors. It has a dual purpose. It can be thrown by itself, or it can serve as a base class to various even more specialized types of runtime error exceptions, such as std::range_error, std::overflow_error etc. You can define your own exception classes descending from std::runtime_error, as well as you can define your own exception classes descending from std::exception.
Just like std::runtime_error, standard library contains std::logic_error, also descending from std::exception.
The point of having this hierarchy is to give user the opportunity to use the full power of C++ exception handling mechanism. Since 'catch' clause can catch polymorphic exceptions, the user can write 'catch' clauses that can catch exception types from a specific subtree of the exception hierarchy. For example, catch (std::runtime_error& e) will catch all exceptions from std::runtime_error subtree, letting all others to pass through (and fly further up the call stack).
P.S. Designing a useful exception class hierarchy (that would let you catch only the exception types you are interested in at each point of your code) is a non-trivial task. What you see in standard C++ library is one possible approach, offered to you by the authors of the language. As you see, they decided to split all exception types into "runtime errors" and "logic errors" and let you proceed from there with your own exception types. There are, of course, alternative ways to structure that hierarchy, which might be more appropriate in your design.
Update: Portability Linux vs Windows
As Loki Astari and unixman83 noted in their answer and comments below, the constructor of the exception class does not take any arguments according to C++ standard. Microsoft C++ has a constructor taking arguments in the exception class, but this is not standard. The runtime_error class has a constructor taking arguments (char*) on both platforms, Windows and Linux. To be portable, better use runtime_error.
(And remember, just because a specification of your project says your code does not have to run on Linux, it does not mean it does never have to run on Linux.)
|
1,569,778 | 1,569,788 | C++ interview preparation | I have a Phone interview coming up next with with a company which works in financial software industry. The interview is mainly going to be in C++ and problem solving and logic. Please tell me the method of preparation for this interview. I have started skimming through Thinking in C++ and brushing up the concepts. Is there any other way I can prepare?? Please help.
Edit:
Thank you all everyone for the advice. I just want to add that I am currently fresh out of grad school and have no previous experience. So Can you suggest some type of questions that will be asked to new grads??
| Make sure you know your basic data structures and algorithms. You're more likely to be asked about that stuff than something higher up the food chain. Those are usually saved for the in-person interview.
Put another way: be solid with the fundamentals and solid with your C++ syntax. Also, knowledge of common libraries like STL and Boost couldn't hurt...but be sure you know what those libraries give you! In the end phone screens are there to cull out people who can't do the basics. Prove you can and you should move on to the next step. Good luck!
Here's some links of interview questions to check out:
C++ Interview Questions @ DevBistro
C++ Interview Questions @ Blogspot
C++ Interview Questions @ FYI Center
Steve Yegge's Five Essential Phone Screen Questions (added this in response to your edit. This isn't C++-only, but a lot of it applies to C++ and I think would be a good read in your situation).
Now, for completion's sake, some books:
Scott Meyers "Effective" series (Effective C++, More Effective C++, Effective STL)
Herb Sutter's "Exceptional" series (Exceptional C++, More Exceptional C++, Exceptional C++ Style)
The C++ Standard Library by Josuttis
C++ Primer by Lippman et al
Stroustrup's text as a reference
|
1,569,829 | 1,570,220 | Open Source C++ game engine math libraries? | I'm looking for a free to use game engine math library. Specifically I'd like a good matrix and vector implementation. And everything needed to move objects in 3D space. Does anyone know any good ones? I'm targeting OpenGL. I'd like to write them myself but don't have the time.
| I'd recommend OpenGL Mathematics (GLM)
Though if you want physics with your math you could go with Bullet Physics Library
Finally if you want an entire engine i'd go with OGRE
|
1,569,939 | 1,571,089 | Rendering different triangle types and triangle fans using vertex buffer objects? (OpenGL) | About half of my meshes are using triangles, another half using triangle fans.
I'd like to offload these into a vertex buffer object but I'm not quite sure how to do this. The triangle fans all have a different number of vertices... for example, one might have 5 and another 7.
VBO's are fairly straight forward using plain triangles, however I'm not sure how to use them with triangle fans or with different triangle types. I'm fairly sure I need an index buffer, but I'm not quite sure what I need to do this.
I know how many vertices make up each fan during run time... I'm thinking I can use that to call something like glArrayElement
Any help here would be much appreciated!
| VBOs and index buffers are an orthogonal things.
If you're not using index buffers yet, maybe it is wiser to move one step at a time.
So... regarding your question. If you put all your triangle fans in a vbo, the only thing you need to draw them is to setup your vbo and pass the index in it for your fan start
glBindBuffer(GL_VERTEX_BUFFER, buffer);
glVertexPointer(3, GL_FLOAT, 0, NULL); // 3 floats per vertex
for each i in fans
glDrawArrays(GL_TRIANGLE_FAN, indef_of_first_vertex_for_fan[i], fan_vertex_count[i])
Edit: I'd have to say that you're probably better off transforming your fans to a regular triangle set, and use glDrawArrays(GL_TRIANGLES) for all your triangles. A call per primitive is rarely efficient.
|
1,569,962 | 1,588,904 | Any good C++/C NNTP libs? | I came across some crusty and limited efforts awhile back but I was wondering if there was something truly functional that I missed, preferably in C++ but C is better than nothing.
| W3Cs libwww exposes a complete, standards compliant NNTP implementation.
It is cross platform and (partially) well documented.
User guide
The API-of-interest: WWWNews client API
I hope this is helpful.
|
1,570,330 | 1,570,616 | Why does memcpy fail copying to a local array member of a simple object? | Classic memcpy gotcha with C arrays as function arguments. As pointed out below, I have an error in my code but the erroneous code worked in a local context!
I just encountered this weird behaviour in a porting job, where I'm emulating the Macintosh Picture opcode playback using objects. My DrawString object was drawing garbage on playback because it apparently failed to copy the string argument. The following is a test case I wrote - note how a manual copying loop works but memcpy fails. Tracing in the Visual Studio debugger shows the memcpy ovewrites the destination with garbage.
Memcpy on two local Str255 arrays works fine.
When one of them is a member in an object on the stack, it fails (in other testing it also fails when the object is on the heap).
The following sample code shows the memcpy being invoked in an operator=. I moved it there after it failed in a constructor but there was no difference.
typedef unsigned char Str255[257];
// snippet that works fine with two local vars
Str255 Blah("\004Blah");
Str255 dest;
memcpy(&dest, &Blah, sizeof(Str255)); // THIS WORKS - WHY HERE AND NOT IN THE OBJECT?
/*!
class to help test CanCopyStr255AsMember
*/
class HasMemberStr255 {
public:
HasMemberStr255()
{
mStr255[0] = 0;
}
HasMemberStr255(const Str255 s)
{
for (int i = 0; i<257; ++i)
{
mStr255[i] = s[i];
if (s[i]==0)
return;
}
}
/// fails
void operator=(const Str255 s) {
memcpy(&mStr255, &s, sizeof(Str255));
};
operator const Str255&() { return mStr255; }
private:
Str255 mStr255;
};
-
/*!
Test trivial copying technique to duplicate a string
Added this variant using an object because of an apparent Visual C++ bug.
*/
void TestMacTypes::CanCopyStr255AsMember()
{
Str255 initBlah("\004Blah");
HasMemberStr255 blahObj(initBlah);
// using the operator= which does a memcpy fails blahObj = initBlah;
const Str255& dest = blahObj; // invoke cast operator to get private back out
CPPUNIT_ASSERT( dest[0]=='\004' );
CPPUNIT_ASSERT( dest[1]=='B' );
CPPUNIT_ASSERT( dest[2]=='l' );
CPPUNIT_ASSERT( dest[3]=='a' );
CPPUNIT_ASSERT( dest[4]=='h' );
CPPUNIT_ASSERT( dest[5]=='\0' ); // trailing null
}
| This is probably a good example of why (in my opinion) it's a bad idea to typedef array types.
Unlike in other contexts, in function declarations a parameter of array type is always adjusted to an equivalent pointer type. When an array is passed to the function it always decays into a pointer to the first element.
These two snippets are equivalent:
typedef unsigned char Str[257];
Str src = "blah";
Str dst;
memcpy( &dst, &src, sizeof(Str) ); // unconventional
unsigned char src[257] = "blah";
unsigned char dst[257];
memcpy(&dst, &src, sizeof(unsigned char[257])); // unconventional
In this latter case &dst and &src are both of type unsigned char (*)[257] but the value of these pointers are the same as the value of pointers to the first element of each array, which is what dst and src would decay into if passed directly into memcpy like this.
memcpy(dst, src, sizeof(unsigned char[257])); // more usual
memcpy takes void* arguments so the types of the original pointers don't matter, only their values.
Because of the rule for parameter declarations (an array type of any or unspecified size is adjusted to the equivalent pointer type), these declarations for fn are all equivalent:
typedef unsigned char Str[257];
void fn( Str dst, Str src );
void fn( unsigned char dst[257], unsigned char src[257] );
void fn( unsigned char dst[], unsigned char src[] );
void fn( unsigned char* dst, unsigned char* src );
Looking at this code, it is more obvious that the values being passed into memcpy in this case are pointers to the passed pointers, and not pointers to the actual unsigned char arrays.
// Incorrect
void fn( unsigned char* dst, unsigned char* src )
{
memcpy(&dst, &src, sizeof(unsigned char[257]));
}
With a typedef, the error is not so obvious, but still present.
// Still incorrect
typedef unsigned char Str[257];
void fn( Str dst, Str src )
{
memcpy(&dst, &src, sizeof(Str));
}
|
1,570,364 | 1,570,743 | How to capture ping's return value in C++ | Does anyone know, how to capture ping's return value in c++? According to this link:
ping should return 0 on success, 1 on failure such as unknown host, illegal packet size, etc. and 2 On a unreachable host or network.
In C++ I called ping with the system (), e.g. int ret = system("ping 192.168.1.5");.
My problem is, that ret's value is 0 or 1. It will never 2! If I think correctly, this is because, this return value I get, is the system functions return value, not ping's. So how could i get ping's return vlaue?
Thanks in advance!
kampi
Edit:
Right now i use this system("ping 192.169.1.5 > ping_res.txt"); but i don't want to work with files (open, and read them), that's why i want to capture, th return value , if possible :)
| If you are on Windows, it might be better to use IcmpSendEcho2 directly to implement the ping functionality in your application.
|
1,570,377 | 1,570,396 | C++ linked list memory management | I'm attempting to craft my own basic singly linked list in C++ as a learning exercise, and I'm encountering some difficulty in the memory management department. As it stands I have...
A 'Node' class:
class Node
{
public:
char *value;
Node *next;
Node();
~Node();
};
Node::Node()
{
}
Node::~Node()
{
delete[] value;
}
And then my list (I've omitted certain method calls for brevity):
class LinkedList
{
private:
Node *head;
public:
LinkedList();
~LinkedList();
void Add(char **x);
};
LinkedList::LinkedList()
{
head = 0;
}
LinkedList::~LinkedList()
{
Node *temp;
Node *current = head;
while(current)
{
temp = current;
current = current->next;
delete temp;
}
}
void LinkedList::Add(char **x)
{
Node *nodeToAdd = new Node();
nodeToAdd->value = *x;
nodeToAdd->next = NULL;
Node *current = head;
if(!head)
{
head = nodeToAdd;
return;
}
while(current->next)
{
current = current->next;
}
current->next = nodeToAdd;
}
I'm attempting to use this code as follows (again I've omitted things for brevity):
int main()
{
LinkedList *list = new LinkedList();
char *alpha = "alpha";
char *beta = "beta";
char *charlie = "charlie";
char *delta = "delta";
char *echo = "echo";
list->Add(&alpha);
list->Add(&beta);
list->Add(&charlie);
list->Add(&delta);
list->Add(&echo);
delete list;
}
The last call in main to delete the list produces an error:
Debug Assertion Failed! Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
What am I doing wrong here?
| The data pointed to by the various Node::value aren't dynamically allocated, so you shouldn't delete them. Applying the concept of "ownership", nodes should either make their own copies of data, which they own and can delete, or nodes don't own data, so they shouldn't be responsible for deleting it.
You can also implement multiple ownership using reference counting, like Objective-C does (see Objective-C Memory Management Rules for more info) but you have to be careful to avoid ownership cycles. You often find some type of reference counting in third-party smart pointers, such as Boost's smart_ptr library. Since you're doing this for the learning experience, it may make more sense to roll your own than use a library. Of course, you could also use a library for now, letting you focus on whatever you're trying to learn.
One day a student came to Moon and said: “I understand how to make a better garbage collector. We must keep a reference count of the pointers to each cons.”
Moon patiently told the student the following story:
“One day a student came to Moon and said: ‘I understand how to make a better garbage collector...
|
1,570,382 | 1,574,863 | Why is my DLL failing to register? | I am building a project in VS2005 and several of my DLLs are failing to register. The error message I am getting in Visual Studio is:
Project : error PRJ0019: A tool returned an error code from "Registering ActiveX Control..."
which is nicely vague. When I register the DLL manually through the command line (using regsv32.exe, I get the following error:
LoadLibrary("test.ocx") failed - This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix the problem.
I ran Dependency Walker (depends.exe) on the culprit .ocx file but it isn't showing any obvious problems.
I have also done a re-build but I'm still getting the same problem.
Any suggestions as to how I could determine the cause of this failure to register?
| Microsoft had recently released a Security Update for ATL (KB971090). It is un update on top of MSVS2005sp1 and it's both compilate-time and runtime compatibility breaker. Check if your building environment has this patch.
References:
ATL Security Update:
http://msdn.microsoft.com/en-us/visualc/ee309358.aspx
Breaking changes in ATL:
http://msdn.microsoft.com/de-de/library/ms235654.aspx
And this is a must read:
http://tedwvc.wordpress.com/2009/08/10/avoiding-problems-with-vc2005-sp1-security-update-kb971090/
|
1,570,471 | 1,570,560 | C++ inheritence for on-stack objects | I have a base class, Token. It has no implementation and as such acts as a marker interface. This is the type that will be used by callers.
{
Token t = startJob(jobId);
// ... (tasks)
// t falls out of scope, destructors are called
}
I have a derived class, LockToken. It wraps around a mutex and insures the lock is acquired during construction and released during destruction. The startJob method is a factory method in the sense that it decides whether to return a Token (providing no locking) or a LockToken (providing locking).
Token startJob(int jobId)
{
return (jobId>0) ? LockToken() : Token() ;
}
When startJob would return a base instance (a Token), everything works well. In the other case (jobId>0), there is a copy made of the derived instance to the base instance. In other workds, a different Token is copy-constructed from the LockToken and the original LockToken falls out of scope too soon, releasing the lock inside the scope of startJob.
How do I get out of this? Can I change startJob so that it returns or outputs a truly covariant Token (meaning it may be a LockToken)?
| You are returning a Token by value. That means that you are not returning a LockToken, but rather a Token copy constructed from your LockToken instance.
A much better approach would be to use boost::shared_ptr. That way your clients can copy things around without needing to worry about deletion. Something like this:
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<void> Token;
Token startJob(int jobId)
{
if (jobId < 1) return shared_ptr<void>();
return shared_ptr<void>(new LockToken);
}
void use_it()
{
Token t = startJob(jobId);
// ....
// Destructors are called
}
Note that you no longer need a Token class that does nothing, and the LockToken class is now an implementation detail that is entirely hidden from clients, giving you scope for doing all kinds of other things when the Token goes out of scope.
|
1,570,516 | 1,570,596 | Warning linking boost lib in WDK build ("LNK4217: locally defined symbol _ imported in function _") | I'm building the below example boost-consuming user-mode app with the WDK, but I'm getting the following errors when linking with the boost libraries that I built earlier using bootstrap and .\bjam, from the same terminal window.
IIUC, MSDN says it's because the (hideously mangled) function - which appears to be a C++ std lib function - is marked as a DLL import, yet I have a local definition. How did this happen? Is there a way to work around this?
See also: a loosely related question.
C:\exp>more exp.cpp
#pragma warning(disable: 4512)
#include <boost/program_options.hpp>
int __cdecl main() {
boost::program_options::options_description desc("Allowed options");
return 0;
}
C:\exp>more sources
TARGETNAME=exp
TARGETTYPE=PROGRAM
USE_MSVCRT=1
USE_STL=1
USE_NATIVE_EH=1
MSC_WARNING_LEVEL=/W4 /WX
_NT_TARGET_VERSION= $(_NT_TARGET_VERSION_WINXP)
INCLUDES=..\boost_1_40_0
SOURCES=exp.cpp
UMTYPE=console
UMBASE=0x400000
TARGETLIBS = $(SDK_LIB_PATH)\ws2_32.lib ..\boost_1_40_0\stage\lib\libboost_program_options-vc100-mt.lib
C:\exp>build
BUILD: Compile and Link for x86
BUILD: Loading c:\winddk\7600.16385.0\build.dat...
BUILD: Computing Include file dependencies:
BUILD: Start time: Wed Oct 14 17:34:23 2009
BUILD: Examining c:\exp directory for files to compile.
c:\exp
Invalidating OACR warning log for 'root:x86chk'
BUILD: Saving c:\winddk\7600.16385.0\build.dat...
BUILD: Compiling and Linking c:\exp directory
Configuring OACR for 'root:x86chk' - <OACR on>
_NT_TARGET_VERSION SET TO WINXP
Linking Executable - objchk_win7_x86\i386\exp.exe
1>errors in directory c:\exp
1>link : error LNK1218: warning treated as error; no output file generated
BUILD: Finish time: Wed Oct 14 17:34:44 2009
BUILD: Done
1 executable built - 1 Warning - 1 Error
C:\exp>more *wrn
1>warnings in directory c:\exp
1>c:\exp\libboost_program_options-vc100-mt.lib(options_description.obj): warning LNK4217: locally defined symbol ??1?$basic_streambuf@DU?$char_traits@D@std@@@std@@UAE@XZ (public: virtual __thiscall std::basic_streambuf<char,struct std::char_traits<char> >::~basic_streambuf<char,struct std::char_traits<char> >(void)) imported in function "public: virtual __thiscall std::basic_stringbuf<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_stringbuf<char,struct std::char_traits<char>,class std::allocator<char> >(void)" (??1?$basic_stringbuf@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@UAE@XZ)
| You are explicitly including ..\boost_1_40_0\stage\lib\libboost_program_options-vc100-mt.lib in the link.
You should let the boost auto_link stuff configure do the correct #pragma comment(lib, ...) stuff ensure you bring in the right library and set the linker search path correctly. The most likely thing is that the boost library and your code are linking against different runtime libraries.
|
1,570,737 | 1,570,797 | Why Access Violation for cout and Stack Overflow for printf | I wanted to know why Access Violation occurs for cout and Stack Overflow for printf in the following two code snippets.
I wanted to know why Access Violation for the first code instead of the Stack Overflow.
First code which I get Access Violation :
void Test();
void Test()
{
static int i = 0;
cout << i++ << endl;
Test();
}
int main()
{
Test();
return 0;
}
Second code which I get Stack Overflow :
void Test();
void Test()
{
static int i = 0;
printf("%d\n", i++);
Test();
}
int main()
{
Test();
return 0;
}
| I assume you understand that both functions crash due to exhaustion of the stack after an attempt at infinite recursion. I think what you are asking is: why would the cout example not crash with "Stack Overflow" also?
I do not think the answer has to do with the compiler's detection of tail recursion. If the compiler optimized the recursion away, neither example should crash.
I have a guess as to what is going on. "Stack Overflow" exception is implemented in some cases (e.g., Windows) with a single Virtual Memory "guard page" allocated at the end of the stack. When a stack access hits this guard page a special exception type is generated.
Since the Intel small-granularity page is 4096 bytes long, the guard page stands guard over a range of memory that size. If a function call allocates more than 4096 bytes of local variables, it is possible that the first stack access from it will actually stretch beyond the guard page. The next page can be expected to be unreserved memory, so an access violation would make sense in that case.
Of course you don't explicitly declare any local variables in your example. I would assume that one of the operator<<() methods allocates more than a page of local variables. In other words, that the Access Violation occurs near the beginning of an operator<<() method or some other part of the cout implementation (temporary object constructors, etc.)
Also, even in the function you wrote, the operator<<() implementations are going to need to create some storage for intermediate results. That storage is probably allocated as local storage by the compiler. I doubt it would add up to 4k in your example, though.
The only way to really understand would be to see a stack trace of the access violation to see what instruction is triggering it.
Got a stack trace of the access violation and a disassembly around the area of the faulting opcode?
If you are using the Microsoft C compiler, another possibility is that printf() and your own function were compiled with /Ge and operator<<() was not, or that only your function was compiled with /Ge and factors similar to those described above coincidentally cause the behavior you see -- because in the printf() example the crash happens while your function is being called and in the operator<<() case while you are calling the library.
|
1,570,917 | 1,570,963 | Extracting C / C++ function prototypes | I want to do this:
extract_prototypes file1.c file2.cpp file3.c
and have whatever script/program print a nice list of function prototypes for all functions defined in the given C / C++ files. It must handle multi-line declarations nicely.
Is there a program that can do this job? The simpler the better.
EDIT: after trying to compile two C programs, bonus points for something that uses {perl, python, ruby}.
| The tool cproto does what you want and allows to tune the output to your requirements.
Note: This tool also only works for C files.
|
1,570,922 | 1,572,121 | Winsock2: How to allow ONLY one client connection at a time by using listen's backlog in VC++ | I want to allow only one connection at a time from my TCP server. Can you please tell, how to use listen without backlog length of zero.
I m using the code(given below), but when i launch 2 client one by one, both gets connected. I m using VC++ with winsock2.
listen(m_socket,-1);
passing zero as backlog is also not working.
Waiting for ur reply.
Regards,
immi
| If you can indeed limit your application to only use Winsock 2, you can use its conditional accept mechanism:
SOCKET sd = socket(...);
listen(sd, ...);
DWORD nTrue = 1;
setsockopt(sd, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (char*)&nTrue, sizeof(nTrue));
This changes the stack's behavior to not automatically send SYN-ACK replies to incoming SYN packets as long as connection backlog space is available. Instead, your program gets the signal that it should accept the connection as normal -- select(), WSAEventSelect(), WSAAsyncSelect()... -- then you call WSAAccept() instead of accept():
sockaddr_in sin;
WSAAccept(sd, (sockaddr*)&sin, sizeof(sin), ConditionalAcceptChecker, 0);
You write the function ConditionalAcceptChecker() to look at the incoming connection info and decide whether to accept the connection. In your case, you can just return CF_REJECT as long as you're already processing a connection.
Again, beware that this mechanism is specific to Winsock 2. If you need portable behavior, the other posts' advice to close the listening socket while your program already has a connection is better.
|
1,571,033 | 1,571,080 | Are large include files like iostream efficient? (C++) | Iostream, when all of the files it includes, the files that those include, and so on and so forth, adds up to about 3000 lines.
Consider the hello world program, which needs no more functionality than to print something to the screen:
#include <iostream> //+3000 lines right there.
int main()
{
std::cout << "Hello, World!";
return 0;
}
this should be a very simple piece of code, but iostream adds 3000+ lines to a marginal piece of code. So, are these 3000+ lines of code really needed to simply display a single line to the screen, and if not, do they create a less efficient program than if I simply copied the relevant lines into the code?
| If you worry about the size of <iostream> when all you want is print a line of text, try <cstdio> and std::puts().
(Seriously, why do people use printf() or cout when the much simpler and quicker puts() fits the bill perfectly? It even appends an appropriate line feed automatically...)
In a serious application, the size and compile time of <iostream> won't be significant. (Plus, as others already noted, the linker won't link in what isn't used.)
Edit: I just realized I didn't really answer the question. No, not all the 3000 lines are really required to print the line of code, but you'll find it next to impossible to find "the few lines" required to produce your line of output, as I/O library source tends to be heavily interdependent. And aside from increasing compile times a bit, they don't harm - your code does not get any less efficient as the "fluff" is dropped at linker stage.
|
1,571,115 | 1,571,129 | C++ Abstract class construction and destruction | class base
{
base () { }
virtual ~base () { }
}
class middleBase
{
middleBase () { }
middleBase (int param) { }
~middleBase () { }
}
class concrete : public middleBase
{
concrete () { }
concrete (int param) { // process }
~concrete () { // delete something }
}
Error is : undefinded reference to "middleBase::middleBase (int param)"
and is this suitable for best practice for parameterized constructors?
| class base
{
public: // constructor should be accessible by derived class
base () { }
virtual ~base () { }
}; // add semicolon
class middleBase : public base // you missed the declaration
{
public:
middleBase () { }
middleBase (int param) { }
virtual ~middleBase () { }
};
class concrete : public middleBase
{
public:
concrete () { }
concrete (int param) : middleBase(param) { /* process */ }
virtual ~concrete () { /* delete something */ }
};
|
1,571,215 | 1,571,246 | C++: iterating over a list of a generic type | Yet again I find myself struggling with the C++ syntax.
I'm trying to iterate over a list of generic objects. That is I have objects of a class
Event<Q>, crammed into a std::list<Event<Q> >.
So I'm trying to get an iterator over the list and intuitively thought that
std::list<Event<Q> >::iterator it;
for (it = events.begin(); it != events.end(); it++) { ... }
should solve the problem. However, i keep getting these errors:
..\calendar.h:48: error: expected `;' before "it"
..\calendar.h:49: error: `it' was not declared in this scope
Is there a reason for it being this difficult?
| Sure this should work, but it sounds like you either have one or both of the following in action.
Have Q a template parameter or a type that somehow otherwise depend on it (typedef to it). Put a typename before std::list then, so that the compiler knows that ::iterator is a type and can proceed analysis properly (it could be a static value member). Knowing it is a type, the compiler can produce better diagnostics for template definitions, and you are required to tell whether it is a type using typename.
Have events a const list. Use const_iterator then.
Update: The shown compile error surely indicates that the first point is true: Q directly or indirectly depends on a template parameter, and you have to put typename like so:
typename std::list< Event<Q> >::iterator it;
The compiler believes you that it is a non-type, and so it requires some operator or semicolon behind ::iterator (like, a multiplication). Put typename to make it know it names a type instead.
Update: See the Template FAQ for similar template issues and solutions.
|
1,571,340 | 1,571,360 | What is the "assert" function? | I've been studying OpenCV tutorials and came across the assert function; what does it do?
| assert will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.
For example:
assert(length >= 0); // die if length is negative.
You can also add a more informative message to be displayed if it fails like so:
assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");
Or else like this:
assert(("Length can't possibly be negative! Tell jsmith", length >= 0));
When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assert statements by defining the NDEBUG macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.
// BAD
assert(x++);
// GOOD
assert(x);
x++;
// Watch out! Depends on the function:
assert(foo());
// Here's a safer way:
int ret = foo();
assert(ret);
From the combination of the program calling abort() and not being guaranteed to do anything, asserts should only be used to test things that the developer has assumed rather than, for example, the user entering a number rather than a letter (which should be handled by other means).
|
1,571,731 | 1,571,846 | Is it possible to change the temporary object and to pass it as an argument? | Is it possible to change the temporary object and to pass it as an argument?
struct Foo {
Foo& ref() { return *this; }
Foo& operator--() { /*do something*/; return *this; }
// another members
};
Foo getfoo() { return Foo(); } // return Foo() for example or something else
void func_val(Foo x) {}
void func_ref(const Foo & x) {}
int main() {
func_val(--getfoo()); // #1 OK?
func_ref(getfoo()); // #2 OK?
func_ref(getfoo().ref()); // #3 OK?
// the following line is a real example
// using --vector.end() instead of --getfoo()
func_ref(--getfoo()); // #4 OK?
const Foo & xref = --getfoo(); // Does const extend the lifetime ?
func_ref(xref); // #5 OK?
func_val(xref); // #6 OK?
}
It is known that assigning a temporary object to the const reference extends the lifetime of this temporary object. And what about #4 and #5 lines of my code?
Is it true that reference x is always valid in the function func_ref?
The thing is that operator-- returns some reference and the compiler does not see any relation between this reference and the temporary we created.
| func_val(--getfoo()); // #1 OK?
Yes, OK. The operator-- is a member-function, which is called, and which returns itself (and lvalue referring to itself). The object is then copied into the parameter of func_val. Notice that return value optimization is not allowed to apply, since the temporary created by getfoo() was previously bound to a reference.
func_ref(getfoo()); // #2 OK?
Yes, OK. The call getfoo() returns a temporary which is bound to the const reference. A copy constructor is required, but the call it it may be optimized out by the implementation. The temporary persists until the end of the full-expression containing the call to func_ref (the whole expression statement here).
func_ref(getfoo().ref());
Yes, OK. No copy constructor required, as we bind the const reference not to a temporary but to the lvalue representing the object itself.
// the following line is a real example
// using --vector.end() instead of --getfoo()
That is not required to work. Think of a situation where vector.end() returns a T* (allowed). You are not allowed to modify rvalues of non-class type, so in that case, this would be ill-formed.
func_ref(--getfoo());
Yes, OK. The argument is evaluated as in #1, but the resulting lvalue is directly passed and the const reference is bound to it. In this sense it's equal to #3 (except for the decrement side effect).
const Foo & xref = --getfoo();
The Standard wording is not entirely clear. It surely intends to only extend lifetime of objects not yet bound to a reference. But in our case, --getfoo() yields an lvalue refering to a temporary object which was previously bound to a reference. It may be worth submitting a defect report to the committee (i may also have missed wording that requires the temporary object to not be bounded to a reference yet).
In any case, the intended behavior is to destruct the temporary that results from getfoo() at the end of initializing xref, so xref will become a dangling reference.
The thing is that operator-- returns some reference and the compiler does not see any relation between this reference and the temporary we created.
Exactly (but applies only to the initialization of xref which will go mad. In all other cases, the intended behavior you want (or what i believe you want) is achieved).
|
1,572,016 | 1,572,030 | What's the ampersand for when used after class name like ostream& operator <<(...)? | I know about all about pointers and the ampersand means "address of" but what's it mean in this situation?
Also, when overloading operators, why is it common declare the parameters with const?
| In that case you are returning a reference to an ostream object. Strictly thinking of ampersand as "address of" will not always work for you. Here's some info from C++ FAQ Lite on references.
As far as const goes, const correctness is very important in C++ type safety and something you'll want to do as much as you can. Another page from the FAQ helps in that regard. const helps you from side effect-related changes mucking up your data in situations where you might not expect it.
|
1,572,170 | 1,572,470 | Use CArray class from MFC in C++ Builder application | There is a need to pass CArray instance to an external DLL from my application written in C++ Builder. Is there a way to utilize MFC from C++ Builder? If yes, how?
Addendum: this DLL is not mine and I cannot change it.
| C++ Builder doesn't support MFC because the Microsoft and Borland C++ runtimes are incompatible.
See http://www.parashift.com/c++-faq-lite/compiler-dependencies.html#faq-38.9
|
1,572,290 | 1,572,469 | Fastest way to scan for bit pattern in a stream of bits | I need to scan for a 16 bit word in a bit stream. It is not guaranteed to be aligned on byte or word boundaries.
What is the fastest way of achieving this? There are various brute force methods; using tables and/or shifts but are there any "bit twiddling shortcuts" that can cut down the number of calculations by giving yes/no/maybe contains the flag results for each byte or word as it arrives?
C code, intrinsics, x86 machine code would all be interesting.
| Using simple brute force is sometimes good.
I think precalc all shifted values of the word and put them in 16 ints
so you got an array like this (assuming int is twice as wide as short)
unsigned short pattern = 1234;
unsigned int preShifts[16];
unsigned int masks[16];
int i;
for(i=0; i<16; i++)
{
preShifts[i] = (unsigned int)(pattern<<i); //gets promoted to int
masks[i] = (unsigned int) (0xffff<<i);
}
and then for every unsigned short you get out of the stream, make an int of that short and the previous short and compare that unsigned int to the 16 unsigned int's. If any of them match, you got one.
So basically like this:
int numMatch(unsigned short curWord, unsigned short prevWord)
{
int numHits = 0;
int combinedWords = (prevWord<<16) + curWord;
int i=0;
for(i=0; i<16; i++)
{
if((combinedWords & masks[i]) == preShifsts[i]) numHits++;
}
return numHits;
}
Do note that this could potentially mean multiple hits when the patterns is detected more than once on the same bits:
e.g. 32 bits of 0's and the pattern you want to detect is 16 0's, then it would mean the pattern is detected 16 times!
The time cost of this, assuming it compiles approximately as written, is 16 checks per input word. Per input bit, this does one & and ==, and branch or other conditional increment. And also a table lookup for the mask for every bit.
The table lookup is unnecessary; by instead right-shifting combined we get significantly more efficient asm, as shown in another answer which also shows how to vectorize this with SIMD on x86.
|
1,572,365 | 1,572,543 | what is the most unobtrusive way of using precompiled headers in Visual C++? | Say I have a single project, with files A.cpp, B.cpp, C.ppp and matching header files (and that's it). The C++ files include system headers or headers from other modules.
I want to compile them to a library with command line actions (e.g., using Make), using 'cl', with the precompiled headers feature.
What are the steps I should do? What are the command line switches?
| Precompiled Headers are done by creating a .cpp that includes the headers you want to be pre-compiled. Normally, stdafx.cpp is used for this purpose.
Create a .cpp that includes the headers you want to be precompiled -- normally this file would be called stdafx.cpp
Add the .cpp to your project
Compile that file with /Yc before any other .cpp files /Fp sets the name of the .pch file with the pre-compiled information
Compile all other files with /Yu and /Fp with the name of the .pch from #3
There are other ways, but I find this to be the simplest.
|
1,572,420 | 1,572,460 | Creating a new primitive type | Is there a way to create a new type that is like one of the basic types (eg char), and can be implcitly converted between, but will resolve diffrently in templates, such that for example, the following code works?
typedef char utf8;
template<typename T>void f(T c);
template<> void f<char>(char c)
{
std::cout << "ascii " << c << std::endl;
}
template<> void f<utf8>(utf8 c)//error C2766: explicit specialization; 'void f<char>(char)' has already been defined
{
std::cout << "utf8 " << c << std::endl;
}
int main()
{
char c1 = 'x';
utf8 c2 = 'g';
f(c1);
f(c2);
}
I'm thinking that it may be possible with a class containing a single data member, if so what is the cleanest way to do it, and will compilers be able to optimise it as if it was a primitive.
EDIT: I tried BOOST_STRONG_TYPEDEF, and that seems to work for basic things, but how can I then go onto create a std::basic_string from the new type?
BOOST_STRONG_TYPEDEF(char,utf8);
//first try
BOOST_STRONG_TYPEDEF(std::string,utf8_string);
//second try
typedef std::basic_string<utf8, std::char_traits<utf8>,std::allocator<utf8> > uft8_string;
The first one doesn't really work because the resulting type still expects char for all its methods, and the second one doesn't seem to like the presence of constructors and assignment operators :(
I haven't tried the other way to create the new char type yet, will it be able to get around this if I cant with BOOST_STRONG_TYPEDEF?
| I heard a rumour that C++0x will bring strong typedefs which will allow for the utf8 class in your case to be distinguishable from the char, but that doesn't exist currently. Maybe Boost's strong typedef would help, but I don't know.
|
1,572,427 | 2,184,204 | Problem with Berkeley DB and C++ | I'm trying to write a simple C++ program that uses Berkeley DB for storage. The key of the database is of type time_t and the data is an integer.
I need to take the difference between two adjacent data in a between two key. I open a cursor with the flag DB_SET_RANGE and then i use DB_NEXT to iterate.
My problem is that the cursor returns unsorted data. Is there a way to specify a custom sorter function for the cursor?
| Some of the reasons why you may want to provide a custom sorting function are:
You are using a little-endian system (such as x86) and you are using integers as your database's keys. Berkeley DB stores keys as byte strings and little-endian integers do not sort well when viewed as byte strings. There are several solutions to this problem, one being to provide a custom comparison function. See http://www.oracle.com/technology/documentation/berkeley-db/db/ref/am_misc/faq.html for more information.
You set a BTree's key comparison function using DB->set_bt_compare().
For example, an example routine that is used to sort integer keys in the database is:
int
compare_int(DB *dbp, const DBT *a, const DBT *b)
{
int ai, bi;
/*
* Returns:
* < 0 if a < b
* = 0 if a = b
* > 0 if a > b
*/
memcpy(&ai, a->data, sizeof(int));
memcpy(&bi, b->data, sizeof(int));
return (ai - bi);
}
|
1,572,586 | 1,572,918 | C++: how to deal with const object that needs to be modified? | I have a place in the code that used to say
const myType & myVar = someMethod();
The problem is that:
someMethod() returns const myType
I need to be able to change myVar later on, by assigning a default value if the object is in an invalid state. So I need to make myVar to be non-const.
I assume I need to make myVar be non-reference as well, right? E.g. myType myVar?
What is the C++ "correct" way of doing this const-to-nonconst? Static cast? Lexical cast? Something else?
I may have access to boost's lexical cast, so I don't mind that option, but I'd prefer the non-boost solution as well if it ends up i'm not allowed to use boost.
Thanks!
| I wouldn't use the const_cast solutions, and copying the object might not work. Instead, why not conditionally assign to another const reference? If myVar is valid, assign that. If not, assign the default. Then the code below can use this new const reference. One way to do this is to use the conditional expression:
const myType& myOtherVar = (myVar.isValid() ? myVar : defaultVar);
Another way is to write a function that takes a const reference (myVar) and returns either myVar or defaultVar, depending on the validity of myVar, and assign the return value from that to myOtherVar.
A third way is to use a const pointer, pointing it at either the address of myVar or the address of the default object.
|
1,572,705 | 1,572,921 | How to convert long to LPCWSTR? | how can I convert long to LPCWSTR in C++? I need function similar to this one:
LPCWSTR ToString(long num) {
wchar_t snum;
swprintf_s( &snum, 8, L"%l", num);
std::wstring wnum = snum;
return wnum.c_str();
}
| Your function is named "to string", and it's indeed easier (and more universal) to convert to a string than to convert "to LPCWSTR":
template< typename OStreamable >
std::wstring to_string(const OStreamable& obj)
{
std::wostringstream woss;
woss << obj;
if(!woss) throw "dammit!";
return woss.str();
}
If you have an API that needs a LPCWSTR, you can use std::wstring::c_str():
void c_api_func(LPCWSTR);
void f(long l)
{
const std::wstring& str = to_string(l);
c_api_func(str.c_str());
// or
c_api_func(to_string(l).c_str());
}
|
1,572,751 | 1,572,819 | How do I find out where an object was instanciated using gdb? | I'm debugging an application and it segfaults at a position where it is almost impossible to determine which of the many instances causes the segfault.
I figured that if I'm able to resolve the position at which the object is created, I will know which instance is causing the problem and resolve the bug.
To be able to retrieve this information, gdb (or some other application) would of course have to override the default malloc/new/new[] implementations, but instrumenting my application with this would be alright.
One could argue that I could just put a breakpoint on the line before the one that segfaults and step into the object from there, but the problem is that this is a central message dispatcher loop which handles a lot of different messages and I'm not able to set a breakpoint condition in such a way as to trap my misbehaving object.
| Have you tried using a memory debugging library (e.g. dmalloc). Many of these already instrument new, etc. and records where an allocation is made. Some are easier to access from gdb than others though.
This product has a memory debugging feature that does what you want: http://www.allinea.com/index.php?page=48
|
1,572,909 | 1,572,946 | Is reinterpreting a member function pointer a 'good idea'? | I have a worker thread, which holds a list of 'Thread Actions', and works through them as an when.
template <class T> class ThreadAction
{
public:
typedef void (T::*action)();
ThreadAction(T* t, action f) :
func(f),obj(t) {}
void operator()() { (obj->*func)(); }
void (T::*func)();
T* obj;
};
It's normally called like this
myActionThread->addAction(
new ThreadAction<TheirClass>(this, &TheirClass::enable)
);
Which worked fine until
void TheirClass::enable()
was changed to
bool TheirClass::enable()
Sadly we can't change it back again because other stuff needs the new format, (and overloads can't differ by return type alone).
I did try
myActionThread->addAction(
new ThreadAction<TheirClass>(this,
reinterpret_cast<void(TheirClass::*)>(&TheirClass::enable)
)
);
Which appears to work just fine, but I'm not certain that reinterpreting a function pointer like this is 'defined' behaviour, can somebody please advise?
| This is definitely not supported behavior, and can potentially cause your program to crash.
Basically, you need to make a wrapper for TheirClass::enable() that will have the proper return type. A simple one-liner will suffice:
public:
void enableWrapper() { enable(); };
Then call:
myActionThread->addAction(
new ThreadAction<TheirClass>(this, &TheirClass::enableWrapper)
);
If you can't modify TheirClass directly, then create a simple subclass or helper class that implements the wrapper.
|
1,573,168 | 1,573,190 | Error: expected constructor, destructor, or type conversion before ';' token? | I'm trying to compile my code to test a function to read and print a data file, but I get a compiling error that I don't understand - "error: expected constructor, destructor, or type conversion before ';' token". Wall of relevant code-text is below.
struct Day
{
int DayNum;
int TempMax;
int TempMin;
double Precip;
int TempRange;
};
struct Month
{
Day Days[31];
int MonthMaxTemp;
int MonthMinTemp;
double TotalPrecip;
int MonthMaxTempRange;
int MonthMinTempRange;
double AverageMaxTemp;
double AverageMinTemp;
int RainyDays;
double AveragePrecip;
}theMonth;
double GetMonth();
double GetMonth()
{
for (int Today = 1; Today < 31; Today++)
{
cout << theMonth.Days[Today].TempMax << theMonth.Days[Today].TempMin;
cout << theMonth.Days[Today].Precip;
}
return 0;
}
GetMonth(); // compile error reported here
| The line with the error looks like you're trying to call GetMonth -- but at the global level, a C++ program consists of a series of declarations. Since a function call isn't a declaration, it can't exist in isolation at the global level. You can have a declaration that's also a definition, in which case it can invoke a function as part of initialization.
A function call by itself, however, has to be contained within some other function:
#ifdef TEST
int main() {
GetMonth();
}
#endif
|
1,573,203 | 1,573,258 | C++ matrix transposion. Boost uBLAS and double*? | I need to do a in-place transposition of a large matrix(so the simplest way to allocate another matrix and transpose to it won't work). Unfortunately, this large matrix isn't square. And worse, the matrix is stored in an array of doubles with number of columns and rows stored separately.
I found that boost has the uBLAS library, but I didn't find a way to wrap my array of doubles in uBLAS matrix. Is there a way to do this?
Or do you recommend another ways to do the job?
| If you have very big matrices and you dont want to store the temporary copies one solution would be to wrap your matrix array into the class and provide different adapters which will iterate through the elements in normal or transposed way. This is not very cache efficient but saves memory on large matrices.
|
1,573,225 | 1,573,271 | Why do I have __stdcall? | I am starting doing some directX programming. I am using this tutorial that I have found from the Internet.
I am just wondering why the CALLBACK has been defined as _stdcall and why WINAPI is as well.
I thought __stdcall was used when exporting functions that will be compiled as a dll.
However, as WindowProc and WINAPI will never been exported why are these functions declared as __stdcall?
Many thanks for any suggestions,
// WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
}
| __stdcall refers to the calling convention, and doesn't necessarily have to do with exporting functions. Take a look at Wikipedia's article on calling conventions if you want to know more. In brief, the compiler needs to know where to pass the parameters to your function, on the stack or in registers etc.
|
1,573,732 | 1,573,773 | Using dlopen, how can I cope with changes to the library file I have loaded? | I have a program written in C++ which uses dlopen to load a dynamic library (Linux, i386, .so). When the library file is subsequently modified, my program tends to crash. This is understandable, since presumably the file is simply mapped into memory.
My question is: other than simply creating myself a copy of the file and dlopening that, is there way for me to load a shared object which is safe against subsequent modifications, or any way to recover from modifications to a shared object that I have loaded?
Clarification: The question is not "how can I install a new library without crashing the program", it is "if someone who I don't control is copying libraries around, is it possible for me to defend against that?"
| If you rm the library prior to installing the new one, I think your system will keep the inode allocated, the file open, and your program running. (And when your program finally exits, then the mostly-hidden-but-still-there file resources are released.)
Update: Ok, post-clarification. The dynamic linker actually completely "solves" this problem by passing the MAP_COPY flag, if available, to mmap(2). However, MAP_COPY does not exist on Linux and is not a planned future feature. Second best is MAP_DENYWRITE, which I believe the loader does use, and which is in the Linux API, and which Linux used to do. It errors-out writes while a region is mapped. It should still allow an rm and replace. The problem here is that anyone with read-access to a file can map it and block writes, which opens a local DoS hole. (Consider /etc/utmp. There is a proposal to use the execute permission bit to fix this.)
You aren't going to like this, but there is a trivial kernel patch that will restore MAP_DENYWRITE functionality. Linux still has the feature, it just clears the bit in the case of mmap(2). You have to patch it in code that is duplicated per-architecture, for ia32 I believe the file is arch/x86/ia32/sys_ia32.c.
asmlinkage long sys32_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
{
struct mm_struct *mm = current->mm;
unsigned long error;
struct file *file = NULL;
flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE); // fix this line to not clear MAP_DENYWRITE
This should be OK as long as you don't have any malicious local users with credentials. It's not a remote DoS, just a local one.
|
1,573,806 | 1,573,868 | When are member data constructors called? | I have a global member data object, defined in a header (for class MyMainObj) like this.
class MyMainObj
{
MyDataObj obj;
}
MyDataObj has a default constructor.
When is the constructor for MyDataObj called?
Is it called as part of the creation of MyMainObj?
| MyDataObj in this case is not a member of MyMainObj, it's a local variable.
But, constructors for data members are called in your class's constructor. The default constructor for every member is called before execution reaches the first line in the constructor, unless you explicitly specify a constructor using an initializer list, in which case that constructor is called instead.
|
1,574,121 | 1,574,199 | Precompiled headers with DLL solutions. Cannot open precompiled header file | This worked without error when this solution worked off of .lib files instead of .dll files.
I have all of my projects except one currently using a precompiled header, without error. The precompiled header is called "LudoGlobal.h". I am trying to link the last project to this precompiled header (which exists in a seperate, "Core", project) but I'm getting the following error:
Error 4 fatal error C1083: Cannot open
precompiled header file:
'....\Output\LudoSound\Debug\LudoSound.pch':
No such file or
directory ludosoundmanager.cpp 1
for each .cpp file. Why is this? How can I solve it?
I realize LudoSound.pch does not exist. I am under the assumption that it probably gets created when LudoSound compiles, yesno?
| Are you using "automatically generate", or "use precompiled header" on the project and "create precompiled header" on the one cpp file? The latter is more efficient, but I've seen the per-file configuration on projects get accidentally reset, so that the "stdafx.cpp" (or whatever) file no longer generates the precompiled header.
|
1,574,286 | 1,574,299 | Vector assignment problem | #include "iostream"
#include "vector"
using namespace std;
const vector<int>& Getv()
{
vector<int> w(10);
w[0]=10;
cout<<w.size()<<endl;
return w;
}
//Now when I write in main:
vector<int>v = Getv();//Throws exception
//and the below rows has no effect
vector<int>v;
v=Getv()//w does not change
please what is the problem?
Hani Almousli...
| You're returning a reference to a local variable. When you exit the function it gets destructed.
You need to return a copy:
vector<int> Getv()
{
vector<int> w(10);
w[0]=10;
cout<<w.size()<<endl;
return w;
}
Or you could make w static:
const vector<int>& Getv()
{
static vector<int> w(10);
w[0]=10;
cout<<w.size()<<endl;
return w;
}
Also you should use <> on your includes since they're part of the standard library.
|
1,574,367 | 1,574,433 | LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification | I recently converted a multi-project Visual Studio solution to use .dlls instead of .libs for each of the projects. However, I now get a linker warning for each project as stated in the example. MSDN didn't serve to be all that helpful with this. Why is this and how can I solve it?
Warning 2 warning LNK4075: ignoring
'/EDITANDCONTINUE' due to '/OPT:ICF'
specification LudoCamera.obj
| You can either have "Edit and continue" support or optimizations. Usually, you put "Edit and continue" on debug builds, and optimizations on release builds.
Edit and continue allows you to change code while you are debugging and just keep the program running. It's not supported if the code also has to be optimized.
|
1,574,512 | 1,574,568 | Constructor injection | I know the code is missing (Someone will give negative numbers). But I only want to know how do you solve constructor injection in this situation?
class PresenterFactory
{
public:
template<class TModel>
AbstractPresenter<TModel>*
GetFor(AbstractView<TModel> * view)
{
return new PresenterA(view, new FakeNavigator());
}
};
class ViewA : public AbstractView<ModelA>
{
static PresenterFactory factory;
public:
ViewA(AbstractPresenter<ModelA> *presenter = factory.GetFor<ModelA>(this)) :
AbstractView<ModelA> (presenter)
{
}
// this one is also not working
// invalid use of ‘class ViewA’
// ViewA()
// {
// this->ViewA(factory.GetFor<ModelA> (this));
// }
};
| Why not to use two constructors?
// constructor with one argument
ViewA(AbstractPresenter<ModelA> *presenter) : AbstractView<ModelA> (presenter)
{
}
// constructor without arguments
ViewA() : AbstractView<ModelA>(factory.GetFor<ModelA>(this))
{
}
By the way, this pointer is valid only within nonstatic member functions. It should not be used in the initializer list for a base class. The base-class constructors and class member constructors are called before this constructor. In effect, you've passed a pointer to an unconstructed object to another constructor. If those other constructors access any members or call member functions on this, the result will be undefined. You should not use the this pointer until all construction has completed.
|
1,574,517 | 1,574,956 | Calling methods in a win32 service with elevated privileges from an application | I have developed a Win32 C/C++ application that creates dynamic WFP IP filters, however it must be run as admin to do so (due to the Windows security policy). I want to place the code that requires admin privileges in a service running with admin privileges and then call it from the application running as a normal user.
First is this the correct approach? And second, although I know how to create a service I cannot find any reference illustrating how to call methods in/send requests to a service.
Although I can probably cheat and play with the manifest, I don't mind extra work to do it correctly especially as the functionality will be reusable across applications.
Does anybody have any experience or pointers?
| It is certainly the right approach to have a separate executable that has the privilege to perform the action you require, so that the main application can run in a restricted user account. As for sending requests to the service, there is nothing special about the fact it is running as a service. Just consider it to be a process that runs with the credentials of an admin user. So communicate with it in the same way you would in any other process-to-process situation, eg named pipes, network sockets, etc.
|
1,574,522 | 1,574,759 | Is there a way to get better information for the context of an error when using msvc? (ex: C2248) | I'm wondering if there is a way to get better information about the location of an error in msvc (2005)?
For example, when inheriting from boost::noncopyable in my class I get a C2248 error saying something like:
error C2248: 'boost::noncopyable_::noncopyable::noncopyable' : cannot access private member declared in class 'boost::noncopyable_::noncopyable'.
This diagnostic occurred in the compiler generated function 'MyClass::MyClass(const MyClass &)'
but it fail to tell me where exactly the copy constructor was called. This is a little annoying. I'm really not sure but I think I remember seeing a settings somewhere where I could specify the output level or something but I searched and found nothing so my question is: Is there a way to get better (fuller?) error message in msvc?
Edit: Well since stackoverflow just told me I should look to accept an answer, I was wondering if anyone could tell if msvc 2008/2010 give a better diagnostic for this error? Someone also mentioned GCC should do, can anyone confirm this? What about other compilers (Intel?, Comeau?)
Thanks
| I can confirm with Code::Blocks and VC++ 2005, that it gives no hint where the error occurs. Neither does declaring your own private copy constructor help.
#include <boost/noncopyable.hpp>
class X: boost::noncopyable
{
};
void foo(X x) {}
int main()
{
X x;
foo(x);
}
The compile log (line five is the last line of the class declaration):
main.cpp(5) : error C2248: 'boost::noncopyable_::noncopyable::noncopyable' : cannot access private member declared in class 'boost::noncopyable_::noncopyable'
C:\boost_1_38_0\boost/noncopyable.hpp(27) : see declaration of 'boost::noncopyable_::noncopyable::noncopyable'
C:\boost_1_38_0\boost/noncopyable.hpp(22) : see declaration of 'boost::noncopyable_::noncopyable'
This diagnostic occurred in the compiler generated function 'X::X(const X &)'
Unless there's a compiler switch to enable more thorough error diagnostics, this wouldn't be the first time for me to simply compile the file with GCC (MinGW) to get more helpful error diagnostics. (Alas, your code should be free of VC++ extensions.)
|
1,574,647 | 1,574,903 | A way to turn boost::posix_time::ptime into an __int64 | Does anyone know if there is a good way to turn a boost::posix_time::ptime into an __int64 value. (I have compiled the microsecond version, not the nanosecond version).
I need to do this somehow as I am looking to store the resulting __int64 in a union type which uses the raw data for a high-performance application. Some type of Memento functionality like this would be highly useful for me. I'd like to avoid casts, if possible, but will resort to them if I need to.
| Converting a ptime to an integer is rather meaningless, since ptime is an abstraction of the actual time. An integer based time is a representation of that time as a count from an epoch. What you (probably) want to do is generate a time_duration from your time to the epoch you are interested in, then use the time_duration::ticks() to get the 64-bit integer. You may have to scale your result to your desired precision:
ptime myEpoch(date(1970,Jan,1)); // Or whatever your epocj is.
time_duration myTimeFromEpoch = myTime - myEpoch;
boost::int64_t myTimeAsInt = myTimeFromEpoch.ticks();
|
1,574,721 | 1,574,784 | g++ doesn't like template method chaining on template var? | I'm trying to compile with g++ some code previously developed under Visual C++ 2008 Express Edition, and it looks like g++ won't let me call a template method on a reference returned by a method of a template variable. I was able to narrow the problem down to the following code:
class Inner
{
public:
template<typename T>
T get() const
{
return static_cast<T>(value_);
};
private:
int value_;
};
class Outer
{
public:
Inner const& get_inner() { return inner_; };
private:
Inner inner_;
};
template<typename T>
int do_outer(T& val)
{
return val.get_inner().get<int>();
}
int main()
{
Outer outer;
do_outer(outer);
return 0;
}
The code compiles fine under Microsoft's compiler, but g++ throws an error:
$ g++ -c main.cpp
main.cpp: In function ‘int do_outer(T&)’:
main.cpp:24: error: expected primary-expression before ‘int’
main.cpp:24: error: expected ‘;’ before ‘int’
main.cpp:24: error: expected unqualified-id before ‘>’ token
where line 24 refers to return val.get_inner().get<int>();.
If I make do_outer a normal method receiving an Outer reference the code compiles. Making Inner::get() a normal method also works. And making Inner::get() return void and receive a template parameter also works because the int specifier below becomes needless, i.e.:
class Inner
{
public:
template<typename T>
void get(T& val) const
{
val = static_cast<T>(value_);
};
private:
int value_;
};
...
template<typename T>
int do_outer(T& val)
{
int i;
val.get_inner().get(i);
return i;
}
...
(g++ doesn't complaing about the code above.)
Now I'm out of ideas. What's the problem? Is there a problem with gcc/g++? Is there a compliance issue with my code?
The compiler I'm using is:
$ g++ --version
g++ (Ubuntu 4.3.3-5ubuntu4) 4.3.3
| could you try with?
template<typename T>
int do_outer(T& val)
{
return val.get_inner().template get<int>();
}
I don't have access to gcc atm, but I've had similar issues and adding the template keyword always solved them. And it works in VS too.
|
1,574,773 | 1,574,974 | Is it possible to hijack standard out | I am trying to redirect the stdout of an already running process on Windows XP using C#. I am aware that I can do this if I spawn the process myself, but for this application I would prefer a "listener" i could just attach to another process.
Is this possible in pure .Net and if not is it even possible with Win32?
Thanks
UPDATE: There are multiple processes I am trying to monitor that are all started by a "gate keeper" process that will restart these processes if they crash. This makes it difficult for me to do any redirecting up front.
| It would be fairly easy to do this in Win32 using the Detours Library. You'd look at all calls to WriteFile, and check whether they were going to standard output. You might also want to look at the console output functions (e.g. WriteConsoleOutput) but they're used rarely enough that you probably don't need to bother for use with most programs.
Offhand I don't remember whether detours directly supports use from .NET languages or not. If it doesn't, I suppose you could still use it via P/Invoke, but I don't think it would be pretty at all...
Edit: There are various similar (free) libraries around. For one example, Jeffrey Richter's book Advanced Windows used to include one that should work for this purpose. A quick look indicates that his current Windows via C/C++ still includes a section on "DLL injection and API hooking." That probably includes (and updated version of) the same code, which should be adequate for this kind of job.
|
1,574,910 | 1,574,927 | C++ map object not growing when members added | Below the map 'widgets' is always size of 1 for some reason. There should be 4 when it's done.
Output:
Widget: widget_ram_label:layout_bar:0 1
Widget: widget_ram_active:layout_bar:0 1
Widget: widget_ram_total:layout_bar:0 1
Widget: widget_wlan0_label:layout_bar:0 1
Here's widgets:
std::map<const char *, Widget *> widgets;
And here's the code:
void Generic::BuildLayouts() {
for(std::map<const char*, std::vector<widget_template> >::iterator l =
widget_templates.begin(); l != widget_templates.end(); l++) {
std::vector<widget_template> layout = l->second;
for(unsigned int i = 0; i < layout.size(); i++ ) {
Json::Value *widget_v = CFG_Fetch_Raw(root, layout[i].key);
if(!widget_v) {
error("No widget named <%s>", layout[i].key);
continue;
}
Json::Value *type = CFG_Fetch_Raw(widget_v, "type");
if(!type) {
error("Widget <%s> has no type!", layout[i].key);
delete widget_v;
continue;
}
Widget *widget;
char name[256];
sprintf(name, "%s:%s", layout[i].key, l->first);
char tmp[256];
int i = 0;
sprintf(tmp, "%s:%d", name, i);
while(widgets.find(tmp) != widgets.end()) {
i++;
sprintf(tmp, "%s:%d", name, i);
}
memcpy(name, tmp, 256);
if(strcmp(type->asCString(), "text") == 0) {
widget = (Widget *) new WidgetText(this, name, widget_v,
layout[i].row, layout[i].col);
std::cout << "Widget: " << name << " " << widgets.size() << std::endl;
} else {
error("Unknown widget type: %s", type->asCString());
}
if(widget) {
widgets[name] = widget;
}
delete type;
}
}
}
| Maybe because all your name pointers poitns to the same buffer? Because the content of name changes, but not the value of the pointer to name in the map.
Try to use std::string instead.
Replace you name buffer by
#include <string >
//...
std::string name = "the name";
and replace your map by
std::map< const std::string , Widget* > widgets;
That will make your life easier, safer and more readable.
To help formatting, use std::stringstream or boost string algorithms.
A start of example, this code :
char name[256];
sprintf(name, "%s:%s", layout[i].key, l->first);
char tmp[256];
int i = 0;
sprintf(tmp, "%s:%d", name, i);
while(widgets.find(tmp) != widgets.end()) {
i++;
sprintf(tmp, "%s:%d", name, i);
}
memcpy(name, tmp, 256);
would be written like this:
Widget *widget = NULL; // always initialize your variables!!!
std::stringstream name_stream; // this will let us format our string
name_stream << layout[i].key << ":" << l->first;
std::string name = name_stream.str(); // now we got the string formated.
std::stringstream tmp_stream; // same for tmp
tmp_stream << name << ":" << i; // will automatically convert basic types, see the doc if you want specific formatting
std::string tmp = tmp_stream.str(); // now we got the string formated.
// the while loop have no sense : a map have only one value by key
// if you want to have several values by key, use std::multi_map instead -- it don't work exactly the same though
// for now i'll just assume you just need to find the value associated to the name:
typedef std::map< const std::string, Widget* > WidgetMap; // for ease of writing, make a shortcut! ease your life!
WidgetMap::iterator tmp_it = widgets.find( tmp );
if( tmp_it != widgets.end() )
{
// starting here I don't understand you code, so I'll let you find the rest :)
}
|
1,575,003 | 1,575,522 | Direct3D Texture Post-Processing/Copying | So I'm trying to implement some Direct3D post-processing, and I'm having issues rendering to textures. Basically, my program looks like this:
// Render scene to "scene_texture" (an HDR texture)...
...
device->SetRenderTarget(0, brightpass_surface);
device->SetTexture(0, scene_texture);
// Render "scene_texture" to "brightpass_texture" using full-screen quad.
// This involves passing the quad geometry through a brightpass shader.
...
device->SetRenderTarget(0, ldr_surface);
device->SetTexture(0, brightpass_texture);
// Render "brightpass_texture" to "ldr_surface" using full-screen quad...
I've left out some parts b/c there is a fair amount of code (I'm just trying to get across the general idea). Unfortunately, the above results in a blank screen. Here is what I want to happen:
Render scene to a texture (HDR)
Render that texture to a second texture THROUGH a brightpass shader
Render the second texture to the visible LDR surface
Note that if I change the last line above from
device->SetTexture(0, brightpass_texture);
to
device->SetTexture(0, scene_texture);
Then everything works. Note that I've tried skipping the brightpass shader and simply passing the pixels through, but that doesn't work either.
| The problem was multisampling. In the D3DPRESENT_PARAMS structure, I had enabled multisampling. You can't render from one floating point texture into another floating point texture using the "full-screen quad" technique while multisampling is enabled.
Instead, I enabled multisampling in the HDR scene render target (scene_texture) and disabled it in the PRESENT_PARAMS structure. This is good because I only needed multisampling for the scene rendering.
|
1,575,240 | 1,575,257 | Using a std::set in a class? | I am trying to combine using a std::set and a class, like this:
#include <set>
class cmdline
{
public:
cmdline();
~cmdline();
private:
set<int> flags; // this is line 14
};
but, it doesn't like the set flags; part:
cmdline.hpp:14: error: ISO C++ forbids declaration of 'set' with no type
cmdline.hpp:14: error: expected ';' before '<' token
make: *** [cmdline.o] Error 1
As far as I can see, I gave a type (of int). Do you write the "set variable" line differently, or is it not allowed there?
| You need to use std::set; set is in the std namespace.
|
1,575,323 | 1,575,344 | How to deal with seniors' bad coding style/practices? | I am new to work but the company I work in hires a lot of non-comp-science people who are smart enough to get the work done (complex) but lack the style and practices that should help other people read their code.
For example they adopt C++ but still use C-like 3 page functions which drives new folks nuts when they try to read that. Also we feel very risky changing it as it's never easy to be sure we are not breaking something.
Now, I am involved in the project with these guys and I can't change the entire code base myself or design so that code looks good, what can I do in this situation?
PS> we actually have 3 page functions & because we do not have a concept of design, all we can do is assume what they might have thought as there is no way to know why is it designed the way it is.
I am not complaining.I am asking for suggestion,already reading some books to solve the issues Pragmatic Programmer; Design portion from B.Stroustrup; Programming and principles by B.Stroustrup;
| The best and most important thing you can do is lead by example. Do things the right way and try to improve things slowly. You aren't going to fix anything overnight.
Make sure every piece of code that you are responsible for is better after you are done with it. Over time, the system will tangibly be better because of your efforts.
After you build a strong reputation with your co-workers, try go start some code reviews or lunch-training sessions to get everyone up to speed on better ways to do things.
In a nutshell: it will be difficult and frustrating, but it's possible. Good luck.
|
1,575,460 | 1,575,754 | Is there a cross-platform exec in Boost? | I want to execute a sub-process in C++. I need it to work on Windows and Linux.
Is there such a function in Boost?
What is the standard way of doing it?
| Poco and ACE have Process classes that do what you want. See Foundation->Processes->Process in Poco; Process.h/Process.cpp for Ace. I wouldn't be surprised if QT has something similar.
As for how to do it, basically you wrap the OS dependencies and bury the details. Poco and Ace offer contrasting common methods. Poco tends to handle things by writing implementation objects (xxx_impl) for each platform with the proper one getting pulled in depending on the OS. ACE seems to #ifdef the code, sometimes to the point of madness, though in fairness it has been a long time since I looked at that code.
|
1,575,698 | 1,575,709 | std::string and format string | I found the below code through Google. It almost does what I want it to do, except it doesn't provide a way to indicate the precision like '%.*f' does in C-type format strings. Also, it doesn't provide anything further than 5 decimal places. Am I going to have to stick with C strings and snprintf?
#include <string>
#include <sstream>
#include <iostream>
template <class T>
std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
{
std::ostringstream oss;
oss << f << t;
return oss.str();
}
int main()
{
std::cout<<to_string<double>(3.1415926535897931, std::dec)<<std::endl;
return 0;
}
| You want to use the std::setprecision manipulator:
int main()
{
std::cout << std::setprecision(9) << to_string<long>(3.1415926535897931, std::dec)
<< '\n';
return 0;
}
|
1,575,749 | 1,575,960 | C++ Abstract base class array of ptrs to ptrs | I have an abstract base class (Comparable) with Date and Time virtually inheriting from it and a DateTime class v-inheriting from Date and Time.
My problem is this:
I was tasked with dynamically allocating an array of Comparables.
Comparable ** compArray;
compArray = new Comparable *[n]; // where n is user specified number of elements
I then populate the array with DateTimes in alternating order.
I need to sort this array using a quicksort and bubblesort combination. Bubble if length < 8. Comparable** from and Comparable ** to are the only parameters I'm allowed to use.
But I'm completely stuck. At this point it isn't worth pasting in the code I have due to it's frantic haphazardness.
Any help would be greatly appreciated. I've spent the past few hours trying to finish this up, only have sorting left in my project. Which is due tomorrow late morning.
Thanks in advance,
Joel
EDIT:
void Sort(Comparable** a);
void quicksort(Comparable** from, Comparable** to);
Comparable** partition(Comparable** from, Comparable** to);
void Swap(Comparable** from, Comparable** to);
void safeRead(istream& sin, Comparable* d, const char* prompt);
void printArray(ostream & sout, Comparable **a, int size);
I was given the above to use as my arraySort.h
I'm using: int aSize = _msize(a) / sizeof(Comparable) - 1; as my length variable... which I have to calculate instead of passing it, which is kind of annoying.
I'm mainly just having headaches over dereferencing the ** and calling it's lessThan or equals method in quicksort. Once I understand how to do a quicksort with it'll 'click' and I'll be able to easily to bubble sort.
EDIT:
I currently have the following as my bubble sort, it doesn't sort the array at all.
void Swap(Comparable** from, Comparable** to)
{
Comparable** tmp;
tmp = from;
**from = **to;
to = tmp;
}
void bubbleSort(Comparable** a, int size)
{
int i, j;
for (i=0; i<size-1; i++)
{
for (j= size - 1; j > i; j--)
if(a[j]->lessThan(*a[j-1]))
Swap(&a[j], &a[j-1]);
}
}
| You have to have alternating Dates and Times so you don't need to create the DateTime object, do you?
Remember you are sorting an inplace array. From and to are like the begin() and end() parts of the STL containers.
void QuickSort(Comparable** from, Comparable** to)
{
int n = to - from;
if (n < 8) BubbleSort(from, to);
else {
// the trick in here is remembering you have to sort in pairs
}
}
Comparable** array = new Comparable*[n];
for (int i = 0; i < n; i += 2) {
array[i] = new Date();
array[i+1] = new Time();
}
// sort it
QuickSort(array, array+n);
|
1,575,802 | 1,597,811 | Python callback with SWIG wrapped type | I'm trying to add a python callback to a C++ library as illustrated:
template<typename T> void doCallback(shared_ptr<T> data) {
PyObject* pyfunc; //I have this already
PyObject* args = Py_BuildValue("(O)", data);
PyEval_CallObject(pyfunc,args);
}
This fails because data hasn't gone through swig, and isn't a PyObject.
I tried using:
swigData = SWIG_NewPointerObj((void*)data, NULL, 0);
But because its a template, I don't really know what to use for the second parameter. Even if I do hard code the 'correct' SWIGTYPE, it usually segfaults on PyEval_CallObject.
So my questions are:
Whats the best way to invoke swig
type wrapping?
Am I even going in the right
direction here? Directors looked
promising for implementing a
callback, but I couldn't find an
example of directors with python.
Update: The proper wrapping is getting generated. I have other functions that return shared_ptrs and can call those correctly.
| My first answer misunderstood the question completely, so let's try this again.
Your central problem is the free type parameter T in the definition of doCallback. As you point out in your question, there's no way to make a SWIG object out of a shared_ptr<T> without a concrete value for T: shared_ptr<T> isn't really a type.
Thus I think that you have to specialize: for each concrete instantiation of doCallback that the host system uses, provide a template specialization for the target type. With that done, you can generate a Python-friendly wrapping of data, and pass it to your python function. The simplest technique for that is probably:
swigData = SWIG_NewPointerObj((void*)(data.get()), SWIGType_Whatever, 0);
...though this can only work if your Python function doesn't save its argument anywhere, as the shared_ptr itself is not copied.
If you do need to retain a reference to data, you'll need to use whatever mechanism SWIG usually uses to wrap shared_ptr. If there's no special-case smart-pointer magic going on, it's probably something like:
pythonData = new shared_ptr<Whatever>(data);
swigData = SWIG_NewPointerObj(pythonData, SWIGType_shared_ptr_to_Whatever, 1);
Regardless, you then you have a Python-friendly SWIG object that's amenable to Py_BuildValue().
Hope this helps.
|
1,575,838 | 1,578,009 | Embedding Ruby in a C++ application using SWIG? | I've successfully created Ruby-C++ bindings in the past using SWIG where the C++ code was compiled as a dynamic library with the Ruby script connecting to it.
However, I'd like to do it the other way around. Create an executable using C++ and enable it to load and execute Ruby code. Ruby should be able to call functions defined on the C++ side as well (naturally, otherwise all I would need is the 'system()' call.)
Does SWIG provide the means to achieve this?
| You may be interested in Ruby embedded into c++
|
1,575,937 | 1,575,951 | Using a pure C++ compiler versus Visual C++ | I searched around for the answers to these questions, but I have had little luck. So, I thought I would post them here to get some clarification. If this is a duplicate, please let me know, and I will close this.
Okay, with that said, I would like to begin learning C++. I come from a C# background and I have a great respect for Visual Studio and what it can do. Now, my question is. How well does Visual Studio's compiler work for C++ as opposed to a non-Microsoft version (such as MinGW)?
My thing is this. I have nothing wrong with Microsoft, but I would really like to learn C++ in a "pure" form and not scewed by any particular implementation. How reliant is Visual C++ on the .NET Framework? Can a "pure" C++ application be created through Visual Studio without any .NET usage or overhead? Does the Visual Studio compiler compile C++ into CIL like it does with C#/VB, or does it compile it all the way down as others do?
Thanks for any help anyone can provide!
| The Visual C++ compiler will compile C++ code into standalone EXEs that have nothing to do with the .NET framework.
The only way to get the .NET baggage thrown in is to compile the C++ as "managed".
If you create a new project (File|New|New Project) Then choose "Win32" from the Visual C++ submenu in the project types and choose "Win32 Console Application" Visual studio will create a simple project with a couple of source files that will compile to a little executable.
Most of the time, Visual C++ is very similar to other compilers. Avoid #pragmas, microsoft libraries (MFC, ATL) and you should be fine.
Edit (thanks Cheeso) - Documentation of where Visual C++ diverges from standard.
In general I would advise using boost libraries for threads and networking because they work on many platforms (i.e linux). Also if your code can compile in GCC and Visual Studio then you are doing a good job keeping it portable.
|
1,576,317 | 1,576,419 | Does code in header file increases binary size? | Consider this:
class Foo{
void func1(){
/*func1 code*/
}
void func2(){
/*func2 code*/
}
};
Case 1: class Foo in Foo.h
Case 2: class Foo nicely seperated among Foo.h and Foo.cpp
Various other cpp files include Foo.h
My question is...Will Case 1 lead to a bigger binary?
| Maybe it will, maybe it won't. It really has nothing to do with header files. What matters here is that your member functions are defined in the class definition. When member functions are defined like that, they are treated as inline functions. If the compiler decides not to actually inline any calls to these functions, there won't be any impact on code size. If the compiler decides to inline any (or all) of the calls, the answer would be "it depends". Inlining calls to small functions might result in increased code size as well as in decreased code size. This all depends on the function itself and on the compiler's capabilities (optimization capabilities specifically).
|
1,576,409 | 1,576,466 | In a makefile, how do I execute a command on each file name in variable? | I know I am doing it wrong, but I can't figure out how to organize this makefile. I define my util source files, and use some functions to define the .o files from them here:
UTIL_SRC = utils/src/foo.cpp utils/src/bar.cpp utils/src/baz.cpp
UTIL_OBJS = $(patsubst utils/src/%.cpp,utils/obj/%.o,$(UTIL_SRC))
This is the target that I use these files for:
lib : lib/libutils.a
lib/libutils.a : $(UTIL_OBJS)
rm -f lib/libutils.a
ar -c -q lib/libutils.a $(UTIL_OBJS)
Then, when I get to the rule to compile these babies, I would love to just have one command that would iterate through each UTIL_OBJS file and each UTIL_SRC file. Instead I have resorted to this monstrosity, which defeats the purpose of storing them in variables.
$(UTIL_OBJS) : $(UTIL_SRC)
g++ $(UTIL_FLAGS) utils/src/foo.cpp -o utils/obj/foo.o
g++ $(UTIL_FLAGS) utils/src/bar.cpp -o utils/obj/bar.o
g++ $(UTIL_FLAGS) utils/src/baz.cpp -o utils/obj/baz.o
Can I condense this down to one line? How? Thanks, great ones!
| It's usually easier to work with implicit rules. There are a lot of predefined ones, where you'll only need to specify variables.
CXX=g++
CXXFLAGS=$(UTIL_FLAGS)
Then you need to define an executable, like this
myutil: $(UTIL_OBJS)
Since you're not storing your objects in the same directory, you'll need to specify a new implicit rule as well though (otherwise, we'd be done now).
utils/obj/%.o: utils/obj/%.cpp
% is a pattern-match, it'll match the same text on both left and right side, so this rule will make foo.o out of foo.cpp.
Try if that'll work without the command (it might have grabbed that from another rule, I'm not sure), otherwise let it say:
utils/obj/%.o: utils/obj/%.cpp
$(CXX) $(CXXFLAGS) -o $@ $^
$@ is the target of the rule (e.g. foo.o), and $^ is all files on the right hand side.
I'm writing this off the top of my head, without the possibility to test it, so please let me know how it turned out.. :)
To make it even more elegant, you can include a dependency file
include .depend
If you're running GNU make, it'll try to make the .depend file if it can't find it (with old school make, you need to create it yourself first, it can be just a dummy though, if you'd like to manage it through the makefile)
.depend: $(UTIL_SRC)
$(CXX) -MM -o $@ $^
The dependency file will contain lines for each .cpp file, telling make what header files it needs, which will allow make to recompile the necessary files when you change something. This doesn't help with your original question though, just thought it might come in handy.
EDIT:
As a response to your edit. You could probably drop the commands for creating the .a-file as well, that too is already available as an implicit rule. Not sure exactly how it works though, haven't used it much. I do know that there are a bunch of quirks in make for dealing with .a(rchive?)-files.
|
1,576,460 | 1,576,496 | Standard Template String class: string.fill() | I need a way to create a string of n chars. In this case ascii value zero.
I know I can do it by calling the constructor:
string sTemp(125000, 'a');
but I would like to reuse sTemp in many places and fill it with different lengths.
I am calling a library that takes a string pointer and length as an argument and fills the string with bytes. (I know that technically string is not contiguous, but for all intents and purposes it is, and will likly become the standard soon). I do NOT want to use a vector.
is there some clever way to call the constructor again after the string has been created?
| The string class provides the method assign to assign a given string a new value. The signatures are
1. string& assign ( const string& str );
2. string& assign ( const string& str, size_t pos, size_t n );
3. string& assign ( const char* s, size_t n );
4. string& assign ( const char* s );
5. string& assign ( size_t n, char c );
6. template <class InputIterator>
string& assign ( InputIterator first, InputIterator last );
Citing source: cplusplus.com (I recommend this website because it gives you a very elaborated reference of the C++ standard libraries.)
I think you're looking for something like the fifth one of these functions: n specifies the desired length of your string and c the character filled into this string. For example if you write
sTemp.assign(10, 'b');
your string will be solely filled with 10 b's.
I originally suggested to use the STL Algorithm std::fill but thus your string length stays unchanged. The method string::resize provides a way to change the string's size and fills the appended characters with a given value -- but only the appended ones are set. Finally string::assign stays the best approach!
|
1,576,647 | 1,576,667 | Using C++ with Eclipse | I'm figuring out that there's two ways of writing C++ in Eclipse: either download the Eclipse IDE for C/C++ Developers or download the regular Eclipse for java and add the CDT plugin. What is the difference between these two? (Note that I'm already exstensively using Eclipse for Java) Thank you
| The C++ tools end up the same so depends if you use Eclipse for other things.
If for other things then I would start with the more complex setup e.g. if you do Java J2EE I would download the Eclipse J2EE then add the C++ tools
If just C++ start with the Eclipse C++
I also found using the Yoxos/Eclipse Source packaging easier to download extra packages. (unless you need the absolute latest patch)
edit:
Sorry I did not read the question fully I have given the general answer. However as you have eclipse working and setup already and if you are happy then just download the C++ plugins. Note I have a separate workspace for java and C++ helps as you will want different perpecives etc and also cuts down on the projects in the explore rs/
|
1,577,084 | 1,577,228 | Storing values of any type as type initially supplied in templated factory method in C++? | This is a slightly different question to this one ([Accessing a method from a templated derived class without using virtual functions in c++?) which I asked recently.
I would like to create an instance of an object using a templated factory method, then from then on only be able to set and get a value based on the initial type supplied to the item.
Here's a quick example of what I'm trying to achieve:
boost::shared_ptr<Item> item = Item::create<float>();
item->setValue(5); // conversion to 5.0 in setting the value
float value = item->value(); // returned value = 5.0
Essentially the only time setValue will fail is if there isn't an implicit conversion from whatever has been supplied to the initial 'type' of the internal value in Item.
So if I made the whole Item class a templated class taking a type, I would need to provide the type of the value every time I created a shared pointer to the Item, which I don't really care about.
The next approach I took was to try and store the initial type in the class and use boost::any for the internal storage, casting the internal type to the initial type specified if there was an implicit conversion. However, I stuggled to store and compare the type information, initially looking at std::type_info, but as setValue took a boost::any, had no way of comparing what was actually passed.
(A slight extension to this might be providing a variant-style list of options to the template argument in the creation and returning the value in the native supplied type.)
There may be a design pattern I'm not aware of, or a different approach I haven't considered, so I'd be interested in hearing any suggestions of how to tackle this?
| Your problem with boost::any is that it's too flexible. The basic idea behind it is still sane. What you need to do is wrap the initial value in an object of type template<typename T> class ItemOfType<T> : public Item. Item::create<T> would then return such a typed object. When you later try to assign a U, you first test if you can dynamic_cast your this to ItemOfType<U>*. This covers your T==U case.
The harder part is the question whether a U is assignable to a T. The usual solution is to instantiate templates, but in your create<T> you don't have the U and in your Item::operator=(U const) you don't have the original T.
|
1,577,488 | 1,577,591 | Templated parameter for a template specialisation? | Hi I've got a static member of a templated class that I want defined for a sub group of classes that are templated ie:
template <typename T>
class FooT
{
private:
static int ms_id;
};
template <typename T>
class Foo {};
template<> template<typename T> int FooT< template Foo<T> >::ms_id = 10;
Sadly this throws the following error under gcc 4.1.1
D:\X\Foo.h(98) : error: template argument 1 is invalid
on the line: template<> template<typename T> int FooT< template Foo<T> >::ms_id = 10;
What am I doing wrong is the general concept allowed in the first place?
| You can do this by partially specializing an "initializer template":
template <typename T>
class FooT
{
private:
static int ms_id;
};
template <typename T>
class Foo {};
template <typename T>
class GetValue {
static const int v = 0;
};
template <typename T>
class GetValue< Foo<T> > {
static const int v = 10;
};
template<typename T> int FooT< T >::ms_id = GetValue<T>::v;
|
1,577,621 | 1,577,646 | Will this regex be enough to remove C++ multiline comments? | I need to parse some C++ files, and to make things easier for me, I thought about removing multiline comments. I tried the following regex : /(\/\*.*?\*\/)/, using the multiline modifier, and it seems to work. Do you think there will be any case where it will fail?
| The following is going to hurt you:
std::cout << "Printing some /* source code */" << std::endl;
This is a kind example. Imagine the damage you could do if the string started a comment and didn't end it? You could end up deleting huge chunks of your code.
A regex may give you a good "quick-and-dirty" solution, and may work in your particular case (I urge you to perform one pass of "extract and print all matches" before you do a pass of "delete all matches" in order to make sure), but in the general case, you will need a much more sophisticated parser. You might be able to account for this situation with a regex, but it's going to get ugly.
EDIT: Thanks to @MSalters in the comments, I've realized that the problem you have involves a bit more than just the source files, though strictly speaking if you use macros with embedded comments you're asking for trouble. So after a bit of testing, it turns out there is already a tool installed on most machines with a C++ compiler that will weed out comments, and handle all the finicky string and macro issues for you. Use this on file.cpp to get the output without comments (single- or multi-line):
cpp file.cpp
Sure, that will expand all the macros and #includes, and may not have the same nice neat formatting you wanted, but it will easily deal with all macro, string, and other issues associated with comment finding. If you don't know, cpp is the C preprocessor as a standalone executable (theoretically you can use #includes and #defines and such in any language with a relatively C-like syntax), so if you don't have it, you can get the same effect with GCC like this:
gcc -E file.cpp
(Change gcc to g++ if you really care - it may handle #include <iostream> better.)
Removing comments is, as far as I know, not strictly a part of the preprocessor, but most preprocessors do it in that stage to simplify the syntax of the actual language parser (well, GCC's preprocessor does, and that's all I have to test with). So if your compiler's preprocessor option will do this for you, and this is all you want done, stop rolling your own right now.
I apologize for not thinking of this sooner. I don't know how it escaped me.
|
1,577,696 | 1,577,754 | Most efficient way to store a mixed collection of doubles and ints | I need to store a collection of ints and doubles (representing nominal and real valued data) in c++. I could obviously store them all in a std::vector<double> , but this feels a bit wrong and doesn't get the aesthetics bonus points.
I could also cook up something based on polymorphism, but I also need the collection to be really efficient: both storing and retrieving the data in the collection should be as fast as possible. I find it hard to judge whether such a solution would be maximally efficient.
I also found boost::variant, which might be of help here.
Additional info: the number of items in the collection will be small (<100) and known when initializing the collection.
Summarizing: I could obviously solve this in countless ways, but I am unsure what would be a good solution when (i) efficiency is really important and (ii) I also want to write somewhat nice code. What is my best bet here?
Edit, additional info: The collection represents a 'row' in a larger data set, its elements represent the values of certain 'columns'. The properties of the rows are known, so it is known what kind of data is stored at which position. The 'efficiency' I am talking about is primarily the efficiency of retrieving the int/double value of a certain column, although fast setting of values is important too. I have some functions that operate on the data that need to retrieve it as fast as possible. Example:
typedef std::vector<double> Row;
void doubleFun(Row const &row)
{
// Function knows there's always a double at index 0
double value = row[0];
...
}
void integerFun(Row const &row)
{
// Function knows there's always an integer at index 1
int value = row[1];
...
}
After some more thought and reading the suggestions so far, it seems that just storing int columns and double columns in two separate vectors is a solid solution. The collection Row could then just define two different members for retrieving nominal and real data that the functions can use.
Just storing as a vector<double> is okay too I guess, but it depends on how fast the conversion between double and int is (which is probably pretty impressive).
Sorry for being a little unclear at first, I hope it's clearer and now and that I can get some more thoughts on the matter.
| Is ordering an important point in your container ?
If not so:
class MyContainer
{
std::vector<double> doubles;
std::vector<int> ints;
push(double value) { doubles.push_back(value); }
push(int value) { ints.push_back(value); }
....
};
The iterator part (to browse the whole container) could be a little trickier...
|
1,577,765 | 1,577,851 | Why must a pointer to a char array need strcpy to assign characters to its array and double quotes assignment will not work? | The first example does not work when you go to delete the pointer. The program either hangs when I add the null terminator or without it I get:
Debug Assertion Failed Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) from Visual Studio 2008
//Won't work when deleting pointer:
char *at = new char [3];
at = "tw"; // <-- not sure what's going on here that strcpy does differently
at[2] = '\0'; // <-- causes program to hang
delete at;
//Works fine when deleting pointer:
char *at = new char [3];
strcpy(at,"t");
at[1] = 'w';
at[2] = '\0';
delete at;
So what's going on when I use double quotes instead of strcpy? Both of them will cout the string perfectly and debugger does not show anything different.
| Because a char* isn't a string. It's just a pointer to some character, with the convention that there might be more characters to follow and that after the last one there is a '\0'.
A string literal in C (and thus in C++) like "abc" is just an array of characters, with the compiler silently adding a '\0'. When you assign an array to a pointer, the array silently converts a pointer to the first element. The result is that
at = "tw";
means, the pointer at is assigned the address of the first character in the string literal "tw". By this, it will lose its old value. Since this was the address of a dynamically allocated character array, you are leaking this array.
When you later assign to a character in the array at now points to, you are assigning a new value to some character in the string literal. That's invoking undefined behavior and the program hanging or crashing immediately is probably the best that could happen to you when you do this. (On many platforms you're writing to read-only memory doing so.)
Later you pass at to delete[] (and not delete, since you called new[], not new). In doing so, you pass it the address of the string literal, instead of the allocated character array. This will, of course, mess up the heap manager. (VC's runtime library catches this in Debug mode.)
std::strcpy, on the other hand, copies a string character by character from one array to another array. No pointers will be changed, only pieces of memory are copied. The pointer to the target array still points to the target array afterwards, only the data in that array has changed.
Let me add this: As a beginner in C++, you should use std::string, rather than C strings. That does all the dirty work for you and has sane semantics.
|
1,577,940 | 1,577,960 | How to store TypeInfo | class A {}
A a;
type_info info = typeid (a); // error type_info is private
i want a list list<type_info> to store the type of classes. Is there a solution?
| You cannot instantiate objects of the type_info class directly, because the class has only a private copy constructor. Since the list needs copy constructor...
If you really need it, use std::list< type_info*>.
I don't know why you need this list, but I would think to an alternative design, not involving RTTI, if possible.
|
1,578,006 | 1,581,581 | Qt: TableWidget's ItemAt() acting weirdly | i'm working on a windows application, where in a dialog i query some data from Postgres, and manually show the output in a table widget.
m_ui->tableWidget->setRowCount(joinedData.count());
for(int i=0; i<joinedData.count(); i++) //for each row
{
m_ui->tableWidget->setItem(i, 0, new QTableWidgetItem(joinedData[i].bobin.referenceNumber));
m_ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(joinedData[i].bobin.width)));
m_ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getHole())));
m_ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getLessThanZeroFive()))); m_ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroFive_to_zeroSeven())));
m_ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroFive_to_zeroSeven_repetitive())));
m_ui->tableWidget->setItem(i, 6, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getZeroSeven_to_Three())));
m_ui->tableWidget->setItem(i, 7, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getThree_to_five())));
m_ui->tableWidget->setItem(i, 8, new QTableWidgetItem(QString::number(joinedData[i].tolerance.getMoreThanFive())));
}
Also, based on row and column information, i paint some of these tablewidgetitems to some colors, but i don't think it's relevant.
I reimplemented the QDialog's contextMenuEvent, to obtain the right clicked tableWidgetItem's row and column coordinates:
void BobinFlanView::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(m_ui->tableWidget);
//standard actions
menu.addAction(this->markInactiveAction);
menu.addAction(this->markActiveAction);
menu.addSeparator();
menu.addAction(this->exportAction);
menu.addAction(this->exportAllAction);
//obtain the rightClickedItem
QTableWidgetItem* clickedItem = m_ui->tableWidget->itemAt(m_ui->tableWidget->mapFromGlobal(event->globalPos()));
// if it's a colored one, add some more actions
if (clickedItem && clickedItem->column()>1 && clickedItem->row()>0)
{
//this is a property, i'm keeping this for a later use
this->lastRightClickedItem = clickedItem;
//debug purpose:
QMessageBox::information(this, "", QString("clickedItem = %1, %2").arg(clickedItem->row()).arg(clickedItem->column()));
QMessageBox::information(this, "", QString("globalClick = %1, %2\ntransformedPos = %3, %4").arg(event->globalX()).arg(event->globalY())
.arg(m_ui->tableWidget->mapFromGlobal(event->globalPos()).x()).arg(m_ui->tableWidget->mapFromGlobal(event->globalPos()).y()));
menu.addSeparator();
menu.addAction(this->changeSelectedToleranceToUygun);
menu.addAction(this->changeSelectedToleranceToUyar);
menu.addAction(this->changeSelectedToleranceToDurdurUyar);
//... some other irrevelant 'enable/disable' activities
menu.exec(event->globalPos());
}
The problem is, when i right click on the same item i get the same global coordinates, but randomly different row-column information. For instance, the global pos is exactly 600,230 but row-column pair is randomly (5,3) and (4,3). I mean, what?!
Also, when i click to an item from the last to rows (later than 13, i guess) will never go into condition "if (clickedItem && clickedItem->column()>1 && clickedItem->row()>0)", i think it's mainly because 'clickedItem' is null.
I'll be more than glad to share any more information, or even the full cpp-h-ui trio in order to get help.
Thanks a lot.
| Try this:
QTableWidgetItem* clickedItem = m_ui->tableWidget->itemAt(event->pos());
The problem is that you are trying to map the global position to the table widget position, without considering the scrollable area. To map the global position into something you can pass to itemAt, use tableWidget->viewport()->mapFromGlobal.
|
1,578,130 | 1,578,312 | how to design system so users can generate their own objects using dlls | I have a server which takes some messages x and outputs some messages Y. Currently the x to y mapping is fixed. So x1 will always generate y1 with corresponding fields.
But now I want to be able to make it configurable such that the users can put their own dll which will generate x1 to y2, y3, or however they want. In case if they don't handle it then it should take a default mapping which is x1 to y1.
One more thing is most of my output messages y1, y2 , y3 are already existing objects which are all derived from a base class.
And I want to be able to do the same thing the other way around...meaning y2(incoming message) to be converted to x1 depending on the user dll.
Can we accomplish this using DLLs? or is there a better way of doing this??
Is there a design pattern(factory pattern or something) to do this correctly so that it is flexible in future also.
Thanks!!!
| This is not too hard, but you will need to provide an interface header (.h file) to DLL writers. You'll also need to tell them which compiler to use, or use a COM-compatible interface.
A quick sketch would be an interface that provides
A queryTypesSupported function, provided by the DLL and called by the EXE to determine the types supported
A std::auto_ptr<Ybase> processMessage(Xbase&) function, implemented by the DLL for the actual processing.
A virtual std::string Ybase::serialize() const function to turn the message into text.
|
1,578,162 | 1,578,265 | Is there any trick to handle very very large inputs in C++? |
A class went to a school trip. And, as usually, all N kids have got their backpacks stuffed with candy. But soon quarrels started all over the place, as some of the kids had more candies than others. Soon, the teacher realized that he has to step in: "Everybody, listen! Put all the candies you have on this table here!"
Soon, there was quite a large heap of candies on the teacher's table. "Now, I will divide the candies into N equal heaps and everyone will get one of them." announced the teacher.
"Wait, is this really possible?" wondered some of the smarter kids.
Problem specification
You are given the number of candies each child brought. Find out whether the teacher can divide the candies into N exactly equal heaps. (For the purpose of this task, all candies are of the same type.)
Input specification
The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.
Each test case looks as follows: The first line contains N : the number of children. Each of the next N lines contains the number of candies one child brought.
Output specification
For each of the test cases output a single line with a single word "YES" if the candies can be distributed equally, or "NO" otherwise.
Example
Input:
2
5
5
2
7
3
8
6
7
11
2
7
3
4
Output:
YES
NO
The problem is simple but the case is that SPOJ judges are using very very large inputs. I have used unsigned long long as datatype, yet it shows wc..
Here's my code:
#include<iostream>
using namespace std;
int main()
{
unsigned long long c=0,n,k,j,testcases,sum=0,i;
char b[10000][10];
cin>>testcases;
while(testcases-->0)
{
sum=0;
cin>>n;
j=n;
while(j-->0)
{
cin>>k;
sum+=k;
}
if(sum%n==0)
{
b[c][0]='Y';b[c][1]='E';b[c][2]='S';b[c][3]='\0';
c++;
}
else
{
b[c][0]='N';b[c][1]='O';b[c][2]='\0';
c++;
}
}
for(i=0;i<c;i++)
cout<<"\n"<<b[i];
return 0;
}
| Easy. Don't add up the number of candies. Instead, keep a count of kids, a count of candies per kid. (CCK), and a count of extra candies (CEC. When you read a new line, CK += 1; CEC += newCandies; if (CEC > CK) CCK += (CEC / CK); CEC %= CK;
|
1,578,190 | 1,578,544 | Using a QListView or similar effectively in Qt4 | I am slowly getting used to using the Qt4 GUI framework. In a project I am working on, I need to be able to add/edit/remove Team objects in a list. Coming from a C#.NET perspective, I would do something like
List<Team> teams = new List<Team>();
teamsListBox.DataSource = teams;
teamsListBox.DisplayMember = "Name";
Then use buttons on the form to do the adding/removing/editing.
But, from what I can tell, there is no easy way to do this in Qt. I have looked over the documentation for QListView, QListWidget, QStandardItemModel, etc. but I cannot figure out how to get the equivalent Qt code for the C#.
My objective is to show the Teams in a list box of some kind, then be able to add/remove/edit the Teams underneath it at runtime.
How would you do this?
| You should have a look at QAbstractItemModel and QStandardItemModel or create a customized TeamItemModel class for your teams that inherits from QAbstractItemModel. Those customized class will manage how the items are displayed in the Widget like QListView.
A simple for QString item example with QStringList:
QStringList list;
list << "item1" << "item2" << "item3" << "item4" << "item5";
ui->listView->setModel(new QStringListModel(list));
Then adding/removing/updating a Team should be easier than what you have tried.
Hope that helps.
|
1,578,215 | 1,578,354 | Exporting template code = dangerous? (MSVC) | As I noted in another SO question, I came across this article. The issue came up when I compiled boost 1.40 via MSVC7.1 and several C4251 warnings popped up.
Now, after reading said article, I wonder: Is it generally discouraged to export template code, e.g.
class DLLEXPORT_MACRO AClass
{
public:
std::vector<int> getVecCopy() { return myVec; }
...
}
Say this code is compiled into a DLL via MSVC7.1.
Though this code does not produce any errors when referenced from other MSVC7.1 code, it is said that referencing this DLL in MSVC8 code produces crashes at runtime (memory alignment issues?).
Since this obviously is bad...what is a "best practice" to cope with the issue of exporting template code?
| This appears to be a bad idea, as std::vector differs or might differ between compiler versions. However, this can likely fail at load time, because the name mangling of std::vector should differ across compiler versions (that's part of the rationale for name mangling).
This link-time failure is something you can't really enforce as a developer though, other than buying compilers that support it. The other solution is to keep template types out of DLL interfaces entirely. Put them into private members.
Note that the problem is not unique to templates. Imagine for a moment that std::string is a UDT instead of a typedef, and provided by the compiler runtime. It could still change between compiler versions, and certainly between compiler vendors. It would still be unusable in a DLL interface.
For these reasons, the practical solutions are 0. use C, 1. use COM or 2. settle on a single compiler version.
|
1,578,635 | 1,578,652 | Declaring a global in a global header file? | I have a header file, lets say Common.h, that is included in all of the files over several projects. Basically i want to declare a global variable, e.g.:
class MemoryManager;
DLL_EXPORT MemoryManager* gMemoryManager;
When i do this i get tons of linker errors saying
class MemoryManager* gMemoryManager is already defined.
:(?
| As it is you are creating a separate copy of the variable in each compiled file. These are then colliding at the linking stage. Remember that the preprocessor reads in all the header files and makes one big file out of all of them. So each time this big file is compiled, another identical copy of gMemoryManager is created.
You need to use extern and define it in one non-header file.
In your header file
extern DLL_EXPORT MemoryManager* gMemoryManager;
In one of your C++ files
DLL_EXPORT MemoryManager * gMemoryManager;
By the way I have no idea what DLL_EXPORT does, I am just assuming it needs to go in both places.
|
1,578,703 | 1,578,767 | variable + value macro expansion | I tried without any result.
My code looks like this:
#include "stdafx.h"
#include <iostream>
#define R() ( rand() )
#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT() H(S(distinct_name_), R())
int main(int argc, _TCHAR* argv[])
{
std::cout << CAT() << std::endl;
std::cout << CAT() << std::endl;
std::cout << CAT() << std::endl;
return 0;
}
I would like to get a result like this:
distinct_name_12233
distinct_name_147
distinct_name_435
as a result of concatenating
distinct_name_ (##) rand()
Right now I am getting an error:
term does not evaluate to a function taking 1 arguments.
Is this achievable ??
EDIT:
I finally succeeded after couple of hours. The preprocessor still does strange things I cannot understand completely. Here it goes:
#include "stdafx.h"
#include <iostream>
class profiler
{
public:
void show()
{
std::cout << "distinct_instance" << std::endl;
}
};
#define XX __LINE__
#define H(a,b) ( a ## b )
#define CAT(r) H(distinct_name_, r)
#define GET_DISTINCT() CAT(XX)
#define PROFILE() \
profiler GET_DISTINCT() ;\
GET_DISTINCT().show() ; \
int main(int argc, _TCHAR* argv[])
{
PROFILE()
PROFILE()
return 0;
}
And the output is:
distinct_instance
distinct_instance
Thanks @Kinopiko for __LINE__ hint. :)
| I see that a lot of people have already correctly answered this question, but as an alternative suggestion, if your preprocessor implements __TIME__ or __LINE__ you could get a result quite like what you want, with a line number or time concatenated, rather than a random number.
|
1,578,714 | 1,578,764 | One class with multiple implementation files | Is there anything wrong with having a single class (one .h) implemented over multiple source files? I realize that this could be a symptom of too much code in a single class, but is there anything technically wrong with it?
For instance:
Foo.h
class Foo
{
void Read();
void Write();
void Run();
}
Foo.Read.cpp
#include "Foo.h"
void Foo::Read()
{
}
Foo.Write.cpp
#include "Foo.h"
void Foo::Write()
{
}
Foo.Run.cpp
#include "Foo.h"
void Foo::Run()
{
}
| This is fine. In the end, it will be all linked together.
I have even seen code, where every member function was in a different *.cpp file.
|
1,578,829 | 1,578,848 | Cannot open include file "AIUtilities.h": No such file or directory. But it exists? | I have a two projects, AI and Core, which used to hold a circular dependency. I have a CoreUtilities file that I have broken up to remove this dependency, and added the functions I have removed to a new file called AIUtilities(.cpp/.h).
I then went to the piece in my AI project that uses these functions and added #include "AI/AIUtilities.h" and changed the function call from CoreUtilities::Functionname to AIUtilities::Functionname. Upon compile, I recieved the error given in the title.
Why! How can I fix it?
| Did you update your project settings with the path to the direcory containing AI/AIUtilities?
Update:
From the solution explorer window, right click on your project and choose "properties" then a new windows "your_project_name property page" will pop up.
In this window on the left pane you'll see a tree. Click on 'Configuration properties' which expands to multiple choices. Continue clicking on 'C/C++' then on General. On the right pane appears multiple properties that affect your project.
Choose the "Additional include directories" property and add the path to your new directory. For instance if your path is : "C:\AI\AIUtilities.h" add the following: "C:\" in the property.
Click on "Aplpy button". Done.
As mentioned in other post, you must consider that moving your project around will break your project settings. Don't forget to update them. Or use either environnement variable to set the root of your project or use the "../../" trick. But personnaly I prefer the former.
|
1,578,950 | 1,578,968 | The procedure entry point could not be located in the dynamic link library Core.dll | I am converting my project to use DLLs and am trying to break apart my Singleton class to avoid using templates.
My class, LudoMemory, originally inherited from Singleton. I am trying to give it the functions to destroy and create itself now and have my main engine not rely on the Singleton.
I have written a simple destroy method like such:
LudoMemory *memory_Singleton = NULL;
void LudoMemory::Destroy()
{
LUDO_SAFE_DELETE(m_Singleton)
}
and upon running the program (no compiler errors) I recieve this error:
The procedure entry point
?Destroy@LudoMemory@@SAXXZ could not
be located in the dynamic link library
LudoCore.dll
LudoCore is the project that LudoMemory belongs to. Why is this happening? How can I solve it?
| you don't have multiple versions of ludocore.dll on your system, do you?
Procedure entry points errors usually mean: you compiled your project against ludocore.lib version x, and when running the program, it uses ludocore.dll version y, and version y does not define LudoMemory::Destroy().
|
1,579,007 | 1,589,683 | How can I include a subset of a .cpp file in a Doxygen comment? | I'm trying to write some Doxygen comment blocks, and I'd like to include example snippets of code. Of course, I'd like the examples to actually compile so they don't get stale.
My example.cpp (that I \include in the .h file) looks like this:
#include "stdafx.h"
#include "../types_lib/Time_Limiter.h"
#include <vector>
void tl_demo () {
// scarce will be a gate to control some resource that shouldn't get called
// more than 10 times a second
Time_Limiter scarce (10);
// here's a bunch of requests
std::vector<int> req (500);
for (size_t i=0;i<req.size ();i++) {
scarce.tick ();
// once we get here, we know that we haven't ticked
// more than 10 times in the last second.
// do something interesting with req[i]
}
}
// endcode
and my header file (that I'm running Doxygen) looks like this:
/**
* \ingroup types_lib
*
* \class Time_Limiter
*
* \brief Thread safe gate used to control a resource (such as an internet quote service) that has a limit on how often you can call it.
*
* \dontinclude Time_Limiter_example.cpp
* \skipline void
* \until endcode
*
**/
And I'd like to get doxygen to just include stuff starting at "void demo" to the end of the file (but without the // endcode).
I've tried experimenting with \dontinclude and \skip, \skipline, and \until, and I can't quite figure out the right incantations.
EDIT: included my .h file, and now I've almost got the right incantation. This does almost exactly what I want, is there some way to use \until without a tag, and get rid of that last // endcode line from example.cpp?
| EDITED to add 2nd arg to clip macro.
Here's what I've done, which seems to work for me. Mostly taken from hint from EricM....
my source file Time_Limiter_example.cpp is:
#include "stdafx.h"
#include "../types_lib/Time_Limiter.h"
#include <vector>
void tl_demo () {
// scarce will be a gate to control some resource that shouldn't get called
// more than 10 times a second
Time_Limiter scarce (10);
// here's a bunch of requests
std::vector<int> req (500);
for (size_t i=0;i<req.size ();i++) {
scarce.tick ();
// once we get here, we know that we haven't ticked
// more than 10 times in the last second.
// do something interesting with req[i]
}
} // endcode
void tl_demo_short ()
{
} //endcode
And I want to include it, but not have the #includes at the top.
I defined an ALIAS in my Doxyfile as:
ALIASES += clip{2}="\dontinclude \1 \n \skipline \2 \n \until endcode"
And in my header, my comment looks like this:
/**
* \ingroup types_lib
*
* \class Time_Limiter
*
* \brief Thread safe gate used to control a resource (such as an internet quote service) that has a limit on how often you can call it.
*
* \clip{Time_Limiter_example.cpp,tl_demo}
**/
And that does exactly what I want, including just the funciton tl_demo () from the .cpp file.
|
1,579,086 | 1,579,533 | Why does ofstream sometimes create files but can't write to them? | I'm trying to use the ofstream class to write some stuff to a file, but all that happens is that the file gets created, and then nothing. I have some simply code here:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
ofstream file;
file.open("test.txt");
if (!file) {
cout << strerror(errno) << endl;
} else {
cout << "All is well!" << endl;
}
for (int i = 0; i < 10; i++) {
file << i << "\t" << time(NULL) << endl;
}
file.flush();
file.close();
return 0;
}
When I create a console application, everything works fine, so I'm afraid this code is not completely representative. However, I am using code like this in a much larger project that - to be honest - I don't fully understand (Neurostim). I'm supposed to write some class that is compiled to a dll which can be loaded by Neurostim.
When the code is run, "test.txt" is created and then "No error!" is printed, as this is apparently the output from strerror. Obviously this is wrong however. The application runs perfectly otherwise, and is not phased by the fact that I'm trying to write to a corrupted stream. It just doesn't do it. It seems to me like there is no problem with permissions, because the file is in fact created.
Does anyone have any ideas what kind of things might cause this odd behavior? (I'm on WinXP Pro SP3 and use Visual C++ 2008 Express Edition)
Thanks!
| Just a thought :- in your real code are you re-using your stream object?
If so, you need to ensure that you call clear() on the stream before re-using the object otherwise, if there was a previous error state, it won't work. As I recall, not calling clear() on such a stream would result in an empty file that couldn't be written to, as you describe in your question.
|
1,579,154 | 1,579,328 | ASSERT fails on CDC SelectObject() call - What can I try? | I'm working on a multi-threaded win32 MFC application. We are rendering a map and displaying it in a pane in the user interface along with custom-rendered objects on top. It's slow to render (~800 ms), which is happening on the User Interface thread.
I'm trying to move the rendering onto its own thread so that the menus still remain snappy while the other rendering can still run in the background. The Draw thread will render continually using its own CDC. The UI thread will call a redraw function, which locks the mutex, and takes the last snapshot of the CBitmap and draws it using the UI's CDC. Every location where the Draw thread's CDC is used, is locked by the mutex.
What I'm seeing is the thread creating a new CBitmap via CreatCompatibleBitmap, and then trying to select the new CBitmap object into the Draw thread's CDC.
this->m_canvas.CreateCompatibleDC(&compatibleDC);
this->m_bitmap = new CBitmap();
this->m_bitmap->CreateCompatibleBitmap(&compatibleDC, m_width, m_height);
m_oldBitmap = this->m_canvas.SelectObject(m_bitmap);
At this point, there is a debug ASSERT failure in CGdiObject::FromHandle().
CGdiObject* PASCAL CGdiObject::FromHandle(HGDIOBJ h)
{
CHandleMap* pMap = afxMapHGDIOBJ(TRUE); //create map if not exist
ASSERT(pMap != NULL);
CGdiObject* pObject = (CGdiObject*)pMap->FromHandle(h);
ASSERT(pObject == NULL || pObject->m_hObject == h);
return pObject;
}
The second ASSERT is failing because the m_hObject does not match the handle passed in. Basically, MFC is taking the handle, and doing a lookup to get a CBitmap object which somehow doesn't match the CBitmap that was just created.
Does this sound familiar to anyone? What could be happening to cause the FromHandle method to return the wrong object? Is there a fundamental flaw with the way I create a CDC for the Draw thread, and then re-use it over and over? Are there any approaches I can take to help debug/fix this problem?
| Golden. The mapping between handles and objects are in thread-local storage.
In a multi-threaded environment
because windows are owned by threads,
MFC keeps the temporary and permanent
window handle map in thread local
storage. The same is true for other
handle maps like those for GDI objects
and device contexts. Keeping the
window handle maps in thread local
storage ensures protection against
simultaneous access by several
threads.
So basically, store the handle, then create a CBitmap from the handle in order to manipulate them between threads.
My mistake was in the UI thread creating my CBitmap, and then accessing the CBitmap object from both threads.
|
1,579,232 | 1,579,264 | C++ Get object type at compile time, e.g., numeric_limits<typeof<a>>::max()? | Given int a;, I know that the following returns the largest value that a can hold.
numeric_limits<int>::max()
However, I'd like to get this same information without knowing that a is an int. I'd like to do something like this:
numeric_limits<typeof<a>>::max()
Not with this exact syntax, but is this even possible using ISO C++?
Thanks, all. Aurélien Vallée's type_of() comes closest, but I'd rather not add anything extra to our codebase. Since we already use Boost, Éric Malenfant's reference to Boost.Typeof led me to use
numeric_limits<BOOST_TYPEOF(m_focusspeed)>::max()
I'd never used it before. Again, thanks for so many well-informed responses.
| numeric_limits is what is known as a type trait. It stores information relative to a type, in an unobtrusive way.
Concerning your question, you can just define a template function that will determine the type of the variable for you.
template <typename T>
T valued_max( const T& v )
{
return numeric_limits<T>::max();
};
template <typename T>
T valued_min( const T& v )
{
return numeric_limits<T>::min();
};
or just create a small type returning structure:
template <typename T>
struct TypeOf
{
typedef T type;
};
template <typename T>
TypeOf<T> type_of( const T& v )
{
return TypeOf<T>();
}
int a;
numeric_limits<type_of(a)::type>::max();
|
1,579,273 | 1,579,518 | How would you solve this math equation for x in C++/C | Solve this equation for x, (1 + x)^4=34.5 . I am interested in the math libraries you'd use.
the equation is MUCH SIMPLER (1 + x)^4=34.5
thanks
| approximate x*(x+a)^b=c
You'll need a more robust solution for more complex polynomials, but this may be good enough to finish your homework.
This algorithm uses Newton's Method and is written in Ruby. You can verify that the derivative and answer is correct using wolfram|alpha.
def f(x,a,b,c)
return x*(x+a)**b-c
end
def df(x,a,b,c)
return (x+a)**b+b*x*(x+a)**(b-1)
end
def newton(a,b,c)
xn=0 #initial seed for Newton's method
while true
xn2=xn-f(xn,a,b,c)/df(xn,a,b,c) #Newton's method
print "f(%.5f)=%.5f\n"%[xn,f(xn,a,b,c)]
break if (xn2*10000).to_i==(xn*10000).to_i #set desired precision here
xn=xn2
end
print "root is %.5f"%[xn2]
end
newton(1,4,34.5)
this produces:
f(0.00000)=-34.50000
f(34.50000)=54793902.65625
f(27.44093)=17954483.09402
f(21.79391)=5883122.74717
f(17.27661)=1927672.51373
f(13.66318)=631598.66717
f(10.77301)=206926.07160
f(8.46171)=67782.26596
f(6.61400)=22194.34671
f(5.13819)=7259.61867
f(3.96214)=2367.67791
f(3.03097)=765.73665
f(2.30728)=241.54928
f(1.77466)=70.68568
f(1.43951)=16.48341
f(1.30101)=1.97186
f(1.27945)=0.04145
f(1.27897)=0.00002
root is 1.27897
|
1,579,357 | 1,587,913 | Heap currupted error in VS2005 with OpenCV? | I'm getting an error called, "corruption of the heap" when I try to debug this simple code,
CvCapture* capture = cvCaptureFromFile("1.avi");
if( capture )
{
cvNamedWindow( "Motion", 1 );
while(true)
{
//Grab the frame and display the image
//No need of this, because error is coming in the cvCaptureFromFile("1.avi");
}
}
But the actual problem is, that error wont come if I try run the .exe (debug output) of the code (not through the vs2005). can anyone please help me to figure this out ? Thanks...
| This likely means that OpenCV can't load the AVI. I always convert my videos to RAW I420 format; this loads perfectly.
The following command will convert a video to this format using MEncoder:
mencoder -ovc raw -nosound -vf format=i420 -o "%OUTPUT%" "%INPUT%"
where %INPUT% and %OUTPUT% are the input and output files.
|
1,579,391 | 1,579,434 | Static Global Fields in a Shared Library - Where do they go? | I have a cpp file from which I am generating a shared library (using autofoo and the like). Within the cpp file, I have declared a couple of static fields that I use throughout the library functions.
My question is 2-part:
1) Where are these fields stored in memory? It's not as if the system instantiates the entire library and keeps it in memory... the library, after all, really is just a bunch of hooks.
2) Is there a better way to do this? The reason I did it to begin with is that I want to avoid requiring the user to pass the fields into every library function call as parameters.
Thanks!
| The code used to load shared libraries:
Generally (each has minor technical differences):
Loads the shared lib into memory
Walks the symbol table and updates the address of function in the DLL
Initializes any global static members using their constructor.
Note: The shared lib loader need not do all this at the load point.
It may do some of these jobs lazily (implementation detail). But they will be done before use.
Any Global staic POD variables (things with no constructor). Will be stored in special memory segments depending on weather they are initialized or not (again an implementation detail). If they were initialized then they will be loaded with the from disk (or shared lib source) with that value already defined.
So the answer to your questions:
undefined.
The library is code segments
Initialized data segments
Uninitialized data segments
Some utility code that knows how to link it into a running application.
Better than what exactly
Good practice would suggest passing values to a function rather than relying on global state. But to be honest that is an over generalization and really down to the problem.
|
1,579,426 | 1,590,115 | CMake Visual Studio linking executable with static library | I have a very simple (currently just a main.cpp) CMake C++ project that I'm trying to build on both Mac OS X and Windows. It depends on libgsasl, which I have compiled as a static library on both platforms.
Mac OS X has no problems building, and Windows doesn't complain during the build either and produces an EXE. When I try to run the EXE on windows, it gives an error message saying the application cannot run because it can't find libgsasl.dll.
I'm not even trying to link against the dynamic library, just the static library (the .lib version). Am I missing something? In Visual Studio it looks like the gsasl.lib file is found and included in the linking command.
| In the MS tool chain, a .lib can either be static library or an import library to the actual DLL.
You can use dumpbin to peek inside the library to see the actual type it is. There are a couple of different ways to handle the details, but my preferred technique is to use the /summary option. An import library will have sections .idata$n (where n is an integer) while a static library will have a .text section.
|
1,579,487 | 1,579,501 | C++ initializing the dynamic array elements | const size_t size = 5;
int *i = new int[size]();
for (int* k = i; k != i + size; ++k)
{
cout << *k << endl;
}
Even though I have value initialized the dynamic array elements by using the () operator, the output I get is
135368
0
0
0
0
Not sure why the first array element is initialized to 135368.
Any thoughts ?
| My first thought is: "NO...just say NO!"
Do you have some really, truly, unbelievably good reason not to use vector?
std::vector<int> i(5, 0);
Edit: Of course, if you want it initialized to zeros, that'll happen by default...
Edit2: As mentioned, what you're asking for is value initialization -- but value initialization was added in C++ 2003, and probably doesn't work quite right with some compilers, especially older ones.
|
1,579,492 | 1,588,191 | pimpl idiom and template class friend | I'm trying to use the pimpl idiom to hide some grungy template code, but I can't give derived classes of the body class friend access to the handle class. I get an error C2248 from MSVC 9 sp1. Here's some code to duplicate the error:
//
// interface.hpp
//
namespace internal{
template<class T>
class specific_body;
}
class interface
{
struct body;
body *pbody_;
interface(body *pbody);
template<class T>
friend class internal::specific_body;
public:
~interface();
interface(const interface &rhs);
bool test() const;
static interface create( bool value );
};
//
// interface.cpp
//
struct interface::body
{
virtual ~body(){}
virtual bool test() const = 0;
virtual interface::body *clone() const = 0;
};
class true_struct {};
class false_struct {};
namespace internal {
template< class T>
class specific_body : public interface::body
{ // C2248
public:
specific_body(){}
virtual bool test() const;
virtual interface::body *clone() const
{
return new specific_body();
}
};
bool specific_body<true_struct>::test() const
{
return true;
}
bool specific_body<false_struct>::test() const
{
return false;
}
} //namespace internal
interface::interface(body *pbody) : pbody_(pbody) {}
interface::interface(const interface &rhs) : pbody_(rhs.pbody_->clone()) {}
interface::~interface() { delete pbody_; }
bool interface::test() const
{
return pbody_->test();
}
interface interface::create(bool value )
{
if ( value )
{
return interface(new internal::specific_body<true_struct>());
}
else
{
return interface(new internal::specific_body<false_struct>());
}
}
//
// main.cpp
//
// #include "interface.hpp"
//
int _tmain(int argc, _TCHAR* argv[])
{
interface object( interface::create(true));
if ( object.test() )
{
// blah
}
else
{
}
return 0;
}
Any help would be appreciated, I'm trying to hide interface::body and specific_body implementations from the users of interface if that's not obvious from my question.
| Well, I was able to "solve" this problem by making the body a public declaration in the interface. That solves the C2248 error during the declaration of the specific_body. I also made the body a friend to the interface class and added a method to the body struct:
static interface create( body *pbody )
{
return interface(pbody);
}
so that a specific_body can create an interface if there is a nested relationship between instances of specific_body
|
1,579,521 | 1,579,540 | Converting a C-string to a std::vector<byte> in an efficient way | I want to convert a C-style string into a byte-vector.
A working solution would be converting each character manually and pushing it on the vector. However, I'm not satisfied with this solution and want to find a more elegant way.
One of my attempts was the following:
std::vector<byte> myVector;
&myVector[0] = (byte)"MyString";
which bugs and gets me an
error C2106: '=': left operand must be l-value
What is the correct way to do this?
| The most basic thing would be something like:
const char *cstr = "bla"
std::vector<char> vec(cstr, cstr + strlen(cstr));
Of course, don't calculate the length if you know it.
The more common solution is to use the std::string class:
const char *cstr;
std::string str = cstr;
|
1,579,532 | 1,587,015 | Create from scratch, or build up on Scratch? | I'm considering building a visual programming language, akin to Scratch, for use by children (a.k.a. poor typists) in programming micro-controllers or robots.
There is, for example, a project to build a graphical programming environment for the Arduino.
I really like Scratch, and would like the graphical coding to be similar. Scratches source is available under its own free license. It is written in Squeak (based on Smalltalk), and I don't know the language.
It occurs to me there might be other projects to build off of. When I looked through Wikipedia's list of graphical languages, I didn't see much that was open source and could be built off of.
I am familiar with C/C++, Python, and a little bit of Objective C. If I were to build my own project from scratch, I think I would use the Qt library, as I would want to build something cross-platform, but unfortunately, I don't know it either.
If I had an infinite amount of time to work on it, you can bet I'd learn Squeak and Qt and do an exhaustive search of all existing visual programming projects. That not being the case, I'm asking for opinions:
Is there an existing project that I should consider working from?
Would you recommend learning Squeak, or Qt, or something else?
| If you are familiar with C/C++ then its worth learning QT. It should be easy for you to pick up and get going in no time. There are also plenty of examples that come with the package to get you started once you install it. From there you will be able to evaluate how best it can work for you.
|
1,579,663 | 1,579,671 | Does copying the content of one array to another cause a memory leak | Does this code cause a memory leak:
int main(){
int * a = new int[10];
int * b = new int[10];
for(int i = 0 ; i < 10; i++)
{
a[i] = 1;
b[i] = 1;
}
for(int i = 0 ; i < 10; i++)
{
a[i] = b[i]; //each a[i] is allocated 4 bytes on heap
//when we copy b[i] into a[i] do we loose
//the reference to a[i] (hence a leak),
//and replace that reference
//with a reference to a new value?
}
delete[] a;
delete[] b;
}
| No, there's no leak there. You're just copying values within the array. Think of the arrays as two banks of lockers in a changing room - you're just copying what's in one locker and putting it in a locker in the other bank; the locker itself stays where it is.
|
1,579,688 | 1,579,702 | Can c++ create array of pointers to different classes dynamically loaded from dll? | Can c++ create array of pointers to different classes dynamically loaded from dll?
ps.without headers with class definations
| I think you need to have an exported function that instantiates objects of the class. Then you can, of course, put these values into array.
|
1,579,711 | 1,579,734 | Optional parameter for reference to pointer? | How do I declare the second parameter as optional?
template <typename T>
inline void Delete (T *&MemoryToFree,
T *&MemoryToFree2 = ){
delete MemoryToFree;
MemoryToFree = NULL;
delete MemoryToFree2;
MemoryToFree2 = NULL;
}
I tried several things after the = operator, like NULL, (T*)NULL etc. Can this be done?
The only way the compiler let me do it was using an overload...
template <typename T, typename T2>
inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){
delete MemoryToFree;
MemoryToFree = NULL;
delete MemoryToFree2;
MemoryToFree2 = NULL;
}
| You could just overload the function
template <typename T>
inline void Delete (T *&MemoryToFree){
delete MemoryToFree;
MemoryToFree = NULL;
}
template <typename T, typename T2>
inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){
delete MemoryToFree;
MemoryToFree = NULL;
delete MemoryToFree2;
MemoryToFree2 = NULL;
}
|
1,579,719 | 1,579,732 | Variable number of parameters in function in C++ | How I can have variable number of parameters in my function in C++.
Analog in C#:
public void Foo(params int[] a) {
for (int i = 0; i < a.Length; i++)
Console.WriteLine(a[i]);
}
public void UseFoo() {
Foo();
Foo(1);
Foo(1, 2);
}
Analog in Java:
public void Foo(int... a) {
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public void UseFoo() {
Foo();
Foo(1);
Foo(2);
}
| These are called Variadic functions. Wikipedia lists example code for C++.
To portably implement variadic
functions in the C programming
language, the standard stdarg.h header
file should be used. The older
varargs.h header has been deprecated
in favor of stdarg.h. In C++, the
header file cstdarg should be used.
To create a variadic function, an
ellipsis (...) must be placed at the
end of a parameter list. Inside the
body of the function, a variable of
type va_list must be defined. Then the
macros va_start(va_list, last fixed
param), va_arg(va_list, cast type),
va_end(va_list) can be used. For
example:
#include <stdarg.h>
double average(int count, ...)
{
va_list ap;
int j;
double tot = 0;
va_start(ap, count); //Requires the last fixed parameter (to get the address)
for(j=0; j<count; j++)
tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
va_end(ap);
return tot/count;
}
|
1,579,786 | 1,579,813 | Are array of pointers to different types possible in c++? | Are array of pointers to different types possible in c++?
with example please)
| C++ is C with more stuff. So if you want to do it the C way, as above you just make an array of void pointers
void *ary[10];
ary[0] = new int();
ary[1] = new float();
DA.
If you want to do things the object oriented way, then you want to use a collection, and have all the things you going to be adding to the collection derive from the same base object class that can be added to the collection.
In java this is "Object", C++ has no base object built in, but any collection library you use will have such a thing that you can subclass.
|
1,579,809 | 1,589,663 | MATLAB engine versus libraries created by MATLAB Compiler? | To call MATLAB code in C or C++, how do you choose between using the MATLAB engine and using the MATLAB Compiler mcc to create C or C++ shared libraries from your MATLAB code? What are their pros and cons? For the second method, see http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/f2-9676.html
Are there other ways to call MATLAB from C or C++?
| If the computation is linear and long, I would use mcc to compile the code. It is as if MATLAB was simply another library with numerical routines in it to be linked into your program.
If I wanted to provide interaction with MATLAB in my program, where the user could specify any of a large number of statements that would be impossible or merely tedious to code individually, then I would use the MATLAB engine. It is as if I wanted to run MATLAB without the Mathworks' UI.
I have never bothered with opening the MATLAB engine outside of a test.
|
1,579,873 | 1,580,132 | Benefits of Parallel programming | I have three similar questions:
Which known applications have benefits of multicore processors?
Which known applications use posix threads (pthreads)?
What can pthreads do that Java threads cannot?
| Answer to first two questions: most Linux open source projects written in C use pthreads.
For example Apache.
What can pthreads do that java threads cannot?
They can work without Java Virtual Machine.
|
1,579,928 | 1,579,980 | C++ functor - unexpected behaviour? | I have written this program, which sorts some ints using a functor:
#include<iostream>
#include<list>
#include<set>
using namespace std;
struct IntSorter
{
unsigned int comparisons;
IntSorter()
{
std::cout << "new intsorter" << std::endl;
comparisons = 0;
}
bool operator() (const int &a, const int &b)
{
std::cout << "c is " << comparisons << std::endl;
++comparisons;
std::cout << "c is now " << comparisons << std::endl;
return a<b;
}
};
int main(int argc, char *argv[])
{
list<int> my_list;
my_list.push_back(4);
my_list.push_back(3);
my_list.push_back(5);
my_list.push_back(1);
IntSorter s;
my_list.sort(s);
for (list<int>::iterator it=my_list.begin(); it!=my_list.end(); it++)
{
std::cout << *it << std::endl;
}
return 0;
}
The sorting works fine, but the part counting the number of comparisons gives a result I didn't expect:
./prog -a -b -c -d
new intsorter
c is 0
c is now 1
c is 0
c is now 1
c is 0
c is now 1
c is 1
c is now 2
c is 2
c is now 3
1
3
4
5
I was thinking the structure would be reused, counting and storing the number of comparisons. However, it appears to copy it, or some other behaviour as the numbers printed out go 1,1,1,2,3, instead of 1,2,3,4,5. What am I doing wrong?
| You're not really doing anything wrong. The problem lies entirely in your expectation -- the sorter is passed by value, so there's a bare minimum of one copy made as you pass it. The sort function is free to make more copies as well (e.g. a recursive sort will probably pass a copy to each recursive invocation).
There's a simple lesson here: any such object should be cheap to create and/or copy.
|
1,579,981 | 1,580,014 | l-value substr method in C++ | I want to create a substr method in C++ in a string class that I made.
The string class is based on C-style string of course, and I take care of the memory management.
I want to write a substr(start, length) function that can work on the regular way:
CustomString mystring = "Hello";
cout << mystring.substr(0,2); // will print "He"
And also in this way:
mystring.substr(1,3) = "DD"; // mystring will be "HDDo"
Notice that even though I get a 3 chars long sub-string, I put in the assignment only 2 chars and the output string will be HDDo, still.
Any idea how to get this done?
Thanks!
| To support that, you'll probably have to write your substr() to return a proxy object that keeps track of what part of the original string is being referred to. The proxy object will overload operator=, and in it will replace the referred-to substring with the newly assigned one.
Edit in response to comments: the idea of a proxy is that it's similar enough to the class for which it's a proxy that returning a proxy is still a closed operation -- i.e. from the user's viewpoint, all that's visible is the original type of object, but it has capabilities that wouldn't be possible (or would be much more difficult to implement) without the proxy. In this case, we the proxy class would be private to the string class, so the user could never create an instance of the proxy class except as a temporary. That temporary can be used to modify its parent string if you assign to it. Using the proxy in any other way just yields a string.
As to what this buys you over attempting to do it all inside the original string: each proxy object is a temporary object -- the compiler can/will/does keep track of how to create temporaries as needed, destroys them properly at the end of a full expression, etc. The compiler also keeps track of what substring a particular assignment refers to, automatically converts one to a string when we try to use its value, and so on. Simply put, the compiler handles nearly all the hard work involved.
Here's some working code. The surrounding string class is pretty minimal (e.g. it has no searching capability). I'd expect to add a fair amount to a useful version of the string class. The proxy class, however, is complete -- I wouldn't expect to see it change much (if at all) in a feature-complete version of the string class.
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
class string {
std::vector<char> data;
public:
string(char const *init) {
data.clear();
data.assign(init, init+strlen(init));
}
string(string const &s, size_t pos, size_t len) {
data.assign(s.data.begin()+pos, s.data.begin()+pos+len);
}
friend class proxy;
class proxy {
string &parent;
size_t pos;
size_t length;
public:
proxy(string &s, size_t start, size_t len) : parent(s), pos(start), length(len) {}
operator string() { return string(parent, pos, length); }
proxy &operator=(string const &val) {
parent.data.erase(parent.data.begin()+pos, parent.data.begin()+pos+length);
parent.data.insert(parent.data.begin()+pos, val.data.begin(), val.data.end());
return *this;
}
};
proxy substr(size_t start, size_t len) {
return proxy(*this, start, len);
}
friend std::ostream &operator<<(std::ostream &os, string const &s) {
std::copy(s.data.begin(), s.data.end(), std::ostream_iterator<char>(os));
return os;
}
};
#ifdef TEST
int main() {
string x("Hello");
std::cout << x << std::endl;
std::cout << x.substr(2, 3) << std::endl;
x.substr(2, 3) = "DD";
std::cout << x << std::endl;
return 0;
}
#endif
Edit 2:
As far as substrings of substrings go, it depends. The one situation that's not currently covered is if you want to assign to a substring of a substring, and have it affect the original string. If you want something like x=y.substr(1,4).substr(1,2); it'll work fine as-is. The first proxy will be converted to a string, and the second substr will be invoked on that string.
If you want: x.substr(1,4).substr(1,2) = "whatever"; it won't currently work. I'm not sure it accomplishes much, but on the assumption that it does, the addition to support it is fairly minimal -- you'd add a substr member to proxy:
proxy substr(size_t start, size_t len) {
return proxy(parent, pos+start, len);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.