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
|
|---|---|---|---|---|
963,982
| 964,037
|
Should I use return/continue statement instead of if-else?
|
In C, C++ and C# when using a condition inside a function or loop statement it's possible to use a continue or return statement as early as possible and get rid of the else branch of an if-else statement. For example:
while( loopCondition ) {
if( innerCondition ) {
//do some stuff
} else {
//do other stuff
}
}
becomes
while( loopCondition ) {
if( innerCondition ) {
//do some stuff
continue;
}
//do other stuff
}
and
void function() {
if( condition ) {
//do some stuff
} else {
//do other stuff
}
}
becomes
void function() {
if( condition ) {
//do some stuff
return;
}
//do other stuff
}
The "after" variant may be more readable if the if-else branches are long because this alteration eliminates indenting for the else branch.
Is such using of return/continue a good idea? Are there any possible maintenance or readability problems?
|
The compiler will almost certainly generate the same code. Even if it didn't, the difference will be probably irrelevant. Hence, the relevant argument is certainly how people would read it.
Therefore the question is how similar "//do some stuff" and "do other stuff" are. If they are conceptually similar, use if/else. If they're conceptually different, use continue/return.
|
964,139
| 965,794
|
Huge Integer JavaScript Library
|
Is there any JavaScript library that can be used for calculations involving 700+ Digits?
Also, how about the same thing in C++?
|
JavaScript:
Leemon Baird's BigInt library. This seems to be popular. It's made specifically for cryptographic uses.
My own BigInteger library. Similar to the Java BigInteger class, but all calculations are done in base-10.
jsbn. Another BigInteger class similar to Java's. I've never used this one, but the API looks similar to mine.
C++:
Most people use GMP.
CLN - Class Library for Numbers. I've used this in the past and it has a pretty nice API.
|
964,249
| 964,267
|
Linux Shared Libraries c++
|
I have a Shared Library wise.so. How I can use it in my programm? Do I need to include headers of that library?
I work with Eclipce under Linux. I have set a path to the library using -L and -l. But my function is not visible in the program.
Could you explain me how does Shared Library work?
Regards.
EDIT:
I get the following error:
int main() {
char* path = "/export/home/pdmazubi3/workspace/proj1/src/pic.jpg";
CEDD_Descriptor::CEDD ced; // undefined reference to `CEDD_Descriptor::CEDD::CEDD[in-charge]()'
ced.execute(path);
}
Header:
class CEDD
{
public:
CEDD(double Th0, double Th1, double Th2, double Th3,bool CompactDescriptor);
CEDD();
~CEDD(void);
double T0;
double T1;
double T2;
double T3;
bool Compact;
double* execute(char* path);
private:
int cedd_segnum; //number of segments
int* cedd_partitionSize; //number of pixels in each segment
};
|
You need to include the header file in your application and link against it.
Have a look at how to use libraries in shared libraries and Linux howto.
If the header file is not in the same directory as your application (which it usually isn't) then you need to tell compiler where to look for it, you use -I/path/to/include to include path to include directory that contains the header file.
In linking step you need to point to the library. The general usage is to use -L/path/to/lib is path to directory containing your library followed by -l<libname> where <libname> is the name of library without lib e.g. if you have libboost_serialization-d-1_34_1.so you would use -lboost_serialization-d-1_34_1
Examples:
g++ -I/sw/include -Wall -g -I/usr/local/include/boost-1_36/ -c main.cpp -o main.o
g++ -L/sw/lib -lboost_serialization-d-1_34_1 -o x main.o
|
964,396
| 1,032,054
|
absolute path... confused (ubuntu)
|
So in Code::Blocks in Ubuntu (latest).
I have a project in which I load a file and read a number from it.
#include <fstream>
using namespace std;
int main(){
ifstream in("data/file.t");
int n;in>>n;
}
now with a cout<<n it shows -1203926 (and other random numbers) though the number in the file is 0.
data is where the binary is(I mean data and binary are in the same folder(Program)) and I was expecting the path to be relative like in Windows... but only if I put the full path /home/csiz/Desktop/C++/ep0/Program/data/file.t it will get me a 0.
Can you tell me how to make it a relative path? I would prefer something so that in Windows the code can compile without any changes.
|
After using the absolute path I found the mistake.
In codeblocks you can enter the working directory (that in wich it will launch the program) and I accidentally put a . in there.
|
964,719
| 965,872
|
WaitForSingleObject( )
|
I have got myself stuck into a really amazing issue here.The code is like as below.
class A
{
public:
A(){
m_event = CreateEvent(NULL, false, false, NULL); // create an event with initial value as non-signalled
m_thread = _beginthread(StaticThreadEntry, 0, this); // create a thread
}
static void StaticThreadEntry(A * obj) { obj->ThreadEntry(); }
void ThreadEntry();
};
void A::ThreadEntry()
{
WaitforSingleObject(m_event,INFINITE);
}
int main()
{
A a;
SetEvent(m_event); // sets the event to signalled state which causes the running thread to terminate
WaitForSingleObject(m_thread, INFINITE); // waits for the thread to terminate
return 0;
}
Problem :
When the above code is run,sometimes( 1 out of 5 ) it hangs and the control gets stuck in the call to WaitforSingleObject()( inside the main function ).The code always calls SetEvent() function to ensure that the thread would terminate before calling Wait() function.
I do not see any reason why it should ever hang?
|
The problem is your use of the _beginthread API. You cannot use the handle returned from this function with the Win32 wait functions. You should use _beginthreadex or CreateThread. From MSDN:
If successful, each of these functions returns a handle to the newly created thread; however, if the newly created thread exits too quickly, _beginthread might not return a valid handle...
You are ... able to use the thread handle returned by _beginthreadex with the synchronization APIs, which you cannot do with _beginthread.
|
965,093
| 3,394,305
|
Selectively disable GCC warnings for only part of a translation unit
|
What's the closest GCC equivalent to this MSVC preprocessor code?
#pragma warning( push ) // Save the current warning state.
#pragma warning( disable : 4723 ) // C4723: potential divide by 0
// Code which would generate warning 4723.
#pragma warning( pop ) // Restore warnings to previous state.
We have code in commonly included headers which we do not want to generate a specific warning for. However, we want files which include those headers to continue to generate that warning (if the project has that warning enabled).
|
This is possible in GCC since version 4.6, or around June 2010 in the trunk.
Here's an example:
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wuninitialized"
foo(a); /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
foo(b); /* no diagnostic for this one */
#pragma GCC diagnostic pop
foo(c); /* error is given for this one */
#pragma GCC diagnostic pop
foo(d); /* depends on command line options */
|
965,316
| 965,368
|
How can Unix pipes be used between main process and thread?
|
I am trying to channel data via pipes whenever a signal arrives from a thread to the main process.
Is this possible?
How can this be done?
The problem:
A child thread reads data and puts it into a queue.
Main application does its own stuff, however, when data is available on the queue, it should be notified by the thread, and start processing the data (main thread has access to the queue).
How should this scenario be implemented?
|
Yes its possible through pipes.
Step one call pipe to get a pipe:
#include <unistd.h>
int main(...)
{
int fileDescriptors[2];
pipe(fileDescriptors);
Step 2 pass the fileDescriptors[0] to the main process, and fileDescriptors1 to the thread. In Main you wait for the pipe to be written to to by reading from fileDescriptors[0]
...
char msg[100];
read(fileDescriptors[0], msg, 100); // block until pipe is read
}
Step 3, from your thread write to fileDescritpors1 when the signal occurs
void signal_handler( int sig )
{
// Write to the file descriptor
if (sig == SIGKILL)
{
const char* msg = "Hello Mama!";
write(fileDescriptors[1], msg, strlen(msg));
}
}
|
965,401
| 965,461
|
C++ memory management and vectors
|
I'm getting very confused with memory management in relation to vectors and could do with some basic concepts explaining.
I have a program that uses big vectors.
I created the vectors with the new operator and release them at the end of the program with delete to get the memory back.
My question is, if the program crashes or gets aborted for what ever reason, the delete lines will be missed, is there a way to recover the memory even in this scenario.
I also have some other large vectors that I assign without the new keyword.
I have read that these will be created on the heap but do not need to be deallocated in anyway as the memory management is dealt with 'under the hood'.
However I am not sure this is the case as every time I run my program I lose RAM.
So my second question is, can vectors created without the new keyword really be left to their own devices and trusted to clear up after themselves even if code is aborted mid flow.
And I suppose a third question that has just sprung to mind is, if Vectors are automatically created on the heap why would you ever use the new keyword with them?
Thanks for reading,
ben
|
I suspect your questions are about std::vector< T > (as opposed to an array T[]).
When your application crashes or gets aborted for whatever reason, the OS reclaims the memory. If not you are using a truly rare OS and have discovered a bug.
You need to distinguish between the memory used by the vector itself and the memory of its contained objects. The vector can be created on the heap or on the stack as you noted, the memory it allocates for its contained elements is always on the heap (unless you provide your own allocator which does something else). The memory allocated by the vector is managed by the implementation of vector, and if the vector is destructed (either because it goes out of scope for a vector on the stack or because you delete a vector on the heap) its destructor makes sure that all memory is freed.
|
965,725
| 965,873
|
Large file support in C++
|
64bit file API is different on each platform.
in windows: _fseeki64
in linux: fseeko
in freebsd: yet another similar call ...
How can I most effectively make it more convenient and portable? Are there any useful examples?
|
Most POSIX-based platforms support the "_FILE_OFFSET_BITS" preprocessor symbol. Setting it to 64 will cause the off_t type to be 64 bits instead of 32, and file manipulation functions like lseek() will automatically support the 64 bit offset through some preprocessor magic. From a compile-time point of view adding 64 bit file offset support in this manner is fairly transparent, assuming you are correctly using the relevant typedefs. Naturally, your ABI will change if you're exposing interfaces that use the off_t type. Ideally you should define it on the command line, e.g.:
cxx -D_FILE_OFFSET_BITS=64
to make sure it applies to all OS headers included by your code.
Unfortunately, Windows doesn't support this preprocessor symbol so you'll either have to handle it yourself, or rely on a library that provides cross-platform large file support. ACE is one such library (both POSIX based and Windows platforms - just define _FILE_OFFSET_BITS=64 in both cases). I know that Boost.filesystem also supports large files on POSIX based platforms, but I'm not sure about Windows. Other cross-platform libraries likely provide similar support.
|
966,520
| 966,732
|
Is there a way to extract a custom request header with cgicc
|
I am using Cgicc , which has some methods to extract specific request headers, e.g. getUserAgent would return "User-Agent" header.
Is there a generic method that can return an arbitrary header value, e.g. something like
getHeaderValue("x-my-header");
Is there a way to do this using cgicc? and if cannot be done with cgicc, how else can I extract a custom header from the request in c++?
|
No, cgicc does not support this direcly. However, it is just a wrapper around CGI. http://en.wikipedia.org/wiki/Common_Gateway_Interface and it uses "getenv" in CgiInput
class to extract all information provided by the web server.
So if the client send some header that is not supported directly by CgiCC but does supported by the web server (lets say Accept-Encoding:) that you just need to read apropriate
environment variable getenv("HTTP_ACCEPT_ENCODING")
But it should be supported by web server you are working with
EDIT: actually according CGI RFC http://www.ietf.org/rfc/rfc3875.txt web server should provide enviroment variable for your example: HTTP_X_MY_HEADER
|
966,541
| 966,548
|
C++ template with map allocator problem
|
I define a template function which loads a map from a CSV file:
template <class T>
bool loadCSV (QString filename, map<T,int> &mapping){
// function here
}
I then try to use it:
map<int, int> bw;
loadCSV<int>((const QString)"mycsv.csv",&bw);
But get htis compile time error:
error: no matching function for call to
‘loadCSV(const QString, std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >*)’
It seems my function call is bringing in some implicit arguments, but I don't understand the error and how to fix it. Any ideas?
|
Drop the ampersand, you don't want to pass a pointer to the map (notice the asterisk at the end of the error message). Also, you don't have to explicitly cast the string literal. Moreover, the compiler should be able to deduce the template argument automatically.
loadCSV("mycsv.csv", bw);
|
966,544
| 966,549
|
I get "no member function declared in class" error on my copy constructor when I compile a templated class
|
I am using C++ and I am trying to create a templated class (a Stack).
I would like to define the copy constructor and the assignment operator.
There are defined in the header and then I implement them in the cpp file.
Here are the problems I get:
- For the copy constructor:
prototype for ‘Stack::Stack(const Stack&)’ does not match any in class ‘Stack’
- For the assignement operator:
stack.cpp:28: error: no ‘Stack& Stack::operator=(const Stack&)’ member function declared in class ‘Stack’
- For the constructor:
stack.cpp:4: error: candidate is: Stack::Stack()
Here is the header file:
// stack.hpp
#ifndef STACK_HPP
#define STACK_HPP
#include <stdio.h>
#include <assert.h>
template <class T>
class Stack
{
public:
Stack();
~Stack();
Stack(const Stack&);
Stack& operator=(const Stack&);
private:
T* v_;
size_t vsize_;
size_t vused_;
};
Here is the cpp file:
// stack.cpp
#include "stack.hpp"
template <class T>
Stack<T>::Stack() :
v_(0),
vsize_(10),
vused_(0)
{
v_ = new T[vsize_];
}
template <class T>
Stack<T>::~Stack()
{
delete[] v_;
}
// Stack(const Stack&);
template <class T> Stack<T>::Stack( const Stack<T>& other) :
v_(NewCopy(other.v, other.vsize_, other.vsize_)),
vsize_(other.vsize_),
vuser_(other.vused)
{
}
// Stack& operator=(const Stack&);
template<class T> Stack<T>& Stack<T>::operator=(const Stack<T>& other)
{
if (this != &other)
{
T* v_new = NewCopy(other.v_, other.vsize_, other.vsize__;
delvete v_;
v_ = v_new
vsize_ = other.vsize_;
vused_ = other.vused_;
}
return *this
}
One last thing, here is the log from the compilation:
g++ -c stack.cpp -o stack.o
stack.cpp:20: error: prototype for ‘Stack<T>::Stack(const Stack<T>&)’ does not match any in class ‘Stack<T>’
stack.cpp:4: error: candidate is: Stack<T>::Stack()
stack.cpp:28: error: no ‘Stack<T>& Stack<T>::operator=(const Stack<T>&)’ member function declared in class ‘Stack<T>’
I am sure this is only a small typo error but I cannot seem to find it.
Thanks for your help
|
You can't compile templates into separate compilation units. In short, all the template code has to all be in one header. This is likely whats causing your problem.
The reason is that templates don't define true classes. Templates specify how code can be generated. So when you make a
Stack<int> myStack;
The compiler uses the template to generate a copy constructor:
Stack<int>::Stack<int>( const Stack<int>& src);
This is a completely different type than a
Stack<float>
which will define a completely independent copy constructor, and completely independent set of methods.
One option many use is to include the cpp in the header, in a reverse kind-of-way.
ie in Stack.hpp, at the bottom
#include "Stack.cpp"
but that kind of hides the fact that really its all just plopped into one header.
|
966,605
| 966,793
|
Program Deployment Failing
|
The project my team has been working on has reached a point where we need to deploy it to computers without the development environment (Visual Studio 2005) installed on them. We fixed the dependency issues we had at first, but we're still having issues.
Now, once the installer is finished, our project gets stuck somewhere before entering WinMain. It only takes up 13MB of RAM, but takes up 50% of the cpu cycles.
Are there any suggestions as to how debug this problem?
Edit: Clarification - this is a C++ project.
|
Is it possible the hang occurs while some global variable is initialized? That happens before WinMain, and from a global variable's constructor any code could be run. Also, take a look at the busy thread's stack using Process Explorer (make sure you deploy the PBD in order to get a meaningful stack trace). The stack trace should make it obvious where is that thread hanging.
|
966,688
| 1,022,121
|
Show window in Qt without stealing focus
|
I'm using the Qt library to show a slideshow on the second monitor when the user isn't using the second monitor. An example is the user playing a game in the first monitor and showing the slideshow in the second monitor.
The problem is that when I open a new window in Qt, it automatically steals the focus from the previous application. Is there any way to prevent this from happening?
|
It took me a while to find it but I found it: setAttribute(Qt::WA_ShowWithoutActivating);
This forces the window not to activate. Even with the Qt::WindowStaysOnTopHint flag
|
966,757
| 966,768
|
Is there a way to "delete" a pure virtual function?
|
I have an abstract class with a couple pure virtual functions, and one of the classes I derive from it does not use one of the pure virtual functions:
class derivative: public base
{
public:
int somevariable;
void somefunction();
};
anyways, when I try to compile it, I get an error (apparently, a class is still considered abstract if derive from an abstract class and don't override all pure virtual functions). Anyways, it seems pointless to define a function
int purevirtfunc(){return 0;}
just because it needs to be defined through a technicality. Is there anyway to derive a class from an abstract class and not use one of the abstract class's pure virtual functions?
|
If your derived class doesn't "use" the base class pure virtual function, then either the derived class should not be derived from the base, or the PVF should not be there. In either case, your design is at fault and needs to be re-thought.
And no, there is no way of deleting a PVF.
|
966,905
| 966,924
|
Stuck on C++ template - deriving from std::map
|
I'm going to extend the existing std::map class and add a new function to it:
template<typename key_type, typename value_type>
class CleanableMap : public Cleanable, public std::map<key_type, value_type>
{
CleanableMap(const CleanableMap& in); //not implemented
CleanableMap& operator=(const CleanableMap& in); //not implemented
public:
CleanableMap() {}
CleanableMap(const std::map<key_type, value_type>& in) { *this = in; }
virtual ~CleanableMap() {}
std::map<key_type, value_type>& operator=(const std::map<key_type, value_type>& in)
{
*((std::map<key_type, value_type>*)this) = in;
return *this;
}
};
I've got a copy constructor and assignment operator such that I can simply assign an existing std::map of the same type to my new map:
CleanableMap<DWORD, DWORD> cm;
std::map<DWORD, DWORD> stdm;
cm = stdm;
The problem is, the compiler is complaining with an error that doesn't make sense -- I've explicitly coded for what it's complaining about:
1>c:\dev\proj\commonfunc.cpp(399) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::map<_Kty,_Ty>' (or there is no acceptable conversion)
1> with
1> [
1> _Kty=DWORD,
1> _Ty=DWORD
1> ]
1> c:\dev\proj\templates.h(245): could be 'CleanableMap<key_type,value_type> &CleanableMap<key_type,value_type>::operator =(const CleanableMap<key_type,value_type> &)'
1> with
1> [
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> c:\dev\proj\templates.h(250): or 'std::map<_Kty,_Ty> &CleanableMap<key_type,value_type>::operator =(const std::map<_Kty,_Ty> &)'
1> with
1> [
1> _Kty=unsigned long, <--- where did it come up with that?
1> _Ty=std::pair<const DWORD,DWORD>, <--- where did it come up with that?
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> while trying to match the argument list '(CleanableMap<key_type,value_type>, std::map<_Kty,_Ty>)'
1> with
1> [
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> and
1> [
1> _Kty=DWORD,
1> _Ty=DWORD
1> ]
There 'could be' it mentions on line 245 doesn't make sense -- there is no assignment operator like that (well, it's private. Removing it completely doesn't change anything).
The 'could be' it mentions on line 250 is the assignment operator that I defined, but it was somehow deduced some other non-matching template types. Where did it get those??
Help!!! :)
|
Adding onto Neil's answer.
One concrete reason you should not be deriving from std::map is that it does not have a virtual destructor. This means you simply cannot guarantee any resources you allocate as a part of your map will be freed during the destruction of your implementation via a std::map pointer.
std::map<int,int>* pMap = GetCleanableMap();
...
delete pMap; // does not call your destructor
|
966,960
| 966,986
|
What does -fPIC mean when building a shared library?
|
I know the '-fPIC' option has something to do with resolving addresses and independence between individual modules, but I'm not sure what it really means. Can you explain?
|
PIC stands for Position Independent Code.
To quote man gcc:
If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on AArch64, m68k, PowerPC and SPARC.
Use this when building shared objects (*.so) on those mentioned architectures.
|
967,141
| 967,627
|
Portable way to "fork()" in Qt4 application?
|
Say, I need to run a bunch of code that is prone to crash so I need to run it on a different process. Typically I'd do it like this:
pid = fork();
if (pid == -1) {
std::cout << "Cant Spawn New Thread";
exit(0);
} else if (pid == 0) {
std::cout << "Im a child that will crash\n";
char *foo = (char *) 0xffff;
std::cout << foo;
exit(0);
} else {
std::cout << "PID: " << pid << "\n";
}
do {
std::cout << "Waiting for " << pid << " to finish .. \n";
pid_w = waitpid(pid,&status,0);
} while (pid_w == -1);
Obviously I can just use fork in my Qt4 application but I'm wondering if can I archive same functionality with any anything that Qt4 provides or any portable manner without resorting to having bunch of architecture #ifdefs ?
In any case, I'm targeting this app to have only pthread implementation but I'd still like to keep things as much close to "native" Qt API as possible.
I've tested QThread, and segfaulting in thread crashes the whole application obviously and it seems that QProcess is only targetted to be used when spawning completely different executables. Any other alternatives ?
|
Windows flat-out doesn't have fork() in any publicly consumable way, so there's no Qt call to emulate it; you'll need to do something like start yourself with special command-line params or something.
|
967,219
| 1,796,379
|
Adding and removing items without invalidating iterators
|
I have an object that has a list of 'observers'. These observers get notified of things, and they might respond to this change by adding or removing themselves or other observers from the object.
I want a robust, and not unnecessarily slow, way to support this.
class Thing {
public:
class Observer {
public:
virtual void on_change(Thing* thing) = 0;
};
void add_observer(Observer* observer);
void remove_observer(Observer* observer);
void notify_observers();
private:
typedef std::vector<Observer*> Observers;
Observers observers;
};
void Thing::notify_observers() {
/* going backwards through a vector allows the current item to be removed in
the callback, but it can't cope with not-yet-called observers being removed */
for(int i=observers.size()-1; i>=0; i--)
observers[i]->on_change(this);
// OR is there another way using something more iterator-like?
for(Observers::iterator i=...;...;...) {
(*i)->on_change(this); //<-- what if the Observer implementation calls add_ or remove_ during its execution?
}
}
I could perhaps have a flag, set by add_ and remove_, to reset my iterator if it gets invalidated, and then perhaps a 'generation' counter in each observer so I know if I've already called it?
|
The sane way to manage this chaos is to have a flag so the remove code knows whether it's iterating the observers.
In the remove, if the code is in an iteration, then the pointer is set to null rather than removed. The flag is set to a third state to indicate that this has happened.
The observers must be iterated with [] operator in case an add is called during iteration, and the array is reallocated. Null values in the array are ignored.
After iteration, if the flag is set to indicate that observers were removed in the iteration, the array can be compacted.
|
967,352
| 967,363
|
Why can't I access a protected member from an instance of a derived class?
|
I haven't done C++ in a while and can't figure out why following doesn't work:
class A {
protected:
int num;
};
class B : public A {
};
main () {
B * bclass = new B ();
bclass->num = 1;
}
Compiling this produces:
error C2248: 'A::num' : cannot access protected member declared in class 'A'
Shouldn't protected members be accessible by derived classes?
What am I missing?
|
yes protected members are accessible by derived classes but you are accessing it in the main() function, which is outside the hierarchy. If you declare a method in the class B and access num it will be fine.
|
967,538
| 967,555
|
C++ Member Functions vs Free Functions
|
I keep on getting confused about this design decision a lot of the time when I'm writing programs, but I'm not 100% sure when I should make a function to be a member function of a class, when to leave it as a normal function in which other source files can call the function when the function declaration is exposed in a header file. Does the desired access to member variables of a class have to do with the decision most of the time?
|
The Interface Principle by Herb Sutter
For a class X, all functions, including free functions, that both
(a) "mention" X, and
(b) are "supplied with" X
are logically part of X, because they form part of the interface of X.
For in depth discussion read Namespaces and the Interface Principle by Herb Sutter.
EDIT
Actually, if you want to understand C++ go and read everything what Herb Sutter has written :)
|
967,930
| 967,947
|
Creating program libraries in Windows and LINUX [C++]
|
I am planning to use libraries in my C++ program. Development is happening on Linux but application is designed to compile on both Linux and Windows. I understand direct equivalent for shared libraries(.so) in windows is DLL, right?
In Linux using g++, I can create shared library using -fPIC and -shared flags. AFAIK, there is no other code change required for a shared library. But things are different in a Windows DLL. There I should specify the functions which have to be exported using dllexport, right?
My question is how do I manage this situation? I mean dllexport is invalid in Linux and the compiler will give an error. But it is required in Windows. So how do I write a function which will compile on both platforms without any code change?
Compilers used
g++ - LINUX
VC++ - Windows
Any help would be great!
|
We specify __declspec(dllexport) for class:
#define EXPORT_XX __declspec(dllexport)
class EXPORT_XX A
{
};
You can then check for platform and only define the macro on windows. E.g.:
#ifdef WIN32
#define EXPORT_XX __declspec(dllexport)
#else
#define EXPORT_XX
#endif
We mostly build static libraries so there might be more stuff to do for dynamic libs but the concept is the same - use preprocessor macro to define string that you need to insert into Windows code.
|
968,001
| 968,112
|
determine size of array if passed to function
|
Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } ..
I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the other function where the array is passed. I tried something like:
for( int i = 0; array[i] != NULL; i++) {
........
}
But I noticed that at the near end of the array, array[i] sometimes contain garbage values like 758433 which is not a value specified in the initialization of the array..
|
The other answers overlook one feature of c++. You can pass arrays by reference, and use templates:
template <typename T, int N>
void func(T (&a) [N]) {
for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements
}
then you can do this:
int x[10];
func(x);
but note, this only works for arrays, not pointers.
However, as other answers have noted, using std::vector is a better choice.
|
968,177
| 968,213
|
Sending string data between threads (Win32)
|
This is a fairly straightforward question, I'm basically looking for a 'best practice' approach to what I'm trying to do.
I have a Win32 GUI application which starts up a worker thread to do a bunch of blocking calls. I want this thread to send string messages back to the GUI so they can be displayed to the user.
Currently I'm thinking the use of SendMessage would be a good approach, using WM_COPYDATA? Is this on the right track? I did originally have a thread safe queue class which sent simple notification messages back to the GUI thread, which then popped the string off the queue. However I soon took a step back and realised I didn't need the queue; I could just send the string directly.
Any tips? Thanks!
Edit: And for completeness, I'm using C++.
|
WM_COPYDATA would work fine, but I think it's better to simply define your own private window message. Allocate the string on the worker thread and free it on the GUI thread when you're done. Use PostMessage instead of SendMessage so that you don't block your worker unnecessarily.
|
968,324
| 968,355
|
How to run regasm.exe from a C++ program?
|
I want to write a program which runs regasm.exe to create a tlb file programatically.
How can I do this??
Ur help is greatly appreciated...
Thanks in advance.
|
You have to use the CreateProcess() function to run the command line like "fullPathToRegasm /somekeys filename".
The main problem is to detect the regasm location - use GetCORSystemDirectory() function for that. First use first LoadLibrary() to load the mscoree.dll, then call GetProcAddress() to locate the GetCORSystemDirectory() function, then call the function.
This will get you the root of .NET installation. regasm is usually located in the same subpath of the installation root on any given machine so you can safely combine the detected root with the subpath and this will be a valid regasm location.
|
968,435
| 968,460
|
What could cause a deterministic process to generate floating point errors
|
Having already read this question I'm reasonably certain that a given process using floating point arithmatic with the same input (on the same hardware, compiled with the same compiler) should be deterministic. I'm looking at a case where this isn't true and trying to determine what could have caused this.
I've compiled an executable and I'm feeding it the exact same data, running on a single machine (non-multithreaded) but I'm getting errors of about 3.814697265625e-06 which after careful googling I found is actually equal to 1/4^9 = 1/2^18 = 1/262144. which is pretty close to the precision level of a 32-bit floating point number (approx 7 digits according to wikipedia)
My suspicion is that it has something to do with optimisations that have been applied to the code. I'm using the intel C++ compiler and have turned floating point speculation to fast instead of safe or strict. Could this make a floating point process non-deterministic? Are there other optimisations etc that could lead to this behaviour?
EDIT: As per Pax's suggestion I recompiled the code with floating point speculation turned to safe and I'm now getting stable results. This allows me to clarify this question - what does floating-point-speculation actually do and how can this cause the same binary (i.e. one compilation, multiple runs) to generate different results when applied to the exact same input?
@Ben I'm compiling using Intel(R) C++ 11.0.061 [IA-32] and I'm running on an Intel quadcore processor.
|
In almost any situation where there's a fast mode and a safe mode, you'll find a trade-off of some sort. Otherwise everything would run in fast-safe mode :-).
And, if you're getting different results with the same input, your process is not deterministic, no matter how much you believe it to be (in spite of the empirical evidence).
I would say your explanation is the most likely. Put it in safe mode and see if the non-determinism goes away. That will tell you for sure.
As to whether there are other optimizations, if you're compiling on the same hardware with the same compiler/linker and the same options to those tools, it should generate identical code. I can't see any other possibility other than the fast mode (or bit rot in the memory due to cosmic rays, but that's pretty unlikely).
Following your update:
Intel has a document here which explains some of the things they're not allowed to do in safe mode, including but not limited to:
reassociation: (a+b)+c -> a+(b+c).
zero folding: x + 0 -> x, x * 0 -> 0.
reciprocal multiply: a/b -> a*(1/b).
While you state that these operations are compile-time defined, the Intel chips are pretty darned clever. They can re-order instructions to keep pipelines full in multi-CPU set-ups so, unless the code specifically prohibits such behavior, things may change at run-time (not compile-time) to keep things going at full speed.
This is covered (briefly) on page 15 of that linked document that talks about vectorization ("Issue: different results re-running the same binary on the same data on the same processor").
My advice would be to decide whether you need raw grunt or total reproducability of results and then choose the mode based on that.
|
968,602
| 968,667
|
Error C2678 after migrating C++ code from VC6 to VS2008 - no operator found which takes a left-hand operand of type 'type'
|
This piece of code compiles file in VC6 but in VS 2008 it gives an error. Can anyone tell me why?
I guess it is because you can no longer compare a pointer to NULL (which is a typedef for 0).
If that is the case, how do I do this comparison in VC9?
for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin(); iT < attrLst.end(); iT++)
{
if ( (iT != NULL) && (*iT != NULL) ) //Error: C2678
{
//code
}
}
error C2678: binary '!=' : no operator
found which takes a left-hand operand
of type
'std::_Vector_iterator<_Ty,_Alloc>'
(or there is no acceptable conversion)
|
The type for 'std::vector::iterator' is not necessarily a pointer type so you can not compare it to NULL.
In your old compiler it just happened to be a pointer and so your code compiled. But you just got lucky (as shown when you moved the code to a different compiler).
The only test on iterator you have is to compare it to end() or begin() or any valid iterator within the range begin() -> end(). Since this is a vector you can do mathematical operations with the iterator. iT-begin() should give you an offset. But this is not valid for all containers (check each containers documentation).
All you need to do is test what the iterator points at:
for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin();
iT != attrLst.end(); // Changed this. Notice the !=
++iT) // Changed this. Prefer pre increment for not integer types
{
if ( *iT != NULL)
{
//code
}
}
|
968,621
| 975,949
|
Dynamic SQL vs Static SQL
|
In our current codebase we are using MFC db classes to connect to DB2. This is all old code that has been passed onto us by another development team, so we know some of the history but not all.
Most of the Code abstracts away the creation of SQL queries through functions such as Update() and Insert() that prepend something like "INSERT INTO SCHEMA.TABLE" onto a string that you supply. This is done through the recordset classes that sit on top of the database class
The other way to do the SQL queries is to execute them directly on the database class using dbclass.ExecuteSQL(String).
We are wondering what the pro's and cons of each approach is. From our perspective its much easier to do the ExecuteSQL() call, as we dont have to write another class etc, but there must be good reasons to do the other way. we are just not sure what they are.
Any help would be great!
Thanks Mark
Update----
I think I may have misunderstood Dynamic and Static SQL. I think our code always uses Dynamic, so my question really becomes, should I construct the SQL strings myself and do an ExecuteSQL() or should this be abstracted away in a class for each table in the database, as the recordset classes from mfc seem to do?
|
The ATL OLE DB consumer database classes are absolutely the way to go. Beyond the risks of injection (mentioned by Skurmedel), piles of string-concatenated queries will become impossible to maintain very quickly.
While the ATL classes can be initially tedious, they provide the benefit of strong-typed and named columns, result navigation, connection and session management, etc.
|
968,725
| 968,740
|
change variable name with a loop
|
Is there a way without using arrays to write the following with a loop:
cout<<"This variable c1 ="c1
cout<<"This variable c2 ="c2
cout<<"This variable c3 ="c3
for(i=1,i<8,i++)
cout<<"This variable c%d =",i<<**????**<<
This is obviously not what I Need to be done but is the easiest example I could think of with the same problem...
So what I would like to do is change the variables in the loop, not the output!
EDIT:
Thanks a lot for all the input,
here is a bit more of the code to help illustrate my problem...Im Using Cplex with c++.
The loop will not end at seven but when a stop criteria is met
static void populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
{
IloExpr c1(env);
IloExpr c2(env);
IloExpr c3(env);
IloExpr c4(env);
c.add(c1>=n);
c.add(c2>=n); ...
model.add(c);
}
I Want to add these expressions to an Array called c that will be an input for a model in cplex.
Then after I get a result from Cplex I want to add an expression c(i) and solve it again...
This until i get the values I want...
IloExprArray could also be used somehow, but then I dont know how to add the expressions using this method:
for(i= 0,...)
{
c7 +=x[i];
}
|
If I understand correctly, you are trying to create variable names dynamically. AFAIK this is not possible with C++.
|
968,945
| 969,005
|
Sending SMS with delivery message
|
How can i write code for send SMS with delivery message in Windows Mobile? please guide me with C# or C++ code.
I want to use SmsSendMessage API in this code because this API have more features.
|
You could use SmsSendMessage to send the message and use SmsGetMessageStatus to get the status report of the sent SMS. This is all C++ code, but you can pinvoke it as well.
|
969,232
| 969,374
|
Why does virtual assignment behave differently than other virtual functions of the same signature?
|
While playing with implementing a virtual assignment operator I have ended with a funny behavior. It is not a compiler glitch, since g++ 4.1, 4.3 and VS 2005 share the same behavior.
Basically, the virtual operator= behaves differently than any other virtual function with respect to the code that is actually being executed.
struct Base {
virtual Base& f( Base const & ) {
std::cout << "Base::f(Base const &)" << std::endl;
return *this;
}
virtual Base& operator=( Base const & ) {
std::cout << "Base::operator=(Base const &)" << std::endl;
return *this;
}
};
struct Derived : public Base {
virtual Base& f( Base const & ) {
std::cout << "Derived::f(Base const &)" << std::endl;
return *this;
}
virtual Base& operator=( Base const & ) {
std::cout << "Derived::operator=( Base const & )" << std::endl;
return *this;
}
};
int main() {
Derived a, b;
a.f( b ); // [0] outputs: Derived::f(Base const &) (expected result)
a = b; // [1] outputs: Base::operator=(Base const &)
Base & ba = a;
Base & bb = b;
ba = bb; // [2] outputs: Derived::operator=(Base const &)
Derived & da = a;
Derived & db = b;
da = db; // [3] outputs: Base::operator=(Base const &)
ba = da; // [4] outputs: Derived::operator=(Base const &)
da = ba; // [5] outputs: Derived::operator=(Base const &)
}
The effect is that the virtual operator= has a different behavior than any other virtual function with the same signature ([0] compared to [1]), by calling the Base version of the operator when called through real Derived objects ([1]) or Derived references ([3]) while it does perform as a regular virtual function when called through Base references ([2]), or when either the lvalue or rvalue are Base references and the other a Derived reference ([4],[5]).
Is there any sensible explanation to this odd behavior?
|
Here's how it goes:
If I change [1] to
a = *((Base*)&b);
then things work the way you expect. There's an automatically generated assignment operator in Derived that looks like this:
Derived& operator=(Derived const & that) {
Base::operator=(that);
// rewrite all Derived members by using their assignment operator, for example
foo = that.foo;
bar = that.bar;
return *this;
}
In your example compilers have enough info to guess that a and b are of type Derived and so they choose to use the automatically generated operator above that calls yours. That's how you got [1]. My pointer casting forces compilers to do it your way, because I tell compiler to "forget" that b is of type Derived and so it uses Base.
Other results can be explained the same way.
|
969,394
| 969,409
|
How to split long lines of code in c++?
|
I need to make sure none of the lines in my code exceeds a a certain length.
Normally I separate lines where there's a comma or another suitable break.
How can I separate this line into 2?
cout<<"Error:This is a really long error message that exceeds the maximum permitted length.\n";
If I just press enter somewhere in the middle it doesn't work.
|
Two options:
cout << "Error:This is a really long "
<< "error message that exceeds "
<< "the maximum permitted length.\n";
Or:
cout << "Error:This is a really long "
"error message that exceeds "
"the maximum permitted length.\n";
The second one is more efficient.
|
969,496
| 969,537
|
Access Iterator in BOOST_FOREACH loop
|
I have a BOOST_FOREACH loop to iterate over a list. Unfortunately, I also need to cache an iterator to a particular item.
typedef List::iterator savedIterator;
BOOST_FOREACH(Item &item, list)
{
// stuff...
if (condition)
savedIterator = &item; // this won't work
// do more stuff...
}
Obviously I can do this using a list.begin()..list.end() for loop, but I've grown to like BOOST_FOREACH. Is there a way round this?
|
This is not possible, as you do not have access to an iterator pointing to the current item inside the loop.
You could fetch an iterator from the list somehow using the current items data but I don't know if this is a good idea to follow, also performance-wise.
I'd suggest you use the solution you already proposed yourself with list.begin() .. list.end(), this is in my opinion the easiest to implement and recognize.
|
969,939
| 969,957
|
Force instantiation of objects with gcc
|
In the following code, gcc does not instantiate the NSP::Admin and NSP::Server objects.
It just skips them.
int main(int argc, char **argv)
{
// Here we bootstrap google logging
// we also install the signal handler
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
// now we parse the arguments with gflags
google::ParseCommandLineFlags(&argc, &argv, true);
NSP::Admin admin();
NSP::server server();
DLOG(INFO) << "boost io_service run";
NSP::IOService::getIOService().run();
}
If I add a parameter to the CTORS they are instantiated.
Example :
NSP::Admin admin(1);
NSP::server server(1);
I cannot break point on them with gdb, and stepping skips them.
These two objects register themselves with the boost io service and call a method in their CTORS.
NSP is the project namespace.
Using gcc4.2 on FreeBSD,
glog, gflags and boost asio.
|
It does not instantiate them because NSP::Admin admin(); does not create any objects.
Instead it is a declaration of a function prototype of a function which returns NSP::Admin object and takes void arguments. It is one of those wierd C++ syntaxes. The second one works because, compiler doesn't get 'confused' thinking that it is a function prototype. It can clearly see that you are creating an object.
To create an object using the default constructor use
NSP::Admin admin; // (without parenthesis)
NSP::server server;
|
969,974
| 970,127
|
Optional reference member - is it possible?
|
I have the following class
class CItem
{
public:
CItem(CRegistry &Registry) _Registry(Registry) {Registry.Register();}
~CItem() {_Registry.Unregister()};
private:
CRegistry &_Registry;
}
After a while it turns out that not all CItem objects need to be registered so I need a version of CItem which does not requires Registry in constructor (and of course of the registration code). How can I implement this?
The only solution I can see here is to get and keep Registry as a pointer. Is there more elegant solution, like using templates, etc (I don't like switching from reference to pointer)?
|
If you want to keep a single class, just change the attribute into a raw pointer and allow it to be null. As Neil points out, there is a widespread unjustified jihad against raw pointers that is not fully justified. Use a raw pointer and clearly document (comment) that the object holds no ownership of the pointed memory so that no one feels like adding a delete in your destructor at a later time.
All other solutions will be worse than using a pointer internally. It is an implementation detail. Also consider whether it makes sense. Your code will no longer be able to assume that the pointer is valid and it will complicate the logic inside your class.
class CItem
{
public:
CItem(CRegistry &Registry) : _Registry(&Registry) {Registry->Register();}
CItem() : _Registry(0) {}
~CItem() { if ( _Registry ) _Registry->Unregister(); }
private:
CRegistry *_Registry; // Pointer is not owned. Do not delete!
};
As a last note: do not prefix attributes with a single underscore as they are reserved by the standard for C++ implementations (compiler and standard libraries)
|
970,306
| 970,379
|
How come the WaitForDeath() can kill the thread in the sample?
|
class Thread
{
public:
Thread ( DWORD (WINAPI * pFun) (void* arg), void* pArg)
{
_handle = CreateThread (
0, // Security attributes
0, // Stack size
pFun,
pArg,
CREATE_SUSPENDED,
&_tid);
}
~Thread () { CloseHandle (_handle); }
void Resume () { ResumeThread (_handle); }
void WaitForDeath ()
{
WaitForSingleObject (_handle, 2000);
}
private:
HANDLE _handle;
DWORD _tid; // thread id
};
How come the WaitForDeath() can kill the thread?
|
The thread is not killed, it just dies by itself when the function passed as a parameter exits.
WaitForSingleObject waits for that termination.
|
970,382
| 970,496
|
"Cannot convert parameter" using boost::variant iterator
|
I want to create a function that can take different types of iterators which store the same type of object:
The first is a std::map containing shared_ptr<Foo> (typedef-ed as FooMap) and the other is a std::list which also contains shared_ptr<Foo> (FooList).
I really like the solution MSalters suggested for a similar question and tried to implement boost::variant iterators, which the function will get as parameters to iterate from the first to the second.
My function looks like this (simplified quite a bit):
set<Foo> CMyClass::GetUniqueFoos(FooIterator itBegin, FooIterator itEnd)
{
set<Foo> uniques;
for(/**/;
apply_visitor(do_compare(), itBegin, itEnd); // equals "itBegin != itEnd"
apply_visitor(do_increment(), itBegin)) // equals "++itBegin"
{
// Exact mechanism for determining if unique is omitted for clarity
uniques.insert( do_dereference< shared_ptr<Foo> >(), itBegin) );
}
return uniques;
}
The FooIterator and the visitors are defined as follows:
typedef
boost::variant<
FooMap::const_iterator,
FooList::const_iterator>
FooIterator;
struct do_compare : boost::static_visitor<bool>
{
bool operator() (
const FooMap::const_iterator & a,
const FooMap::const_iterator & b) const
{ return a != b; }
bool operator() (
const FooList::const_iterator & a,
const FooList::const_iterator & b) const
{ return a != b; }
};
struct do_increment: boost::static_visitor<void>
{
template<typename T>
void operator()( T& t ) const
{ ++t; }
};
template< typename Reference >
struct do_dereference: boost::static_visitor<Reference>
{
template<typename T>
Reference operator()( const T& t ) const
{ return *t; }
};
I got most of the above from the attachment of this mail. That solution also uses adaptors and policies, which seems to be a little too much, according to the answer of MSalters, so I don't want to simply copy that code. Especially as I only understand part of it.
With the above code I get the following compiler error from VS2008 (this is only the first few lines of 160 in total, which I think is a bit too much to post here; however I'll be happy to add them If somebody wants to see it all):
1>c:\boost\boost\variant\detail\apply_visitor_binary.hpp(63) :
error C2664: 'bool CMyClass::do_compare::operator ()(
const std::list<_Ty>::_Const_iterator<_Secure_validation> &,
const std::list<_Ty>::_Const_iterator<_Secure_validation> &) const' :
cannot convert parameter 1 from 'T0' to
'const std::list<_Ty>::_Const_iterator<_Secure_validation> &'
1> with
1> [
1> _Ty=shared_ptr<Foo>,
1> _Secure_validation=true
1> ]
1> Reason: cannot convert from 'T0' to 'const std::list<_Ty>::_Const_iterator<_Secure_validation>'
1> with
1> [
1> _Ty=shared_ptr<Foo>,
1> _Secure_validation=true
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1> c:\boost\boost\variant\variant.hpp(806) : see reference to function template instantiation 'bool boost::detail::variant::apply_visitor_binary_invoke<Visitor,Value1>::operator ()<T>(Value2 &)' being compiled
1> with
1> [
1> Visitor=const CMyClass::do_compare,
1> Value1=T0,
1> T=T1,
1> Value2=T1
1> ]
[...]
What am I doing wrong?
|
I suspect you are missing cases on your do_compare static_visitor. Remeber, the variants might have anything, so you need all possible combinations, like comparing a FooList::const_iterator to a FooMap::const_iterator. It's complaining because the compiler is trying to find some match for that case, and can't convert a FooMap::const_iterator to a FooList::const_iterator.
Hammering it out:
struct do_compare : boost::static_visitor<bool>
{
bool operator() (
const FooMap::const_iterator & a,
const FooMap::const_iterator & b) const
{ return a != b; }
bool operator() (
const FooList::const_iterator & a,
const FooList::const_iterator & b) const
{ return a != b; }
bool operator() (
const FooMap::const_iterator & a,
const FooList::const_iterator & b) const
{ return false; }
bool operator() (
const FooList::const_iterator & a,
const FooMap::const_iterator & b) const
{ return false; }
};
Here's a version with templates:
template <typename A, typename B>
bool operator() (
const A & a,
const B & b) const
{ return false; }
template <typename A>
bool operator() (
const A & a,
const A & b) const
{ return a != b; }
It's compiling on comeau, but I'm not 100% it will work, so some testing is required. Other than cleaner, more versatile code, it shouldn't have any effect, as long as it works.
|
970,472
| 970,509
|
Extracted Interface naming conventions
|
I'm currently refactoring some code to make it more testable.
Specifically, I am extracting the interface of several classes to allow easy creation of test doubles.
I'd like to keep the public interface the same to this code, naming the interface after the original class.
However this leaves me with the problem of what to call the original class.
I'm using C++.
If my interface is:
class ServiceClient;
What should I call the contrete, I've come up with a few options that I'm not convinced by:
class ConcreteServiceClient;
class ServiceClientImpl;
class StandardServiceClient;
class BasicServiceClient;
What conventions do people use?
|
I would change the name of the interface class.
class ServiceClientInterface {};
Then place the concrete implementations in seprate namespaces:
namespace MyService
{
class Client: public ServiceClientInterface {};
}
namespace MyServiceTest
{
class TestClient: public ServiceClientInterface {};
}
Or something completely different.
PS. I am into full names. I don;t like the the short 'I' is interface thing. Your taste may vary.
|
970,498
| 970,576
|
Instantiate a new STL vector
|
I have a situation where I have a pointer to an STL vector.
So like
vector<MyType*>* myvector;
I have to set this pointer to NULL in the constructor and then lazy load when the property is touched.
How can I instantiate this to a new instance of a vector?
|
I have to set this pointer to NULL in the constructor and then lazy load when property is touched.
How can I instantiate this to a new instance of a vector?
I'm not sure I understand you all the way. Why not simply leave the vector empty, and set a Boolean that says whether the property was loaded or not? Alternatively, you can use boost::optional:
boost::optional< vector<MyType*> >
Or
boost::optional< vector< shared_ptr<MyType> > >
You can then simply receive the object by dereferencing the optional object, and assign a vector to it like usual.
I would not use a pointer for this. It complicates the matter, and you have to think about what happens when you copy the object containing the property, ...
If you really have to use a pointer, you can do it like this:
struct A {
A():prop() { }
~A() { delete prop; }
vector< MyType *>& get() {
if(!prop) prop = new vector< MyType* >();
return prop;
}
private:
// disable copy and assignment.
A(A const&);
A& operator=(A const&);
vector< MyType* > *prop;
};
Or use shared_ptr, which would be the way to go in my program (but boost::optional would still be first option, after which would be the vector-and-Boolean option, after which would be the following)
struct A {
typedef vector< shared_ptr<MyType> > vector_type;
vector_type &get() {
if(!prop) {
prop.reset(new vector_type);
}
return *prop;
}
private:
// disable copy and assignment.
A(A const&);
A& operator=(A const&);
shared_ptr< vector_type > prop;
};
Copy and assignment are disabled, as they would share the property behind the scene (shallow copy), which should be either clearly documented or disabled by deep copying in these functions.
|
970,753
| 970,789
|
Passing data from C++ to PHP
|
I need to pass a value from PHP to C++. I think I can do with PHP's passthru() function.
Then I want C++ to do something to that value and return the result to PHP.
This is the bit I can't work out, does anyone know how to pass data from C++ to PHP?
I'd rather not use an intermediate file as I am thinking this will slow things down.
|
You could have your c++ app send its output to stdout, then call it from PHP with backticks, e.g.
$output=`myapp $myinputparams`;
|
971,409
| 971,455
|
Unit testing , approval testing and datafiles
|
(Leaving aside hair-splitting about if this is integration-testing or unit-testing.)
I would rather first test at the large scale. If my app writes a VRML file that is the same as the reference one then the VRML exporter works, I don't then have to run unit tests on every single statement in the code. I would also like to use this do some level of poor-man gui testing by comparing screenshots.
Is there a unit test framework (for C++ ideally) that integrates this sort of testing - or at least makes it easy to integrate with unit tests?
edit. It seems a better term is approval testing. So are there any other unit test frameworks that incorporate Approval Testing ?
|
Have a look at Approval Tests, written by a couple of friends of mine. Not C++, but it's the general idea of what you're after, also known as Golden Master tests. Good stuff, whether it's unit tests or not.
|
971,478
| 971,515
|
C++ SQL database library comparison
|
I am starting development on a medium-scale C++ project that has to work with a Microsoft SQL Server database. I have done database work before using .NET technologies but I don't find using a .NET approach to be appropriate this time. I would like to get some feedback concerning the various free (as in GPL, LGPL, Boost) C/C++ SQL libraries available. I found MySQL++ and SOCI to be pretty interesting and I would like to know which one you guys prefer and why.
Also, although this project will primarily be run on Windows workstations, I prefer developing under Linux so cross-platform compatibility is an advantage.
Thank you all for your time, I really appreciate your advices !
Jeremie
EDIT : Sorry about the typo, I meant Microsoft SQL Server and not MySQL Server.
|
I can highly recommend OTL.
Not only does it support all major DBs, it's also very STL-ish and is generally written according to to proper C++ methodology (IMO). It worked for me just fine on VC8 (I used the MySQL ODBC connector).
Moreover, it's a one-header library. So there's no linkage issues or anything. Just include the header and you're done. You're 3 lines of code away from querying a MySQL table.
I've used it over the past few months, and also had a good experience communicating with its developer, asking questions, etc.
|
971,528
| 1,012,124
|
FileSystemWatcher does not fire when using C++ std::ofstream
|
I'm trying to add a log monitor to an in-house test utility for a windows service I'm working on. The service is written in C++ (win32) and the utility is in .NET (C#)
The log monitor works for many other C++ apps I've written, but not for my service.
The only main difference I can see is that the other apps use the older ::WriteFile() to output to the log, whereas in the service I'm using std::ofstream like this:
std::ofstream logFile;
logFile.open("C:\\mylog.log");
logFile << "Hello World!" << std::endl;
logFile.flush();
From my utility I use FileSystemWatcher like this:
FileSystemWatcher fsw = new FileSystemWatcher(@"C:\", "mylog.log");
fsw.Changed += new FileSystemEventHandler(fsw_Handler);
fsw.EnableRaisingEvents = true;
But for the service, it never gets any change events as the log is updated. I've found that any example code using FileSystemWatcher I've come across online has the same exact issue as well...
But, I know the events should be available because other log monitor apps (like BareTail) work fine with the service log file.
I'd rather get the C# code for the utility to just work so it works with anything, but if I have to change the logging code for the service I will. Does anyone see what's going wrong here?
|
I really wanted to be able to pick one of the previous answers as "the answer", but all of them contributed to me being able to figure out the final solution.
After a great deal of trial and error with each solution, I found that I could get it to work (without modifying the C++ logging code) by setting NotifyFilter to:
NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.CreationTime;
I had kind of assumed that by default it would've searched for everything by default, but obviously not. In general, I think the filter that helped it the most was "Size". LastAccess worked better, but it didn't always pick up every change... it kind of depended on when the watcher was launch. But Size got it to see all changes.
Thanks for all your help everyone! Since I couldn't pick just one answer I tried to be fair and made sure to up-vote each one of your answers.
|
971,645
| 971,760
|
What are my options for C++ DLL to call a C# DLL?
|
I have a C++ DLL that needs to call a function (pass a value, return a value) in a C# class library.
Is my only option to give the C# DLL a COM interface and call it from C++ with IDispatch?
Is this the best method?
|
Couple of options available for you here
Use a mixed mode C++/CLI assembly as a bridge between the C++ and C# DLL
Use the a COM bridge by exposing several of the key C# types as COM objects. This can then be accessed via the C++ code by normal COM semantics
|
971,668
| 972,315
|
Pointer-to-Exception Clean-Up
|
We all know that throwing pointers to exception is bad:
try
{
...
throw new MyExceptionClass();
}
catch (MyExceptionClass* e)
{
...
}
What's your approach to cleaning the catch targets up in legacy code? I figure that I can fix the first part by making operator new private:
class MyExceptionClass
{
public:
...
private:
void* operator new(size_t);
}
How can I make the catch side of things equally ugly at compile-time? I don't want to just cause this to fall into the catch (...) territory.
|
If I understand you correctly, you want to turn a bad practice into a compilation error.
By making the exception type non-heap-allocatable, you've managed to make this illegal:
throw new MyExceptionClass();
Alas, the next part can't be done like you want it. There's no way to make the catch block illegal. Although, if you've made it illegal to heap-allocate MyExceptionClass, there's no need to worry about the catch blocks. It'll just be wasted space.
If you want to enforce not catching by a pointer, you want a lint-like tool.
I'd recommend looking at EDoC++. It's a modified gcc compiler to check for proper exception usage.
|
971,726
| 972,908
|
Can the signal system call be used with C++ static members of the class?
|
Is the following supported across *nix platforms?
#include <cstdio>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
class SignalProcessor
{
public:
static void OnMySignal(int sig_num)
{
printf("Caught %d signal\n", sig_num);
fflush(stdout);
return;
}
};
using namespace std;
int main()
{
signal(SIGINT,SingalProcessor::OnMySignal);
printf("Ouch\n");
pause();
return 0;
}
|
Technically no you can't.
You just happen to be getting lucky that your compiler is using the same calling convention that it uses for 'C' functions. As the C++ ABI is not defined the next version of the compiler is free to use a completely different calling convention and this will mess with your code with no warning from the compiler.
See: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2
See the note at the end of this section
Note: static member functions do not require an actual object to be invoked,
so pointers-to-static-member-functions are usually type-compatible with regular
pointers-to-functions. However, although it probably works on most compilers,
it actually would have to be an extern "C" non-member function to be correct,
since "C linkage" doesn't only cover things like name mangling, but also
calling conventions, which might be different between C and C++.
Edit:
To answer the comment by Sasha:
Using threading as an example:
#include <iostream>
class Thread
{ public: virtual void run() = 0; };
extern "C" void* startThrerad(void* data)
{
Thread* thread = reinterpret_cast<Thread*>(data);
try
{
thread->run();
}
catch(...)
{ /* Log if required. Don't let thread exit with exception. */ }
return NULL;
}
class MyJob: public Thread
{
public: virtual void run() {std::cout << "HI\n";}
};
int main()
{
MyJob job; // MyJob inherits from Thread
pthread_t th;
// In most situation you do not need to dynamic cast.
// But if you use multiple inheritance then things may get
// interesting, as such best to always use it.
pthread_create(&th,NULL,startThrerad,dynamic_cast<Thread*>(&job));
void* result;
pthread_join(th,&result);
}
|
971,804
| 971,821
|
create a control programmatically using MFC
|
I just wonder how to do it.
I write :
CEdit m_wndEdit;
and in the button event handler (dialog app),
I write :
m_wndEdit.Create(//with params);
but I still don't see the control appear in the UI.
I actually wrote this in the button handler :
CWnd* pWnd = GetDlgItem(IDC_LIST1);
CRect rect;
pWnd->GetClientRect(&rect);
//pWnd->CalcWindowRect(rect,CWnd::adjustBorder);
wnd_Edit.Create(ES_MULTILINE | ES_NOHIDESEL | ES_READONLY,rect,this,105);
wnd_Edit.ShowWindow(SW_SHOW);
this->Invalidate();
id 105 doesn't exist. (I used it in the Create member function of CEdit). I just put it in there. isn't it supposed to be the id you want to give to the new control ? Should it already exist ?
|
Check with the following set of flags as the example mentioned in MSDN:
pEdit->Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER | ES_NOHIDESEL | ES_READONLY,
rect, this, 105);
|
971,809
| 971,829
|
Trouble using ReadFile() to read a string from a text file
|
How can I make the code below to read correct text. In my text file has Hello welcome to C++, however at the end of the text, it has a new line. With the code below, my readBuffer always contains extra characters.
DWORD byteWritten;
int fileSize = 0;
//Use CreateFile to check if the file exists or not.
HANDLE hFile = CreateFile(myFile, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile != INVALID_HANDLE_VALUE)
{
BOOL readSuccess;
DWORD byteReading;
char readBuffer[256];
readSuccess = ReadFile(hFile, readBuffer, byteReading, &byteReading, NULL);
if(readSuccess == TRUE)
{
TCHAR myBuffer[256];
mbstowcs(myBuffer, readBuffer, 256);
if(_tcscmp(myBuffer, TEXT("Hello welcome to C++")) == 0)
{
FindClose(hFile);
CloseHandle(hFile);
WriteResultFile(TRUE, TEXT("success!"));
}
}
}
Thanks,
|
Either remove the new line character from the file or use _tcsstr for checking the existence of the string "Hello Welcome to C++".
|
972,128
| 972,145
|
Refactoring build system to use Autotools
|
Over the past couple of days I have been reading into using autotools to build my project instead of the Makefiles I have pieced together over the past couple of months. Unfortunately I have not found an example that gave me enough insight towards how my project structure is currently.
I have three libraries that are included in the application code of my project. I am looking for the best way to use a single configure script to make (and install) the application, and libraries.
|
Here are a few I found that don't look to bad:
http://www.lrde.epita.fr/~adl/autotools.html
http://www.developingprogrammers.com/index.php/2006/01/05/autotools-tutorial/
http://sources.redhat.com/autobook/
The last one is a free book
Good Luck
|
972,152
| 972,197
|
How to create a template function within a class? (C++)
|
I know it's possible to make a template function:
template<typename T>
void DoSomeThing(T x){}
and it's possible to make a template class:
template<typename T>
class Object
{
public:
int x;
};
but is it possible to make a class not within a template, and then make a function in that class a template? Ie:
//I have no idea if this is right, this is just how I think it would look
class Object
{
public:
template<class T>
void DoX(){}
};
or something to the extent, where the class is not part of a template, but the function is?
|
Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.
|
972,206
| 972,269
|
Corba request timeout
|
I am working on a Corba client for some time. One problem that I run in is that I am not really able to define a timeout configuration.
I am using a Mico C++ orb but it seems to be a global problem because I found noone who could describe if there is a Corba defined method to configure a request timeout.
Does anyone know of such an interface or orb initialization?
|
The Messaging section of the CORBA spec defines RelativeRequestTimeoutPolicy and RelativeRoundtripTimeoutPolicy for that. You may look at the section named "Programming client timeouts" in http://www.cs.wustl.edu/~schmidt/PDF/C++-report-col19.pdf for more information.
I don't have experience with MICO, but it seems that it is supported since version 2.3.13
|
972,511
| 972,529
|
View array in Visual Studio debugger?
|
Is it possible to view an array in the Visual Studio debugger? QuickWatch only shows the first element of the array.
|
You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.
For example if pArray is the array, type pArray,10 in the watch window.
|
972,705
| 972,738
|
Is there a way to initialize an array with non-constant variables? (C++)
|
I am trying to create a class as such:
class CLASS
{
public:
//stuff
private:
int x, y;
char array[x][y];
};
Of course, it doesn't work until I change int x, y; to
const static int x = 10, y = 10;
Which is impractical, because I am trying to read the values of x and y from a file. So is there any way to initialize an array with non-contant values, or declare an array and declare its size on different statements? And I know this would probably require the creation of an array class, but I'm not sure where to start on this, and I don't want to create a 2D dynamic list when the array itself is not dynamic, just the size is not known at compile-time.
|
The compiler need to have the exact size of the class when compiling, you will have to use the new operator to dynamically allocate memory.
Switch char array[x][y]; to char** array; and initialize your array in the constructor, and don't forget to delete your array in the destructor.
class MyClass
{
public:
MyClass() {
x = 10; //read from file
y = 10; //read from file
allocate(x, y);
}
MyClass( const MyClass& otherClass ) {
x = otherClass.x;
y = otherClass.y;
allocate(x, y);
// This can be replace by a memcopy
for( int i=0 ; i<x ; ++i )
for( int j=0 ; j<x ; ++j )
array[i][j] = otherClass.array[i][j];
}
~MyClass(){
deleteMe();
}
void allocate( int x, int y){
array = new char*[x];
for( int i = 0; i < y; i++ )
array[i] = new char[y];
}
void deleteMe(){
for (int i = 0; i < y; i++)
delete[] array[i];
delete[] array;
}
MyClass& operator= (const MyClass& otherClass)
{
if( this != &otherClass )
{
deleteMe();
x = otherClass.x;
y = otherClass.y;
allocate(x, y);
for( int i=0 ; i<x ; ++i )
for( int j=0 ; j<y ; ++j )
array[i][j] = otherClass.array[i][j];
}
return *this;
}
private:
int x, y;
char** array;
};
*EDIT:
I've had the copy constructor
and the assignment operator
|
972,865
| 4,173,606
|
Code metrics and warnings for C++
|
I have a pretty new code base written in C++. Already I'm starting to see some bad practices creeping into the project (class file with 1000+ lines of code, functions with a lot of parameters, ...).
I would like to stop on these right away with some automated tools which can hook into the build and check for poor coding practices. What suggestions do you have for such tools? I'm interested in metrics but really more interested in a stylistic sort of lint which would highlight functions with 37 parameters.
|
As with the others I'm not sure of a tool that will judge style. But CCCC will produce numerous metrics that can help you find the trouble spots. Metrics like cyclomatic complexity will give you quantitative evidence where the problem spots are. The downside is that you will have to incorporate these metrics with a style guide that you adopt or create on your own.
|
972,927
| 972,971
|
How to check the status of mail server (SSL, SMTP port 465) in C++
|
Ping is not working. Telnet is not an option, sending a mail also. Preferably a function from a library that returns true or false.
Thanks.
|
If by working you mean open, you can just connect to the port and see if the socket opens successfully.
If you mean that it's accepting valid SMTP over SSL, then you'd need a library that connects and issues a trivial SMTP command like HELO or something.
Chilkat has library code and examples for this.
Example connect code for win32:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>
void tryconnect(const char * host, const char * port)
{
SOCKET Socket = INVALID_SOCKET;
struct addrinfo *resAddrInfo = NULL;
struct addrinfo *ptr = NULL;
struct addrinfo hints;
int result = 0;
printf("Connecting to %s:%s\n", host, port);
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
result = getaddrinfo(host, port, &hints, &resAddrInfo);
if (result != 0)
{
printError("getaddrinfo failed");
return;
}
ptr = resAddrInfo;
Socket = WSASocket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol, NULL, 0, WSA_FLAG_OVERLAPPED);
if (Socket == INVALID_SOCKET)
{
printError("Error Creating Socket");
freeaddrinfo(resAddrInfo);
return;
}
result = WSAConnect(Socket, ptr->ai_addr, (int)ptr->ai_addrlen, NULL, NULL, NULL, NULL);
if (result != 0)
{
printError("Error Connecting");
closesocket(Socket);
freeaddrinfo(resAddrInfo);
return;
}
freeaddrinfo(resAddrInfo);
printf("Success!\n\n");
}
|
973,000
| 973,007
|
What patterns do you use to decouple interfaces and implementation in C++?
|
One problem in large C++ projects can be build times. There is some class high up in your dependency tree which you would need to work on, but usually you avoid doing so because every build takes a very long time. You don't necessarily want to change its public interface, but maybe you want to change its private members (add a cache-variable, extract a private method, ...). The problem you are facing is that in C++, even private members are declared in the public header file, so your build system needs to recompile everything.
What do you do in this situation?
I have sketched two solutions which I know of, but they both have their downsides, and maybe there is a better one I have not yet thought of.
|
The pimpl pattern:
In your header file, only declare the public methods and a private pointer (the pimpl-pointer or delegate) to a forward declared implementation class.
In your source, declare the implementation class, forward every public method of your public class to the delegate, and construct an instance of your pimpl class in every constructor of your public class.
Plus:
Allows you to change the implementation of your class without having to recompile everything.
Inheritance works well, only the syntax becomes a little different.
Minus:
Lots and lots of stupid method bodies to write to do the delegation.
Kind of awkward to debug since you have tons of delegates to step through.
An extra pointer in your base class, which might be an issue if you have lots of small objects.
|
973,146
| 973,158
|
How to include header files in GCC search path?
|
I have the following code in a sample file:
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGLCanvas.h"
#include "SkGraphics.h"
#include "SkImageEncoder.h"
#include "SkPaint.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkWindow.h"
However, this code is located in various folders within /home/me/development/skia (which includes core/ animator/ images/ ports/ svg/ and a lot more.)
How can I make GCC recognize this path?
|
Try gcc -c -I/home/me/development/skia sample.c.
|
973,439
| 973,447
|
How to set the don't fragment (DF) flag on a socket?
|
I am trying to set the DF (don't fragment flag) for sending packets using UDP.
Looking at the Richard Steven's book Volume 1 Unix Network Programming; The Sockets Networking API, I am unable to find how to set this.
I suspect that I would do it with setsockopt() but can't find it in the table on page 193.
Please suggest how this is done.
|
You do it with the setsockopt() call, by using the IP_DONTFRAG option:
int val = 1;
setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val));
Here's a page explaining this in further detail.
For Linux, it appears you have to use the IP_MTU_DISCOVER option with the value IP_PMTUDISC_DO (or IP_PMTUDISC_DONT to turn it off):
int val = IP_PMTUDISC_DO;
setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
I haven't tested this, just looked in the header files and a bit of a web search so you'll need to test it.
As to whether there's another way the DF flag could be set:
I find nowhere in my program where the "force DF flag" is set, yet tcpdump suggests it is. Is there any other way this could get set?
From this excellent page here:
IP_MTU_DISCOVER: Sets or receives the Path MTU Discovery setting for a socket. When enabled, Linux will perform Path MTU Discovery as defined in RFC 1191 on this socket. The don't fragment flag is set on all outgoing datagrams. The system-wide default is controlled by the ip_no_pmtu_disc sysctl for SOCK_STREAM sockets, and disabled on all others. For non SOCK_STREAM sockets it is the user's responsibility to packetize the data in MTU sized chunks and to do the retransmits if necessary. The kernel will reject packets that are bigger than the known path MTU if this flag is set (with EMSGSIZE).
This looks to me like you can set the system-wide default using sysctl:
sysctl ip_no_pmtu_disc
returns "error: "ip_no_pmtu_disc" is an unknown key" on my system but it may be set on yours. Other than that, I'm not aware of anything else (other than setsockopt() as previously mentioned) that can affect the setting.
|
973,939
| 973,955
|
How to run regasm.exe from command line other than Visual Studio command prompt?
|
I want to run regasm.exe from cmd. which is available in c:\windows\Microsoft.net\framework\2.057
I do like this c:\ regasm.exe
It gives regasm is not recognized as internal or external command.
So I understood that I need to set the path for regasm.exe in environment variable.
For which variable do I need to set the path to run regasm as described above?
|
In command prompt:
SET PATH = "%PATH%;%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
|
973,983
| 974,028
|
error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'type *'
|
I am getting the following error while migrating VC6 code to VS2008. This code works fine in VC6 but gives a compilation error in VC9. I know it is because of a compiler breaking change. What is the problem and how do I fix it?
error C2440: 'initializing' : cannot convert
from 'std::_Vector_iterator<_Ty,_Alloc>'
to 'STRUCT_MUX_NOTIFICATION *'
Code
MUX_NOTIFICATION_VECTOR::iterator MuxNotfnIterator;
for(
MuxNotfnIterator = m_MuxNotfnCache.m_MuxNotificationVector.begin();
MuxNotfnIterator != m_MuxNotfnCache.m_MuxNotificationVector.end();
MuxNotfnIterator ++
)
{
STRUCT_MUX_NOTIFICATION *pstMuxNotfn = MuxNotfnIterator; //Error 2440
}
|
If it worked before, I am guessing MUX_NOTIFICATION_VECTOR is a typedef
typedef std::vector<STRUCT_MUX_NOTIFICATION> MUX_NOTIFICATION_VECTOR;
The iterator for a container can often be mistaken with a pointer (because it works the same way) and, in the case of some stl implementations, it can actually be a pointer (it probably was the case with STL provided with VC6). But there is no guarantee about that.
What you should do is the following :
STRUCT_MUX_NOTIFICATION& reference = *MuxNotfnIterator;
// or
STRUCT_MUX_NOTIFICATION* pointer = &(*MuxNotfnIterator);
|
974,250
| 994,255
|
Windows Mobile/Pocket PC: How do I change the border color of focused/unfocused CEdit, CListCntl, CButton in MFC or Win32
|
How do I change the border color of focused/unfocused CEdit, CListCntl, CButton in WinCE/Windows Mobile 5/6 with MFC or Win32 API?
|
There's this trick I found here to draw a borderless control and then draw the border from its parent. or make a static control slightly bigger than the control just to draw the border.
Is there any better Idea? such as making use of Window Clipping Region or something?
update:
Here is a discussion with an MSFT on the topic
|
974,454
| 974,468
|
Game Programming as Hobby, should I use Java or C++
|
Presently, i am learning Java from the book The Art and Science of Java and following Standford's Programming Methodology Course.
I would like to do game programming, but only as a hobby.
I was thinking, would Java be a good choice or is C++ the defacto in game programming.
|
Since you are learning Java i would recommend that you stick to it.
If you are only developing games for fun, it won't really matter what language you use.
|
974,512
| 974,602
|
Ignoring source code in the debugger
|
How can I get the Visual Studio debugger to ignore certain source files? In other words, I would like it to behave as if the functions defined in those files had no debugging info, so that:
When stepping into code, it will ignore functions defined in those files (a smart pointer operator-> is an example where this is useful)
If the debugger stops due to an exception or _asm int 3 in one of these files, it shows a function further up the callstack instead (handy for assert code)
VC6 had a (undocumented?) feature along these lines, if my long term memory isn't playing tricks on me.
I'm using Visual Studio 2005, but the answer for each version of Visual Studio, if different, would be useful.
|
Here's a tutorial / explanation from an msdn blog.
|
974,815
| 974,846
|
How to save c++ object into a xml file and restore back?
|
How to save c++ object into a xml file and restore back?
|
Boost.Serialization and libs11n can both do this. The libs11n manual (available here) has an extensive comparison of the two.
As Tobias said, the C++ FAQ has good background information.
|
974,964
| 975,011
|
best practice when returning smart pointers
|
What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code):
class X
{
public:
boost::shared_ptr<Y> getInternal() {return m_internal;}
private:
boost::shared_ptr<Y> m_internal;
}
However I've seen some experienced coders returning the raw pointer, and putting the raw pointers in vectors. What is the right way to do it?
|
There is no "right" way. It really depends on the context.
You can internally handle memory with a smart pointer and externally give references or raw pointers. After all, the user of your interface doesn't need to know how you manage memory internally. In a synchronous context this is safe and efficient. In an asynchronous context, there are many pitfalls.
If you're unsure about what to do you can safely return smart pointers to your caller. The object will be deallocated when the references count reaches zero. Just make sure that you don't have a class that keeps smart pointers of objects for ever thus preventing the deallocation when needed.
As a last note, in C++ don't overuse dynamically allocated objects. There are many cases where you don't need a pointer and can work on references and const references. That's safer and reduces the pressure on the memory allocator.
|
975,028
| 975,045
|
Converting argv back to a single string
|
I'm writing a (Win32 Console) program that wraps another process; it takes parameters as in the following example:
runas.exe user notepad foo.txt
That is: runas parses user and then will run notepad, passing the remaining parameters.
My problem is that argv is broken down into individual parameters, but CreateProcessAsUser requires a single lpszCommandLine parameter.
Building this command line is probably not as simple as just joining argv back together with spaces. Any pointers?
This is just an example. My first argument isn't actually a user name, and might have spaces in it. This makes manually parsing the result of GetCommandLine tricky.
Similarly, a naive concatenation of argv won't work, because it needs to deal with the case where the original arguments were quoted and might have spaces in them.
|
Manually recombining them is hard:
You could try to re-combine them, I think it would work, but be sure to following the same command line escaping rules that windows has. This could be more than the trivial solution you're looking for.
Also if there are any parameters that have spaces in them, then you would want to join them to the string with quotes around them. Here is an example of a strange escaping rule: if you have --folderpath "c:\test\" then the last backslash has to be doubled --folderpath "c:\test\\".
If you are using MFC:
You can can get the value you want from your derived CWinApp's theApp.m_lpCmdLine. Note you could still access them the other way too with __argc, and __argv or CommandLineToArgvW.
If you are using Win32 only (even without a GUI):
You can get it from WinMain. Which can be your program's entry point.
Note you could still access them the other way too with __argc, and __argv or CommandLineToArgvW.
If you must use a console based application with main or wmain:
The Win32 API GetCommandLine seems to be the way to go. You would need to still parse this to get past the .exe name though. Take into account quotes around the exe name/path too. If there are no such quotes at the start, then just go to the next space for the start.
|
975,371
| 975,415
|
C++0x performance improvements
|
One of the C++0x improvements that will allow to write more efficient C++ code is the unique_ptr smart pointer (too bad, that it will not allow moving through memmove() like operations: the proposal didn't make into the draft).
What are other performance improvements in upcoming standard? Take following code for example:
vector<char *> v(10,"astring");
string concat = accumulate(v.begin(),v.end(), string(""));
The code will concatenate all the strings contained in vector v. The problem with this neat piece of code is that accumulate() copies things around, and does not use references. And the string() reallocates each time plus operator is called. The code has therefore poor performance compared to well optimized analogical C code.
Does C++0x provide tools to solve the problem and maybe others?
|
Yes C++ solves the problem through something called move semantics.
Basically it allows for one object to take on the internal representation of another object if that object is a temporary. Instead of copying every byte in the string via a copy-constructor, for example, you can often just allow the destination string to take on the internal representation of the source string. This is allowed only when the source is an r-value.
This is done through the introduction of a move constructor. Its a constructor where you know that the src object is a temporary and is going away. Therefore it is acceptable for the destination to take on the internal representation of the src object.
The same is true for move assignment operators.
To distinguish a copy constructor from a move constructor, the language has introduced rvalue references. A class defines its move constructor to take an rvalue reference which will only be bound to rvalues (temporaries). So my class would define something along the lines of:
class CMyString
{
private:
char* rawStr;
public:
// move constructor bound to rvalues
CMyString(CMyString&& srcStr)
{
rawStr = srcStr.rawStr
srcStr.rawStr = NULL;
}
// move assignment operator
CMyString& operator=(CMyString&& srcStr)
{
if(rawStr != srcStr.rawStr) // protect against self assignment
{
delete[] rawStr;
rawStr = srcStr.rawStr
srcStr.rawStr = NULL;
}
return *this;
}
~CMyString()
{
delete [] rawStr;
}
}
Here is a very good and detailed article on move semantics and the syntax that allows you to do this.
|
975,511
| 975,526
|
visual studio doesn't show new members
|
I've editted a struct, added some members, removed others. But when I'm debugging, it doesn't show the new members, but is still showing some old members. It's very annoying.
This is the struct. It doesn't show the firstFreeSpot int. But a vector called appointments, which I removed. This is the struct.
struct AppointmentHour
{
string date;
string beginTime;
string endTime;
string class;
int firstFreeSpot;
string toString();
static AppointmentHour* fromString(string str);
int getOccupation();
bool isSpaceFree(int duration);
int getFirstFreeSpot();
void addAppointmentDuration(int duration);
};
I'm certain this is the right struct, because when i go to the definition, it leads to this struct. And when i remove a field of this struct, it sayt it can't find it.
Has anybody a clue whats going on here?
|
Maybe try Rebuild solution?
|
975,513
| 975,614
|
Books about how linking, compiling, etc and how it all fits together?
|
I'm having trouble understanding how compilers and linkers work and the files they create. More specifically, how do .cpp, .h, .lib, .dll, .o, .exe all work together? I am mostly interested in C++, but was also wondering about Java and C#. Any books/links would be appreciated!
|
There are suprisingly few books on this topic Here are some thoughts:
Do not bother withn the Dragon Book unless you are actually writing a compiler using a table driven approach. It is a very hard read abd does not cover the simplest approach to parsing - recursive descent - in any detail. Caveat: I haven't read the leatest edition.
If you actually want to write a compiler, take a look at "Brinch Hansen on Pascal Compilers", which is an easy read and provides the full siource for a small pascal compiler. Don't let the pascal stuff put you off - the lessons it teaches are applicable to all compiled languages.
When it comes to linking, there are very few resources. The best book I've read on the subject is Linkers & Loaders.
|
975,792
| 975,820
|
How does delete[] know the size of an array?
|
I am curious how delete[] figures out the size of the allocated memory. When I do something like:
int* table = new int[5];
delete[] table;
I understand that the memory of the table is freed. But what would happen if I reassigned the pointer to some different table.
int* table = new [5];
int* table2 = new [9];
table = table2;
delete[] table;
Will I free a table of the size 5 or 9? I am interested in how new[] and delete[] share information about their size. Or maybe I am missing something essential here.
|
It would delete an array of size 9.
It deletes the array pointed to by the pointer.
It is unspecified how the size information is stored, so each compiler may implement it in a different way, but a common way to do it is to allocate an extra block before the array. That is, when you do this:
int* table = new int[5];
it actually allocates an array of 6 integers, and stores the array size in the first element. Then it returns a pointer to the second element. So to find the size, delete[] just has to read table[-1], basically.
That's one common way to do it, but the language standard doesn't specify that it must be done in this way. Just that it has to work.
Another approach might be to use the address of the array as a key into some global hash table. Any method is valid, as long as it produces the correct results.
|
976,002
| 2,656,893
|
xsd-based code generator to build xml?
|
I have a schema (xsd), and I want to create xml files that conform to it.
I've found code generators that generate classes which can be loaded from an xml file (CodeSynthesis). But I'm looking to go the other direction.
I want to generate code that will let me build an object which can easily be written out as an xml file. In C++. I might be able to use Java for this, but C++ would be preferable. I'm on solaris, so a VisualStudio plugin won't help me (such as xsd2code).
Is there a code generator that lets me do this?
|
To close this out: I did wind up using CodeSynthesis. It worked very well, as long as I used a single xsd as its source. Since I actually had two xsds (one imported the other), I had to manually merge them (they did some weird inheritance that needed manual massaging).
But yes, Code Synthesis was the way to go.
|
976,015
| 976,087
|
Why do I need to close fds when reading and writing to the pipe?
|
Here is an example to illustrate what I mean:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read?
The example above seems to work only for one write and one read.
|
Your pipe is a unidirectional stream - with a file descriptor for each end. It is not necessary to close() either end of the pipe to allow data to pass along it.
if your pipe spans processes (i.e. is created before a fork() and then the parent and child use it to communicate) you can have one write and and one read end. Then it is good practice to close the unwanted ends of the pipe. This will
make sure that when the writing end closes the pipe it is seen by the read end. As an example, say the child is the write side, and it dies. If the parent write side has not been closed, then the parent will not get "eof" (zero length read()) from the pipe - because the pipe has a open write-end.
make it clear which process is doing the writing and which process is doing the reading on the pipe.
if your pipe spans threads (within the same process), then do not close the unwanted ends of the pipe. This is because the file descriptor is held by the process, and closing it for one thread will close it for all threads, and therefore the pipe will become unusable.
There is nothing stopping you having one process writing continuously to the pipe and the other process reading. If this is a problem you are having then give us more details to help you out.
|
976,152
| 976,236
|
CArray and const template parameter
|
Is it possible to use const parameter to CArray
I am currently using CArray like this but it won't compile:
typedef CArray<const CString, const CString&> data_container;
And I always get this compile error :
error C2664: 'ATL::Checked::memcpy_s'
: cannot convert parameter 1 from
'const CString *' to 'void *'
|
The code that CArray uses expects your TYPE to be non-const, so it can cast to void* (as noted by the compilation error message).
You could store const CString pointers, which would give you a const CString when dereferenced. You do have the burden of allocating/cleaning up that memory now. An alternative is to wrap a CString in a simple class, that has a "GetString" function that returns a const reference to its internal CString instance.
|
976,476
| 976,504
|
Which is more similar to AS3, Java or C++?
|
I am ActionScript 3/Flex programmer, it is the first language I learned.
I want to learn either Java or C++.
Would one of these be easier to learn based on my current knowledge?
|
It really depends what you want to do. C++ is more powerful and fast. But Java has a smaller learning curve.
I'd say learn C++, only because it will require you to gain a better understanding of how computers work under the hood. It will also help position you to learn Java, C#, or any other language down the road.
|
976,573
| 978,912
|
Stopping a service in c++ when do I use the ExitProcess() func
|
I'm stopping a service in my application wanted to know what is the usage of
ExitProcess and if I should use it
|
You should never need to use ExitProcess() to stop a service. In fact, you should never need to use ExitProcess() at all.
Services are deeply intertwined with the SCM, and if a service that it thinks should be running just vanishes it will take some action to repair it. In extreme cases, it will force the system to reboot.
The correct way to stop a service is to use the documented API to ask the SCM to ask the service to stop. It often takes several seconds for this process to complete as the service itself usually needs to a clean shutdown after asking its worker threads to finish up and halt.
The privileges required to interact with the SCM are less dangerous than that required to end an arbitrary process, but neither is usually granted outside of the Administrators group.
Edit: A comment asked about stopping a service from inside itself.
That can be a tough call, especially if the service is in some kind of unfortunate state. The service and the SCM absolutely have to agree that the service is stopping, or the SCM will take the recovery action that was configured for the service.
I do have a complete implementation of a service that might serve as an alternative point of view for how to handle some of these things. It is LuaService and is a framework that allows a (single worker thread) service to be implemented in pure Lua aside from the LuaService executable itself. Its reference manual attempts to fully document the internals, as well as document some of the details of a service's lifetime that are otherwise documented through the interaction of various articles on MSDN.
|
976,834
| 976,845
|
C++ overloaded operator declaration and definition problems
|
I am having a hard time getting this to work
file: myclass.hpp
Class MyClass {
public:
template <class T>
MyClass &operator<<(const T &val);
};
file: myclass.cpp
template <class T>
MyClass &MyClass::operator<<(const T &val) {
...
}
I can compile this in to a object without a problem, But when other functions try to calling it, this error comes up (for every time << was used).
myclass.cpp: undefined reference to `MyClass& MyClass::operator<< <int>(int const&)'
What am I doing wrong?
|
If you want to define instances of your template in separate compilation units (which is typically the case) then you can't define template methods in a separate cpp. Every template method must be visible to the compiler when compiling compilation units that use that template class. Therefore when using the template across cpps, the template must be defined in a header. Template's are really ways of generating classes not classes in-and-of-themselves. Therefore when the compiler sees
YourClass<int>
it needs to see the entire YourClass template at compile time to generate a type called
YourClass<int>
and all its methods, which have completely separate methods from say
YourClass<float>
Which means it must see all the C++ source code. If these two uses of the template are instantiated in separate cpp's then the only way only way the compiler can generate both is to fully define the template in one header.
See my answer here for more info.
Thanks for the useful comments that greatly improved this answer
|
976,993
| 977,118
|
Issues with seeding a pseudo-random number generator more than once?
|
I've seen quite a few recommendations for not seeding pseudo-random number generators more than once per execution, but never accompanied by a thorough explanation. Of course, it is easy to see why the following (C/C++) example is not a good idea:
int get_rand() {
srand(time(NULL));
return rand();
}
since calling get_rand several times per second produces repeated results.
But wouldn't the following example still be an acceptable solution?
MyRand.h
#ifndef MY_RAND_H
#define MY_RAND_H
class MyRand
{
public:
MyRand();
int get_rand() const;
private:
static unsigned int seed_base;
};
#endif
MyRand.cpp
#include <ctime>
#include <cstdlib>
#include "MyRand.h"
unsigned int MyRand::seed_base = static_cast<unsigned int>(time(NULL));
MyRand::MyRand()
{
srand(seed_base++);
}
int MyRand::get_rand() const
{
return rand();
}
main.cpp
#include <iostream>
#include "MyRand.h"
int main(int argc, char *argv[])
{
for (int i = 0; i < 100; i++)
{
MyRand r;
std::cout << r.get_rand() << " ";
}
}
i.e. even though MyRand:s constructor is called several times in rapid succession, each call to srand has a different parameter. Obviously, this is not thread-safe, but then again neither is rand.
|
Each time you call a pseudo-random number generator function, the generator takes some internal state and produces a pseudo-random number and a new internal state. The algorithm for transforming the internal state is carefully chosen so the output appears random.
When you seed the random number generator, you're basically setting this internal state. If you reset the internal state to some predictable value, you'll lose the appearance of randomness.
For example, a popular, simple RNG is a linear congruential generator. Numbers are generated like this:
X[n+1] = (a X[n] + c) mod m
In this case, X[n+1] is both the result and the new internal state. If you seed the generator every time as you suggest above, you'll get a sequence that looks like this:
{(ab + c) mod m, (a(b+1) + c) mod m, (a(b+2) + c) mod m, ...}
where b is your seed_base. This doesn't look random at all.
|
977,105
| 977,138
|
Ever done a total rewrite of a large C++ application in C#?
|
I know Joel says to never do it, and I agree with this in most cases. I do think there are cases where it is justified.
We have a large C++ application (around 250,000 total lines of code) that uses a MFC front end and a Windows service as the core components. We are thinking about moving the project to C#.
The reasons we are thinking about rewriting are:
Faster development time
Use of WCF and other .NET built-in features
More consistent operation on various
systems
Easier 64 bit support
Many nice .NET libraries and
components out there
Has anyone done a rewrite like this? Was it successful?
EDIT:
The project is almost 10 years old now, and we are getting to the point that adding new features we want would be writing significant functionality that .NET already has built-in.
|
Have you thought about instead of re writing from scratch you should start to separate out the GUI and back end layer if it is not already, then you can start to write pieces of it in C#.
the 250,000 lines were not written overnight they contains hundreds of thousands of man years of effort, so nobody sane enough would suggest to rewrite it all from scratch all at once.
The best approach if you guys are intend on doing it is piece by piece. otherwise ask for several years of development effort from your management while no new features are implemented in your existing product (basically stagnating in front of competition)
|
977,265
| 977,356
|
Sleep while holding a boost::interprocess::scoped_lock causes it to be never released
|
I'm doing IPC on Linux using boost::interprocess::shared_memory_object as per the reference (anonymous mutex example).
There's a server process, which creates the shared_memory_object and writes to it, while holding an interprocess_mutex wrapped in a scoped_lock; and a client process which prints whatever the other one has written - in this case, it's an int.
I ran into a problem: if the server sleeps while holding the mutex, the client process is never able to aquire it and waits forever.
Buggy server loop:
using namespace boost::interprocess;
int n = 0;
while (1) {
std::cerr << "acquiring mutex... ";
{
// "data" is a struct on the shared mem. and contains a mutex and an int
scoped_lock<interprocess_mutex> lock(data->mutex);
data->a = n++;
std::cerr << n << std::endl;
sleep(1);
} // if this bracket is placed before "sleep", everything works
}
Server output:
acquiring mutex... 1
acquiring mutex... 2
acquiring mutex... 3
acquiring mutex... 4
Client loop:
while(1) {
std::cerr << "acquiring mutex... ";
{
scoped_lock<interprocess_mutex> lock(data->mutex);
std::cerr << data->a << std::endl;
}
sleep(1);
}
Client output (waits forever):
acquiring mutex...
The thing is, if I move the bracket to the line before the sleep call, everything works. Why? I didn't think sleeping with a locked mutex would cause the mutex to be eternally locked.
The only theory I have is that when the kernel wakes up the server process, the scope ends and the mutex is released, but the waiting process isn't given a chance to run. The server then re-acquires the lock... But that doesn't seem to make a lot of sense.
Thanks!
|
Your theory is correct.
If you look at the bottom of the anonymous mutex example in the reference you linked, you'll see
As we can see, a mutex is useful to protect data but not to notify to another process an event.
Releasing the mutex doesn't notify anyone else that might be waiting on it, and since your process just woke up, it almost certainly has plenty of its scheduling quantum left to do more work. It will loop around and re-acquire the mutex before it sleeps again, which is the first opportunity the client has to acquire the mutex itself.
Moving the server sleep() outside of the scope means it goes to sleep while the mutex is free, giving the client a chance to run and acquire the mutex for itself.
Try calling sched_yield() (Linux only) if you want to give up the processor, but still sleep within your scope. sleep(0) may also work.
|
977,543
| 977,561
|
Under what circumstances is it advantageous to give an implementation of a pure virtual function?
|
In C++, it is legal to give an implementation of a pure virtual function:
class C
{
public:
virtual int f() = 0;
};
int C::f()
{
return 0;
}
Why would you ever want to do this?
Related question: The C++ faq lite contains an example:
class Funct {
public:
virtual int doit(int x) = 0;
virtual ~Funct() = 0;
};
inline Funct::~Funct() { } // defined even though it's pure virtual; it's faster this way; trust me
I don't understand why the destructor is declared pure virtual and then implemented; and I don't understand the comment why this should be faster.
|
Declared destructors must always be implemented as the implementation will call them as part of derived object destruction.
Other pure virtual functions may be implemented if they provide a useful common functionality but always need to be specialized. In the case, typically derived class implementations will make an explicit call to the base implementation:
void Derived::f()
{
Base::f();
// Other Derived specific functionality
}
Typically, you make a destructor virtual if you need to make a class abstract (i.e. prevent non-derived instances from being created) but the class has no other functions that are naturally pure virtual. I think the 'trust me it's faster' is refering to the fact that because destructors called as part of derived object clean up don't need to use a vtable lookup mechanism, the inline implementation can be taken advantage of, unlike typical virtual function calls.
|
977,553
| 977,575
|
Inheritance issue when wrapping (inheriting) from a C++ library
|
The library I'm using has class G and class S which inherits G.
I needed to add functionality to them, so I wrapped G and S, rather I inherited from them making Gnew and Snew respectively.
So, my inheritance is:
G --> Gnew
|
v
S --> Snew
But, I want to use Gnew in Snew and when I try to include the Gnew header (in the Snew implementation file) to use it ... the include guards mask the definition of Gnew in Snew???
How can I use Gnew in Snew? Right now, the compiler wont even let me forward declare Gnew in the Snew definition file (which doesn't make sense to me) unless I forward declare inside the class.
In Snew (if I forward declare before the Snew definition) I have:
...
Gnew *g;
The error is:
error: ISO C++ forbids declaration of ‘Gnew’ with no type
If I change Snew to say:
...
class Gnew *g;
Gnew *g;
The error is:
error: invalid use of undefined type ‘struct Snew::Gnew’
NOTE:
I was trying to abstract the problem, so I'm closing this and reopening a better phrasing of the question ...
|
Where's the cycle? And why would Gnew include the header of Snew?
[Edit]
OK, I think your inheritance arrows are opposite of what's customary. But this should get you sorted out:
In Gnew.h:
#pragma once
#if !defined(Gnew_h)
#define Gnew_h
#include "G.h"
class Gnew : public virtual G
{
// added functionality here.
};
#endif // Gnew_h
In Snew.h:
#pragma once
#if !defined(Snew_h)
#define Snew_h
#include "S.h"
#include "Gnew.h"
class Snew : public virtual Gnew, public virtual S
{
// added functionality here.
};
#endif // Snew_h
You should not have to forward declare anything.
Note however that this only works as expected if S inherits virtually from G. If all these multiple inheritance issues are too much trouble, you should probably just adapt the library classes instead of inheriting from them.
Does this help?
|
977,629
| 977,876
|
OpenGL Rotation Matrices And ArcBall
|
I have been tasked with creating a OpenGL scene implementing ideas such as simple movement, and an Arcball interface. The problem I am having is dealing with the rotation matrix which NeHe's Arcball class (http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=48) computes.
What I have so far is a very simple solar system (just the earth, moon and sun) which looks great. What I want is for the camera to follow whichever planet the user selects (by clicking on the one they want), and for them to be able to rotate around the planet at a fixed distance using mouse-drag (arcball). As I said at the beginning, NeHe's class is generating a rotation matrix based on the mouse clicking and dragging. What I want to apply the matrix to is the camera position. However, when I do that my camera just wobbles without ever rotating around the planet. So I am guessing that I am either missing some step, or that I have a horrible understanding of what I am trying to do.
Here is some code from my camera class to crunch on:
// transform is the matrix from NeHe's arcball interface
void camera::update(Matrix4fT transform) {
glm::mat4 transform_m = glm::mat4(0.0f);
// convert nehe's matrices to GLM matrix
for(int i=0; i < 4; i++)
for(int j=0; j < 4; j++)
transform_m[i][j] = transform.M[i*4+j];
// apply matrix to the position
glm::vec4 pos4 = glm::vec4(this->pos, 1.0f);
pos4 = transform_m * pos4;
this->pos = glm::vec3(pos4);
}
void camera::apply(planet *target) {
// called at the beginning of GLPaint
gluLookAt(this->pos.x,this->pos.y,this->pos.z, // cam->position
target->pos.x,target->pos.y,target->pos.z, // moving
this->up.x,this->up.y,this->up.z); // (0,1,0)
}
Other than that, NeHe's functions are called in the right places (during click and drag)... So really, I have no idea where to go from here. I hope someone can help me with this, and if you want to see the whole code base (its programmed in C++ and pushed into a QTPanel) just send me an email.
Thanks,
Carl Sverre (carl at carlsverre dot com)
|
Well, maybe I am wrong, but what I think that is happening to you is that you are rotating around the center of coordinates and not around the planet (that it's what you want to do). To correct that what you have to do is:
Translate the point you want to rotate around (the center of the planet) to the center of coordinates, applying a translation of the negation of its position
Rotate as you are doing it
Undo the translation previously done.
The thing to understand is that rotations are done around the center of coordinates, and if you want to rotate around somewhere different, you must first move that point to the center of coordinates.
Hope that it helps.
|
977,653
| 980,028
|
GUI thread detecting in the Qt library
|
I need to know in the context of which thread my function is running, is it main GUI thread or some worker thread.
I can't use a simple solution to store QThread pointer in the main function and compare it to QThread::currentThread() because I'm writing a library and I do not have access to the main function. I can of course create InitMyLibary() function and require library user to call it in the context of the GUI thread but I'm really against this.
|
If you have Qt in the lib you can ask for the thread of the application object. The application object is alway living in the main gui thread.
void fooWorker()
{
const bool isGuiThread =
QThread::currentThread() == QCoreApplication::instance()->thread();
}
|
977,927
| 977,946
|
Why does this derived class need to be declared as a friend?
|
I'm learning C++ on my own, and I thought a good way to get my hands dirty would be to convert some Java projects into C++, see where I fall down. So I'm working on a polymorphic list implementation. It works fine, except for one strange thing.
The way I print a list is to have the EmptyList class return "null" (a string, not a pointer), and NonEmptyList returns a string that's their data concatenated with the result of calling tostring() on everything else in the list.
I put tostring() in a protected section (it seemed appropriate), and the compiler complains about this line (s is a stringstream I'm using to accumulate the string):
s << tail->tostring();
Here's the error from the compiler:
../list.h: In member function 'std::string NonEmptyList::tostring() [with T = int]':
../list.h:95: instantiated from here
../list.h:41: error: 'std::string List::tostring() [with T = int]' is protected
../list.h:62: error: within this context
Here's most of list.h:
template <class T> class List;
template <class T> class EmptyList;
template <class T> class NonEmptyList;
template <typename T>
class List {
public:
friend std::ostream& operator<< (std::ostream& o, List<T>* l){
o << l->tostring();
return o;
}
/* If I don't declare NonEmptyList<T> as a friend, the compiler complains
* that "tostring" is protected when NonEmptyClass tries to call it
* recursively.
*/
//friend class NonEmptyList<T>;
virtual NonEmptyList<T>* insert(T) =0;
virtual List<T>* remove(T) =0;
virtual int size() = 0;
virtual bool contains(T) = 0;
virtual T max() = 0;
virtual ~List<T>() {}
protected:
virtual std::string tostring() =0;
};
template <typename T>
class NonEmptyList: public List<T>{
friend class EmptyString;
T data;
List<T>* tail;
public:
NonEmptyList<T>(T elem);
NonEmptyList<T>* insert(T elem);
List<T>* remove(T elem);
int size() { return 1 + tail->size(); }
bool contains(T);
T max();
protected:
std::string tostring(){
std::stringstream s;
s << data << ",";
/* This fails if List doesn't declare NonEmptyLst a friend */
s << tail->tostring();
return s.str();
}
};
So declaring NonEmptyList a friend of List makes the problem go away, but it seems really strange to have to declare a derived class as a friend of a base class.
|
Because tail is a List<T>, the compiler is telling you that you can't access a protected member of another class. Just as in other C-like languages, you can only access protected members in your instance of the base class, not other people's.
Deriving class A from class B does not give class A access to every protected member of class B on all instances that are of type class B or derived from that type.
This MSDN article on the C++ protected keyword may be helpful in clarifying.
Update
As suggested by Magnus in his answer, in this instance, a simple fix might be to replace the call to tail->tostring() with the << operator, which you've implemented for List<T> to provide the same behavior as tostring(). That way, you wouldn't need the friend declaration.
|
978,222
| 2,581,498
|
OpenMp C++ algorithms for min, max, median, average
|
I was searching Google for a page offering some simple OpenMp algorithms.
Probably there is an example to calculate min, max, median, average from a huge data array but I am not capable to find it.
At least I would normally try to divide the array into one chunk for each core and do some boundary calculation afterwards to get the result for the complete array.
I just didn't want to reinvent the wheel.
Additional Remark:
I know that there are thousands of examples that work with simple reduction.
e.g. Calculating PI.
const int num_steps = 100000;
double x, sum = 0.0;
const double step = 1.0/double(num_steps);
#pragma omp parallel for reduction(+:sum) private(x)
for (int i=1;i<= num_steps; i++){
x = double(i-0.5)*step;
sum += 4.0/(1.0+x*x);
}
const double pi = step * sum;
but when these kind of algorithms aren't usable there are almost no examples left for reducing algorithms.
|
OpenMP (at least 2.0) supports reduction for some simple operations, but not for max and min.
In the following example the reduction clause is used to make a sum and a critical section is used to update a shared variable using a thread-local one without conflicts.
#include <iostream>
#include <cmath>
int main()
{
double sum = 0;
uint64_t ii;
uint64_t maxii = 0;
uint64_t maxii_shared = 0;
#pragma omp parallel shared(maxii_shared) private(ii) firstprivate(maxii)
{
#pragma omp for reduction(+:sum) nowait
for(ii=0; ii<10000000000; ++ii)
{
sum += std::pow((double)ii, 2.0);
if(ii > maxii) maxii = ii;
}
#pragma omp critical
{
if(maxii > maxii_shared) maxii_shared = maxii;
}
}
std::cerr << "Sum: " << sum << " (" << maxii_shared << ")" << std::endl;
}
EDIT: a cleaner implementation:
#include <cmath>
#include <limits>
#include <vector>
#include <iostream>
#include <algorithm>
#include <tr1/random>
// sum the elements of v
double sum(const std::vector<double>& v)
{
double sum = 0.0;
#pragma omp parallel for reduction(+:sum)
for(size_t ii=0; ii< v.size(); ++ii)
{
sum += v[ii];
}
return sum;
}
// extract the minimum of v
double min(const std::vector<double>& v)
{
double shared_min;
#pragma omp parallel
{
double min = std::numeric_limits<double>::max();
#pragma omp for nowait
for(size_t ii=0; ii<v.size(); ++ii)
{
min = std::min(v[ii], min);
}
#pragma omp critical
{
shared_min = std::min(shared_min, min);
}
}
return shared_min;
}
// generate a random vector and use sum and min functions.
int main()
{
using namespace std;
using namespace std::tr1;
std::tr1::mt19937 engine(time(0));
std::tr1::uniform_real<> unigen(-1000.0,1000.0);
std::tr1::variate_generator<std::tr1::mt19937,
std::tr1::uniform_real<> >gen(engine, unigen);
std::vector<double> random(1000000);
std::generate(random.begin(), random.end(), gen);
cout << "Sum: " << sum(random) << " Mean:" << sum(random)/random.size()
<< " Min:" << min(random) << endl;
}
|
978,247
| 978,279
|
Is there any kind of "expression class" (C++)
|
I am creating a game that lets the player enter input, changes some states, then checks if a "goal value" is true (obviously this description is muchly simplified), and I want to be able to have that goal value be anything from if the players life is below a certain value to if the amount of enemies remaining is equal to zero. Is there any "expression class" that can hold a simple "value1 compare-operator value2" and check it? ie:
expression goal(x = 4);
if not, does anybody have any suggestions as to how I could develop an expression class?
EDIT: another (more towards what I am trying to achieve) example:
game.init(){ expression goal = FileRead(goalfile); }
game.checkstate(){ if(goal) exit(1); } //exit 1 is the games win state
//another more specific eg.:
class level1 { public: expression goal(total_enemies == 0); };
class level2 { public: expression goal(player.x == goal.x && player.y == goal.y); };
|
Dynamic expressions
If you want to receive a string from the user and built an expression from that, maybe the C++ Mathematical Expression Library fits your bill?
template<typename T>
void trig_function()
{
std::string expression_string = "clamp(-1.0,sin(2 * pi * x) + cos(x / 2 * pi),+1.0)";
T x;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_constants();
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
parser.compile(expression_string,expression);
for (x = T(-5.0); x <= T(+5.0); x += 0.001)
{
T y = expression.value();
printf("%19.15f\t%19.15f\n",x,y);
}
}
There are also the possibility embed a scripting language, such as Lua or Python, which will give you (even) more power. This is something to consider if you're writing a game, since you'll likely want to script large parts of it.
If you're using Qt, you can use QtScript (Javascript-ish) to run expressions that read (static or dynamic) properties from your QObject-derived objects.
Using one of the above keeps you from having to write your own parser, AST and evaluator, however for a small set of operators it shouldn't be too hard to hack together something if you use Boost.Spirit or some other decent parsing library.
Static expressions
For selecting between a set of predefined expressions (i.e. known at compile time), you should store the expression in a polymorphic function object.
For C++11, if that's available to you, use std::function and lambda expressions.
std::function<bool (int, int)> expr = [](int a, int b) { a*2 < b };
For earlier compilers, I recommend function and bind, either in Boost (boost::) or C++0x TR1 (std::), depending on your compiler. Also, Boost.Lambda will be of help here, as it allows you to construct and store expressions for later evaluation. However, if you're not familiar with C++ and templates (or functional programming), it will likely scare you quite a bit.
With that you could write
using namespace boost::lambda;
boost::function<bool (int, int)> myexpr1 = (_1 + _2) > 20;
boost::function<bool (int, int)> myexpr2 = (_1 * _2) > 42;
std::cout << myexpr1(4,7) << " " << myexpr2(2,5);
with bind, it'd look like:
boost::function<bool (Player&)> check = bind(&Player::getHealth, _1) > 20;
Player p1;
if (check(p1)) { dostuff(); }
check = bind(&Player::getGold, _1) < 42;
if (check(p1)) { doOtherStuff(); }
|
978,311
| 978,405
|
C++ Boost ptr_map serialization error
|
I have some code that I want to build. The code uses boost::ptr_map class to serialize certain objects. I have Visual Studio 2008 with boost1.38 and I am getting following error from compiler. I wonder if any one else has seen any thing like this.
C2039: 'serialize' : is not a member of 'boost::ptr_map'
Looks like some reference is missing and I wonder what it is, I don't see any boost/serialization/ptr_map. I have Googled a lot and nothing has proved to be viable. I have created a sample code that generates the same error below
#include <fstream>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/config.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/split_member.hpp>
using namespace std;
class User
{
boost::ptr_map<std::string, string> ptrmap;
public:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & ptrmap;
}
bool save(const std::string& filename)
{
ofstream ofs(filename.c_str());
if(ofs.good() == false)
{
return false;
}
try
{
boost::archive::text_oarchive oa(ofs);
oa << (*this);
}
catch(...)
{
throw;
}
return true;
}
};
int main()
{
User user;
user.save("C:\\test.db");
return EXIT_SUCCESS;
}
Any help is appreciated.
|
It looks like there is a boost/ptr_container/serialize_ptr_map.hpp, that is probably important to #include.
|
978,627
| 1,463,512
|
C# app to C++ dll back to the C# app via callbacks
|
I'm writing a C# application that calls a C++ dll. This dll is a device driver for an imaging system; when the image is being acquired, a preview of the image is available from the library on a line-by-line basis. The C++ dll takes a callback to fill in the preview, and that callback consists basically of the size of the final image, the currently scanned line, and the line of data itself.
Problem is, there's a pretty serious delay from the time when scanning stops and the C# callback stops getting information. The flow of the program goes something like:
Assign callback to C++ dll from within C#
User starts to get data
Device starts up
dll starts to call the callback after a few seconds (normal)
Device finishes image formation
dll is still calling the callback for double the time of image formation.
This same dll worked with a C++ application just fine; there does not appear to be that last step delay. In C#, however, if I have the callback immediately return, the delay still exists; no matter what I do inside the callback, it's there.
Is this delay an inherent limitation of calling managed code from unmanaged code, or is there something either side could do to make this go faster? I am in contact with the C++ library writer, so it's possible to implement a fix from the C++ side.
Edit: Could doing something simple like a named pipe work? Could an application read from its own pipe?
|
Turns out the delay is in the C++ side, by a developer who swore up and down it wasn't.
|
978,644
| 978,653
|
recursive file search
|
I'm trying to figure out how to work this thing out .. For some reason, it ends at a certain point.. I'm not very good at recursion and I'm sure the problem lies somewhere there..
Also, even if I checked for cFileName != "..", it still shows up at the end, not sure why but the "." doesn't show up anymore..
void find_files( wstring wrkdir )
{
wstring temp;
temp = wrkdir + L"\\" + L"*";
fHandle = FindFirstFile( temp.c_str(), &file_data );
if( fHandle == INVALID_HANDLE_VALUE )
{
return;
}
else
{
while( FindNextFile( fHandle, &file_data ) )
{
if( file_data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY &&
wcscmp(file_data.cFileName, L".") != 0 &&
wcscmp(file_data.cFileName, L"..") != 0 )
{
find_files( wrkdir + L"\\" + file_data.cFileName );
}
else if( file_data.dwFileAttributes != FILE_ATTRIBUTE_HIDDEN &&
file_data.dwFileAttributes != FILE_ATTRIBUTE_SYSTEM )
{
results << wrkdir << "\\" << file_data.cFileName << endl;
}
}
}
}
After changing those, the program doesn't enumerate the remaining files left..
For example, if there is a sub folder named test, it enumerates everything inside test but doesn't finish enumerating the files inside the original directory specified.
|
From the FindFirstFile documentation:
If the function fails or fails to
locate files from the search string in
the lpFileName parameter, the return
value is INVALID_HANDLE_VALUE and the
contents of lpFindFileData are
indeterminate.
You should only exit from the one iteration not the whole program:
if( fHandle == INVALID_HANDLE_VALUE )
{
return;
}
And this may solve your other problem:
else if( file_data.dwFileAttributes != FILE_ATTRIBUTE_HIDDEN &&
file_data.dwFileAttributes != FILE_ATTRIBUTE_SYSTEM &&
wcscmp(file_data.cFileName, L".") != 0 &&
wcscmp(file_data.cFileName, L"..") != 0
)
{
results << wrkdir << "\\" << file_data.cFileName << endl;
}
Also see @fretje's answer as well. It gives another problem that your code has.
Updated new: You need to use fHandle as a local variable as well, not global variable.
Change to:
HANDLE fHandle = FindFirstFile( temp.c_str(), &file_data );
|
978,739
| 978,768
|
Command pattern without virtual functions (C++)
|
For performance reasons, I am using the the Curiously Reoccuring Template Pattern to avoid virtual functions. I have lots of small commands which execute millions of times. I am trying to fit this into the Command Pattern. I want to add tons of commands to a queue, and then iterate through them executing each one by one. Each Command uses a CRTP to avoid virtual functions. The problem I am running into is that the Command pattern is typically implemented using a vector of pointers. But when the Command class is templated, it becomes hard to pass around generic Command pointers. I'm not a C++ expert, so perhaps there is an obvious way to store a vector of templated command objects? I have been trying to use something like:
boost:ptr_vector commands;
AddCommand(Command* command) {
commands.push_back(command);
}
The problem is Command is not a type, so Command* command gives a compile error. I need to use Command<CommandType>, but that won't work because I need the queue to hold different types of commands.
Any ideas for solutions? Or are virtual functions my only option?
ADDED: The command objects are part of a monte carlo simulation algorithm. So you might have, Command be a random number from a normal distribution, where the parameters of the normal distribution are part of the class. So the command pattern fits very nicely. I have lots of calls, in a particular order, to functions that need to maintain state.
|
The CRTP does its magic by resolving the run time type of the object at compile time so that the compiler can inline the function calls. If you have a vector of pointers to a generic type, the compiler cannot determine the specific concrete type, and will not be able to do its compile time resolution.
From just the information you have in your question, I think virtual functions are your best option. However, virtual functions are not that slow. They are slower than an in-lined function, sure, but in many cases they are plenty fast enough! Especially if your process is bounded by I/O time instead of processing time.
One of the answers to this question has some more in depth discussion of this issue. To summarize, the overhead for a virtual function call will likely be measured in nanoseconds. It is more complicated than that, but the point is that you shouldn't be afraid of virtual functions unless your function is doing something really trivial like a single assignment. You said that your commands were small, so perhaps this is the case. I'd try doing a quick prototype with virtual functions and see if that gives acceptable performance.
|
979,141
| 979,161
|
How to programmatically cause a core dump in C/C++
|
I would like to force a core dump at a specific location in my C++ application.
I know I can do it by doing something like:
int * crash = NULL;
*crash = 1;
But I would like to know if there is a cleaner way?
I am using Linux by the way.
|
Raising of signal number 6 (SIGABRT in Linux) is one way to do it (though keep in mind that SIGABRT is not required to be 6 in all POSIX implementations so you may want to use the SIGABRT value itself if this is anything other than quick'n'dirty debug code).
#include <signal.h>
: : :
raise (SIGABRT);
Calling abort() will also cause a core dump, and you can even do this without terminating your process by calling fork() followed by abort() in the child only - see this answer for details.
|
979,164
| 979,170
|
C++ / CLI - Change all files to UNMANAGED by default
|
Does anyone know how to change the default behavior of the /clr switch to make all files unmanaged by default? The default behavior of the switch is to make all files managed. I know I can mark each .cpp file individually, but there are ALOT of them...
|
I ended up leaving the switch OFF in the project properties and then tried turning it on only for those .cpp files that needed it, this worked once I fixed the incompatible options like /RTC1 and /Gm, etc.
EDIT In solution explorer, you can right click on the .cpp file and set properties for it, and these will be separate from your project settings.
|
979,174
| 979,188
|
Does an STL map always give the same ordering when iterating from begin() to end()?
|
It appears to from my simple testing but I'm wondering if this is guaranteed?
Are there conditions where the ordering will be not be guaranteed?
Edit: The case I'm particularly interested in is if I populate a map with a large number of entries, will the order of the itertator be the same across multiple runs of my executable? What if the entries are inserted in a different order?
|
Yes, it maintains an internal order, so iteration over a set that isn't changing should always be the same. From here:
Internally, the elements in the map
are sorted from lower to higher key
value following a specific strict weak
ordering criterion set on
construction.
|
979,182
| 980,288
|
learning c++ from boost library source code
|
I am very interested in c++ and want to master this language. I have read a lot of books about c++. I want to read some library source code to improve my skill, but when I read the boost library source code, I find it is very difficulty.
Can anyone give me some advice about how to read boost source code and before I can understand it what kind of books about c++ should I read?
|
Since you mention that you want to learn the dark art of meta programming then I would recommend "Modern C++ Design" by Andrei Alexandrescu.
Meta programming is a very complicated area and is not required most of the time. Once you learn about it, it is very easy to think that it can solve all your problems. It becomes your new favourite hammer.
I would also recommend becoming a very proficient user of libraries based on meta programming like boost and loki before you add it to your own code.
Two different programmers used meta programming in parts of the code base I am responsible for. While they were skilled programmers a commercial product should not be treated like a playground. These are probably the worst area's of our code base now, very complicated and very brittle esp when you add support for new compilers. If I was responsible for the code when they were written they would not be here, now they are too expensive to replace.
In short you very rarely need meta programming unless you are a library writer. And you cannot be a library writer without being a very accomplished library user.
|
979,397
| 979,410
|
What's wrong with my random number generator?
|
I'm just diving into some C++ and I decided to make a random number generator (how random the number is, it really doesn't matter). Most of the code is copied off then net but my newbie eyes cannot see anything wrong with this, is there any way this can be tweaked to give a number other than "6" each time?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int random_number(int min, int max)
{
srand((unsigned)time(0));
int random_num;
int range=(max-min)+1;
random_num = min+int(range*rand()/(RAND_MAX + 1.0));
return random_num;
}
int main()
{
for(int i =0;i < 100;i++)
{
cout << random_number(3,10) << endl;
}
}
|
Add srand before the loop
srand((unsigned)time(0));
for(int i =0;i < 100;i++)
{
std::cout << random_number(3,10) << endl;
}
|
979,436
| 979,465
|
Help with c++ template templates
|
Ok, so I wrote an stl-like algorithm called cartesian_product. For those who don't know, the cartesian product is every possible pair of elements from two sets. So the cartesian product of {1, 2, 3} and {10, 20, 30} is
{(1,10), (1,20), (1,30), (2,10), (2,20), (2,30), (3,10), (3,20), (3,30)}
So the function looks like
template <typename InIt1, typename InIt2, typename OutIt>
void
cartesian_product(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2, OutIt out)
{
for (; first1 != last1; ++first1)
for (InIt2 it = first2; it != last2; ++it)
*out++ = std::make_pair(*first1, *it);
}
There aren't template typedefs, so I made a traits class to hold the type that
the output iterator is from:
template <typename ObjA, typename ObjB, template <typename> class Container>
struct cartesian_product_traits
{
typedef Container<std::pair<ObjA, ObjB> > type;
};
So then I can say:
typedef cartesian_product_traits<int, int, std::vector>::type IntPairList;
IntPairList my_list;
cartesian_product(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(my_list);
but this doesn't seem to compile. I get a nice error:
error C3201: the template parameter list for class template 'std::vector' does not match the template parameter list for template parameter 'Container'
So I'm stumped. How do I get this to work?
|
The template parameter list for vector isn't just one element, it takes two:
template < class T, class Allocator = allocator<T> > class vector
so in order to accept vector, you need to have a template template parameter with two blanks:
template <typename ObjA, typename ObjB, template <typename, typename> class Container>
struct cartesian_product_traits
Edited: cut some advice, misread your code.
The way to do this properly would be to use a variadic macro on the template template parameter:
template <typename ObjA, typename ObjB, template <typename ...> class Container>
struct cartesian_product_traits
But that's far away from being a standard. If it were my code, I'd probably just have the consumers pound out the full template:
std::vector< std::pair<int, int> >
is shorter than
cartesian_product_traits<int, int, vector>
and the latter would only help if the definition for a Cartesian product changed.
|
979,443
| 979,491
|
how to open a file (ie. .txt file) in C++ (kinda like double clicking it in windows)?
|
I'm wondering how I can open a file literally in C++ (like double clicking it)?
|
Provided you have the ".txt" extension registered (and text files should be associated with Notepad in a default installation, or something else if you've changed it from Explorer - you'd have to work pretty hard to disassociate them), Windows will open it for you without you having to specify the executable name:
ShellExecute (hwnd,"open","c:\\x.txt",NULL,NULL,SW_SHOW);
or, for a web page in your browser of choice:
ShellExecute (hwnd,"open","http://www.microsoft.com",NULL,NULL,SW_SHOW);
|
979,759
| 979,768
|
Operator< and strict weak ordering
|
How to define operator< on n-tuple (for example on 3-tuple) so that it satisfy strict weak ordering concept ? I know that boost library has tuple class with correctly defined operator< but for some reasons I can't use it.
|
if (a1 < b1)
return true;
if (b1 < a1)
return false;
// a1==b1: continue with element 2
if (a2 < b2)
return true;
if (b2 < a2)
return false;
// a2 == b2: continue with element 3
if (a3 < b3)
return true;
return false; // early out
This orders the elements by a1 being most siginificant and a3 least significant.
This can be continued ad infinitum, you could also e.g. apply it to a vector of T, iterating over comparisons of a[i] < a[i+1] / a[i+1] < a[i]. An alternate expression of the algorithm would be "skip while equal, then compare":
while (i<count-1 && !(a[i] < a[i+1]) && !(a[i+1] < a[i])
++i;
return i < count-1 && a[i] < a[i+1];
Of course, if the comparison is expensive, you might want to cache the comparison result.
[edit] removed wrong code
[edit] if more than just operator< is available, I tend to use the pattern
if (a1 != b1)
return a1 < b1;
if (a2 != b2)
return a2 < b2;
...
|
979,814
| 979,833
|
C++ References and Java References
|
//C++ Example
#include <iostream>
using namespace std;
int doHello (std::string&);
int main() {
std::string str1 = "perry";
cout << "String=" << str1 << endl;
doHello(str1);
cout << "String=" << str1 << endl; // prints pieterson
return 0;
}
int doHello(std::string& str){
str = "pieterson";
cout << "String=" << str << endl;
return 0;
}
In the above case, as expected the string 'str1' reference is modified when str reference is modified
//Java Example
public class hello {
public static void main(String args[]){
String str1 = "perry";
System.out.println("String=" + str1);
doHello(str1);
System.out.println("String=" + str1); // does not prints pieterson
}
public static void doHello(String str){
str = "pieterson";
System.out.println("String = " + str);
}
}
In Java, String str and String str1 are two different objects initially referencing the same String, so when we change str reference in doHello(), str1 reference does not get changed.
How can we achieve C++ style functionality in Java with Strings, Collections such as List, Vectors, other Objects.
Update:
Thanks Jon for a wonderful explaination, I believe any Java beginner will surely come across this question.
Let me explain what problem i ran into while using lists.
//bad doHello()
void doHello(List inputList) {
inputList = getListFromAnyFunction(); // wrong, didnt work
}
// good doHello
void doHello(List inputList) {
inputList.addAll(getListFromAnyFunction()); // worked
}
Thanks Powell and Harshath for your explainations and code samples.
|
Java does not have pass by reference (which you were using in the C++ code) at all. The references are passed by value. (The values of str and str1 aren't objects at all, they're references - it really helps to keep the two concepts very separate.)
Typically you would use a return value to return a new reference if you need to:
str1 = doHello(str1);
Note that String is slightly different to List etc, because strings are immutable. To modify a collection (well, any mutable collection) you don't need to create a new one, you just modify the object via the original reference:
public static void addHello(List<String> items)
{
items.add("Hello");
}
You could then call this like so:
List<String> list = new ArrayList<String>();
addHello(list);
System.out.println(list.get(0)); // "Hello"
The difference between mutating an existing object and changing the value of a variable to refer to a different object is crucial. If you want to leave the existing collection alone and create a new one, you'd have to do that explicitly:
public static List<String> withHello(List<String> items)
{
List<String> newList = new ArrayList<String>(items);
newList.add("Hello");
return newList;
}
You'd then call it like this:
List<String> empty = new ArrayList<String>();
List<String> newList = withHello(empty);
System.out.println(empty.size()); // Prints 0
System.out.println(newList.size()); // Prints 1
Does this answer everything you needed?
|
979,877
| 979,947
|
Concat string in C++(STL)
|
i have code like this
string xml_path(conf("CONFIG"));
xml_path+=FILE_NAME;
Where,
conf function returns char * and FILE name is const char *
I want to combine it to one line like
xml_path(conf("CONFIG")).append(FILE_NAME)
how do i do it?
any suggestions ??
|
Question asked for one line:
string xml_path = string(conf("CONFIG")) + string(FILE_NAME);
(I assume xml_path is the name of the variable, and not some sort of call in a library I don't know about).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.