question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,711,525 | 1,712,115 | Why this program fails (sometimes)? | #include <cstdio>
#include <QtCore/QProcess>
int main (int argc, char** argv) {
// if we remove 3 following lines, the problem described below doesn't exists!!
QProcess process;
process.start ("asdqwe"); // doesn't matter what we try to execute here.
process.waitForStarted (1000);
while (true) {
char buf[100];
if (scanf ("%s", buf) == EOF) { // it looks like stdin is closed!
printf("FAIL\n");
return 1;
}
printf ("%s\n", buf);
}
return 0;
}
This code is just a snippet to show the problem. In the full application I need read/write communication with process.
I compile it with:
g++ -o out ./main.cpp -I /usr/include/qt4/ -lQtCore
And execute it from bash command line in terminal.
Why this program sometimes prints FAIL and sometimes will stay in loop?
Edit:
This is not question about scan/printf.
The same problem is if I use iostreams + string. This question is about interaction of QProcess with file descriptors of parent process.
| Your scanf was interrupted by SIGCHLD signal that was caught when child process terminated. In this case EOF is also returned.
QProcess stuff does set up signal handler for SIGCHLD (check sources): (4.5.3 here)
Q_GLOBAL_STATIC(QProcessManager, processManager)
QProcessManager::QProcessManager()
{
#if defined (QPROCESS_DEBUG)
qDebug() << "QProcessManager::QProcessManager()";
#endif
// initialize the dead child pipe and make it non-blocking.
// (pipe and fcntl skipped - P. Shved.)
// set up the SIGCHLD handler, which writes a single byte to the dead
// child pipe every time a child dies.
struct sigaction oldAction;
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = qt_sa_sigchld_handler;
action.sa_flags = SA_NOCLDSTOP;
::sigaction(SIGCHLD, &action, &oldAction);
if (oldAction.sa_handler != qt_sa_sigchld_handler)
qt_sa_old_sigchld_handler = oldAction.sa_handler;
}
|
1,711,731 | 1,711,972 | Initialising classes inside another class in C++? | I have this definition in a header file:
class Owner
{
private:
// Fields
Child* _myChild1;
public:
// Constructors
Owner();
Owner(const char childName[]);
};
and this implementation:
Owner::Owner(const char childName[])
{
//do some operations - children must be created after these ops
_myChild = new Child(childName);
}
and this main() function:
int main()
{
Owner("child1");
}
Some questions, and please bear with me here, I'm just starting out with C++ ..
Given that the child classes are known at compile time am I right in thinking that I don't need to create them with 'new' on the heap? If so how? I have tried using this syntax in the Owner implementation but the compiler moans ('term does not evaluate to a function..'):
_myChild(childName);
However, using this syntax in the implementation is ok, why?
Child _myChild(childName);
Is the paradigm that I'm using correct? In other words, as a general rule, if one class wraps another does the owner only ever hold pointers to the classes it wraps?
How would you more experienced guys do it?
Thanks for any advice..
| Basically, how it works is thus:
If the Child class is fully defined before the Owner class, it can be included in the Owner in it's entirety, or as a pointer, whichever you prefer.
If the Child class is not fully defined before the Owner class, it would have to be forward declared and can only be included as a pointer. This would have to be allocated on the heap with new.
If you do include a class in it's entirety, it will be constructed at the same time as the owner object is constructed. Unless explicitly told otherwise, the compiler will use the default constructor for this.
Option 1:
// will create a Child object using the default constructor.
// this is done even before doStuff() is called.
Owner::Owner(const char childName[]) {
doStuff();
}
Option 2:
// will create a Child object using the Child(const char*) constructor.
// again, done before doStuff() is called.
Owner::Owner(const char childName[]): _myChild(childName) {
doStuff()
}
You can't use the _myChild(childName); syntax inside the constructor itself, since _myChild has already been constructed before it ever gets that far. Child _myChild(childName); is legal, but it creates a new local object named _myChild rather than modifying the class member _myChild. This is probably not the intended result.
If you want to assign a new value to _myChild after it's constructed, do one the following:
Preferred method: Modify the existing object somehow (such as overloading the assignment operator to allow you to do _myChild = childName;, or using some form of _myChild.setName(childName); function).
Alternate method: Use _myChild = Child(childName); to create a new Child and assign it to the member variable.
This second option, although functional, is inefficient since it requires constructing the object twice for no good reason.
|
1,711,733 | 1,711,807 | Does anyone know where I can find the standard windows file dialog toolbar icons? | I'm trying to roll my own implementation of IShellBrowser because I need to have a more full-featured File Open and Save As dialog than Windows allows that is compatible with XP (and ideally with W2000)*
At this point I need to add the standard toolbar that you see in upper right of the dialog (manifest styles for XP and earlier) - a back button, a parent-folder button, a new folder button, and a "tools" drop down.
But so far I've been unsuccessful in finding these icons / images. I've looked in USER32.dll, comdlg32.dll, comctl32.dll, but haven't found anything that quite matches.
I could simply take screen shots of an application where I can find them - but it would possibly more useful to know where they come from, so I can access the various versions of these buttons (high rez, low rez, shallow color, deep color, etc.).
Any ideas?
[Edit: I need it to be compatible with Vista & Windows 7 also. Its just that starting with Vista, they broke the old common dialog model, and their new model is brain-damaged IMO - I no longer have enough access to the state of the dialog to perform the necessary duties that our dialogs used to do - so we are forced to approach the problem from another angle]
| Try shell32.dll, in Windows\System32.
|
1,711,990 | 1,711,995 | What is this weird colon-member (" : ") syntax in the constructor? | Recently I've seen an example like the following:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
What does this strange : bar(num) mean? It somehow seems to initialize the member variable but I've never seen this syntax before. It looks like a function/constructor call but for an int? Makes no sense for me. Perhaps someone could enlighten me. And, by the way, are there any other esoteric language features like this, you'll never find in an ordinary C++ book?
| It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other things being equal, your code will run faster if you use initialization lists rather than assignment.
|
1,712,047 | 1,712,295 | Overloading the ostream << operator for a static class? | I have a (simplified) static global class and << operator overload as follows:
class Global
{
private:
static int counter;
Global(){};
public:
friend ostream& operator<<(ostream &out, Global &global);
}
ostream& operator<< (ostream &out, Global &global)
{
//... do output
return out;
}
I want to be able to pass a static reference to cout:
cout << Global
However, the << operator wants an instance, yet no instances of this global class actually exist. Is there anyway around this?
Thanks for any help.
| First of all, you cannot use a class name as a value - it simply isn't one. So you'll have to introduce a different name for use with << - say, global (with lowercase "g").
In general, if you want to introduce a "streamable" name without defining an object, you should write a stream manipulator:
std::ostream& foo(std::ostream& out)
{
out << "foo";
return out;
}
The trick here is that streams have overloaded operator << such that, if you pass a function pointer to it, and that function takes and returns a stream, then << will be equivalent to applying the function to the stream. In other words, you are able to write:
std::cout << 123 << foo << 456;
and it'll be the same as:
foo(std::cout << 123) << 456;
It's how std::endl is implemented, for example.
The same thing also applies to >>, and you can provide template function on basic_istream and/or basic_ostream if you want it to be more generic.
|
1,712,263 | 1,712,269 | How can I create memory dumps and analyze memory leaks? | I need to get the following to analyze a memory leak issue. How to do that?
Orphan Block Addresses Orphan Call
Stack
Are there any good resources/tools to know about/fix memory leaks.
Thanks
| If you're on linux, use valgrind. It's your new best friend. I'm not sure what tools are available for Windows.
|
1,712,407 | 1,712,431 | Can't include dynamic library header file in more than one file? | I have successfully added a dynamic library to a program, but when I try to include the header file in a second file of the project I get errors about class redeclaration. I will add more info if this isn't enough
| You need to put guards into your header so it isn't included multiple times. For file 'my.h', you can add something along the lines of:
#ifndef MY_H
#define MY_H
// Header declarations here
#endif
This way, you can include the .h file multiple times but it will only be included the first time.
|
1,712,411 | 1,714,063 | QtScript -- script-side callback through C++-side implementation | The solution may be simple. Then again it may not be possible.
I have the base callback class:
class CFCallback {
int command_;
int transfer_rate_;
public:
CFCallback(int command, int transfer_rate = 0) {
command_ = command; transfer_rate_ = transfer_rate; }
virtual ~CFCallback() {}
virtual void operator()(void *data) = 0;
int GetCommand() { return command_; }
int GetTransferRate() { return transfer_rate_; }
};
And here's one example of deriving from CFCallback:
void CFPacketVersion::InitiateVersion() {
class InitiateVersionCB : public CFCallback {
CFPacketVersion *visitor_;
public:
InitiateVersionCB(CFPacketVersion *v, int command) :
CFCallback(command) {
visitor_ = v;
}
void operator()(void *data) {
Packet *pkt = (Packet *)data;
unsigned char *pkt_data = pkt->GetData();
std::string version = "";
for(unsigned int i = 0; i < pkt->GetDataLength(); i++ )
version+= pkt_data[i];
delete []pkt_data;
boost::regex rex("CFA(.*?):h(.*?),v(.*?)$");
boost::smatch what;
if( boost::regex_match(version, what, rex) ) {
if(visitor_->GetModel()->GetName() != what[1].str() )
LCDInfo("Crystalfontz: Model mismatch");
visitor_->SetHardwareVersion(what[2]);
visitor_->SetFirmwareVersion(what[3]);
}
}
};
GetVersion(new InitiateVersionCB(this, 1));
}
GetVersion(CFCallback *) is provided to the script engine.
I want to be able to do the same thing as seen in InitiateVersion, but on the javascript side of things. Is that possible?
I know I need to register meta type info for CFCallback. But I don't know if it's possible to use a pointer to a CFCallback. What I tried initially didn't work.
Also, seeing as CFCallback is a functor, I'm not sure how I translate that over to javascript. I imagine I can make CFCallback a QObject and provide a signal emitted from operator(). If you have any tips, please share.
| I'm afraid it won't work the way you've set it up.
If you want to be able to create the callback in javascript, you need a QObject with an accessible GetVersion(QScriptValue) which the script will the use to pass a script-based implementation of the callback. Note, though, that the callback will not be able to work with untyped (void*) data - you need to pass either a valid QtScript object or QObject with a proper interface (like the Packet one in your example!)
You could then wrap it up like this:
QtScript:
function mycb(packet) {
var pkt_data = packet.getData(); // pkt_data is probably a String or custom object with proper interface so to simplify things get the version as string
var version = pkt_data.toString();
pkt_data.release(); // to simulate delete [] pkt_data; this is part of custom interface
// proceed further with the regex checks
}
GetVersion(mycb); // implies that you define the GetVersion() as a property of the global object
C++:
QScriptValue getVersion(QScriptContext *ctx, QScriptEngine *engine)
{
void *data = ...;
Packet pkt_data = wrapPacketData(data);
// Packet is interface registered with QtScript or inherits QObject
// it has methods getData(), toString() and release()
QScriptValueList args;
QScriptValue pkt_data_param = engine->newQObject(&pkt_data);
args << pkt_data_param;
QScriptValue cb = ctx->argument(0);
Q_ASSERT(cb.isFunction()); // we expect a function object!
cb.call(QScriptValue(), args);
}
QScriptValue getVersionFun = engine->newFunction(getVersion);
engine->globalObject().setProperty(QLatin1String("GetVersion"), getVersionFun);
|
1,712,562 | 1,712,577 | Isn't there a point where encapsulation gets ridiculous? | For my software development programming class we were supposed to make a "Feed Manager" type program for RSS feeds. Here is how I handled the implementation of FeedItems.
Nice and simple:
struct FeedItem {
string title;
string description;
string url;
}
I got marked down for that, the "correct" example answer is as follows:
class FeedItem
{
public:
FeedItem(string title, string description, string url);
inline string getTitle() const { return this->title; }
inline string getDescription() const { return this->description; }
inline string getURL() const { return this->url; }
inline void setTitle(string title) { this->title = title; }
inline void setDescription(string description){ this->description = description; }
inline void setURL(string url) { this->url = url; }
private:
string title;
string description;
string url;
};
Now to me, this seems stupid. I honestly can't believe I got marked down, when this does the exact same thing that mine does with a lot more overhead.
It reminds me of how in C# people always do this:
public class Example
{
private int _myint;
public int MyInt
{
get
{
return this._myint;
}
set
{
this._myint = value;
}
}
}
I mean I GET why they do it, maybe later on they want to validate the data in the setter or increment it in the getter. But why don't you people just do THIS UNTIL that situation arises?
public class Example
{
public int MyInt;
}
Sorry this is kind of a rant and not really a question, but the redundancy is maddening to me. Why are getters and setters so loved, when they are unneeded?
| It's an issue of "best practice" and style.
You don't ever want to expose your data members directly. You always want to be able to control how they are accessed. I agree, in this instance, it seems a bit ridiculous, but it is intended to teach you that style so you get used to it.
It helps to define a consistent interface for classes. You always know how to get to something --> calling its get method.
Then there's also the reusability issue. Say, down the road, you need to change what happens when somebody accesses a data member. You can do that without forcing clients to recompile code. You can simply change the method in the class and guarantee that the new logic is utilized.
|
1,712,641 | 1,717,575 | Boost.Asio documentation is non-existent. What do these errors mean? | I'm struggling with two errors with Boost.Asio.
The first occurs when I try to receive data on a socket:
char reply[1024];
boost::system::error_code error;
size_t reply_length = s.receive(boost::asio::buffer(reply, 1024), 0, error);
if (error) cout << error.message() << endl; //outputs "End of file"
The second occurs when I try to create an ip::tcp::socket from a (valid!) native socket:
boost::asio::io_service ioserv;
boost::asio::ip::tcp::socket s(ioserv);
boost::system::error_code error;
s.assign(boost::asio::ip::tcp::v4(), nativeSocket, error);
if (error) cout << error.message() << endl; //outputs "The parameter is incorrect"
With all these troubles an no documentation to turn to, I am tempted to go back to BSD sockets, but I'm having my own problems there...so if anyone can help, I'd really appreciate it.
EDIT: Regarding number 2, nativeSocket is declared thusly:
SOCKET nativeSocket = INVALID_SOCKET;
nativeSocket = accept(svr_sock, (struct sockaddr*)&sin, &size);
After that, a few other things are done to the socket -- namely, setting it as non-blocking using ioctlsocket, and using setsockopt for SO_LINGER and SO_OOBINLINE.
| This is not a complete solution to your second problem by any means. Any errors that it generates should be mapped into a boost::system::error_code, but I don't find anything like it in boost/system/error_code.hpp, so I'm at a loss as to what exactly it is supposed to mean.
But, after looking through the code for boost 1.39, assign is eventually handed off to either detail::reactive_socket_service< Protocol, Reactor >.assign (or detail::win_iocp_socket_service<Protocol>, if you're using windows). It can only be producing an error in two places in boost/asio/detail/reactive_socket_service.hpp:
if (is_open(impl))
{
ec = boost::asio::error::already_open;
return ec;
}
or
if (int err = reactor_.register_descriptor(
native_socket, impl.reactor_data_))
{
ec = boost::system::error_code(err,
boost::asio::error::get_system_category());
return ec;
}
Since, you're not getting an already_open error, the error must from the second bit of code. The reactor type comes from a sequence of ifdef/elif pairs in boost/asio/stream_socket_service.hpp, and of those available only the register_descriptor function in epoll_reactor can throw any error (and of course detail::win_iocp_socket_service<Protocol>.assign can, also). The error in epoll_reactor comes from sys/epoll.h, specifically:
int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, descriptor, &ev);
if (result != 0)
return errno;
In the windows implementation, the related code is
if (iocp_service_.register_handle(native_socket.as_handle(), ec))
return ec;
I think this is the origin of your error, but honestly, I can't trace it past this point.
|
1,712,667 | 1,712,674 | What does "#include <sndfile.h>" mean? | What does "#include <sndfile.h>" mean? (Sorry I'm c\c++ nub)
By the way I know ActionScript and HTML.
| That is a preprocessor directive to include the header file called 'sndfile.h'. Basically it means include the contents of that file in the place of that directive, which will usually give you function definitions for an object file that will be linked with your source code, and often defines constants, etc....
See wikipedia
|
1,712,696 | 1,713,128 | Boost::Regex DOTALL flag | Is there a DOTALL matching flag for boost::regex? The documentation shows:
static const match_flag_type match_not_dot_newline;
static const match_flag_type match_not_dot_null;
but no mention of regular DOTALL.
I'm trying to match a python regular expression written as
re.compile(r'<a(.*?)</a>', re.DOTALL)
| I think what you're looking for is the mod_s syntax_option_type. You can also use the inline modifier, (?s).
|
1,712,701 | 1,712,714 | Is boost::make_shared obsolete now? | Is boost::make_shared obsolete now? Haven't found its definition in 1.35.
| Its in the 1.4 docs: http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/make_shared.html
It appears to have been added in version 1.39
|
1,712,713 | 1,712,754 | CUDA: NVCC gives controlling expression is constant warning on assert | I get the warning controlling expression is constant on assert statement like this:
assert(... && "error message");
Why this warning on this assert? How can I suppress this warning?
NVCC is the NVIDIA cuda compiler, I think it is based on LLVM. Why does it give this warning, when the same compiles fine with GCC or Visual C++ compilers?
| A portable alternative (possibly wrapped in a macro) would be something like:
{
const bool error_message = true;
assert([...] && error_message);
}
To clear up what i meant:
#define myAssert(msg, exp) { const bool msg(true); assert(msg && (exp)); }
// usage:
myAssert(ouch, a && b);
... gives e.g.:
assertion "ouch && (a && b)" failed [...]
|
1,712,753 | 1,712,776 | C++ Win32 API Controls messages | im starting with Win32 api, im adding a button control to my main window with the flowing code:
HWND boton = CreateWindow(
"BUTTON", //
"Caption", //
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles.
250, // x position.
10, // y position.
100, // Button width.
40, // Button height.
hwnd, // Parent window.
NULL, // No menu.
(HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE),
NULL); // Pointer not needed.
how can i assign it an id, so i can get the message on the loop, in the message loop im trying to catch the message as WM_COMMAND but i don't get any result i've tried with WM_NOTIFY too.
| To assign it an ID, you have to use the hMenu parameter. If you have specified that the window will be a child (i.e. with WS_CHILD), the hMenu parameter will be interpreted as an integer ID for the window. Also, provide the BS_NOTIFY style.
HWND boton = CreateWindow (
"BUTTON",
WS_TAPSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY,
250, 10, 100, 40,
hwnd,
(HMENU)101, // This becomes the Control ID
(HINSTNACE)GetWindowLong(hwnd,GWL_HINSTANCE),
NULL);
EDIT: Special shout goes out to Heath Hunnicutt for the info on BS_NOTIFY.
|
1,712,756 | 1,712,803 | "g++" and "c++" compiler | I just found on my Ubuntu, there are two different C++ compilers: /usr/bin/g++ and /usr/bin/c++. I am not familiar with the latter, but man c++ just jumps to the manpage of gcc. I wonder what is their difference as C++ compilers?
| This is typical Ubuntu symlink mayhem.
If you ls -l /usr/bin/c++, you will see it is actually a symbolic link. to:
/etc/alternatives/c++
Which in turn, is also a symbolic link to:
/usr/bin/g++
So, on Ubuntu systems, c++ is g++. The reasoning behind the link indirection is that there are multiple packages that could provide a c++ compiler (such as different versions of g++). You'll see this a lot on Ubuntu. For example, qmake is a link to a file in /etc/alternatives, which is (on my system) a link back to /usr/bin/qmake-qt3.
|
1,712,801 | 1,712,813 | C++ Threadsafe Singleton (NOT FOR INIT) | So I want to access a singleton class from multiple threads. Conceptually I'd think that calling non-const methods on this singleton instance would be not thread-safe. I've been looking online and no one seems to address this possible issue. Is there an actual problem with this, is the only issue with Singleton's thread-safety, the initialization of the instance variable?
| You are correct, calling a non-const methods or methods that depend on instance data that could be modified by other threads must be syncronized.
|
1,713,120 | 1,713,181 | C/C++ Integer Operation | I found by chance that
int a = (h/2)*w+ ( (h+1)/2-h/2 ) * (w+1)/2 ;
is equal to
int b = (w * h + 1) / 2 ;
when w and h are positive integers (assume no overflow).
Can you show me why these 2 are the same?
edit : integer -> positive integer.
| Actually this is a math problem: (integer)/2 should be interpreted as floor. So, the problem is:
Show that floor(h/2)*w + ( floor((h+1)/2) - floor(h/2) ) * floor((w+1)/2) is equivalent to floor((w*h+1)/2)
Proof:
h = 2k, w = 2l: (both numbers are even) ...
h = 2k + 1, w = 2l: ...
h = 2k, w = 2l + 1: ...
h = 2k + 1, w = 2k + 1: ...
A hint: floor((2k+1)/2) == k. You can easily show the equivalence.
For example, the case 4:
a) floor(2k+1/2)*(2l+1) + ( floor((2k+2)/2) - floor((2k+1)/2) ) * floor((2l+2)/2) = 2kl+k + (k+1 - k)*(l+1) = 2kl + k + l + 1
b) floor(((2k+1)*(2l+1)+1)/2) = floor((4kl+2k+2l+2)/2) = 2kl + k + l + 1
Therefore, the two equations are equivalent.
|
1,713,171 | 1,713,427 | Getting return value from a boost::threaded member function? | I have a worker class like the one below:
class Worker{
public:
int Do(){
int ret = 100;
// do stuff
return ret;
}
}
It's intended to be executed with boost::thread and boost::bind, like:
Worker worker;
boost::function<int()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.join();
My question is, how do I get the return value of Worker::Do?
Thanks in advance.
| I don't think you can get the return value.
Instead, you can store the value as a member of Worker:
class Worker{
public:
void Do(){
int ret = 100;
// do stuff
m_ReturnValue = ret;
}
int m_ReturnValue;
}
And use it like so:
Worker worker;
boost::function<void()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.join();
//do something with worker.m_ReturnValue
|
1,713,214 | 1,721,230 | How to use C++ in Go | In the new Go language, how do I call C++ code? In other words, how can I wrap my C++ classes and use them in Go?
| Update: I've succeeded in linking a small test C++ class with Go
If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in $GOROOT/misc/cgo/gmp).
I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.
Here's an example:
I have a C++ class defined as:
// foo.hpp
class cxxFoo {
public:
int a;
cxxFoo(int _a):a(_a){};
~cxxFoo(){};
void Bar();
};
// foo.cpp
#include <iostream>
#include "foo.hpp"
void
cxxFoo::Bar(void){
std::cout<<this->a<<std::endl;
}
which I want to use in Go. I'll use the C interface
// foo.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Foo;
Foo FooInit(void);
void FooFree(Foo);
void FooBar(Foo);
#ifdef __cplusplus
}
#endif
(I use a void* instead of a C struct so the compiler knows the size of Foo)
The implementation is:
//cfoo.cpp
#include "foo.hpp"
#include "foo.h"
Foo FooInit()
{
cxxFoo * ret = new cxxFoo(1);
return (void*)ret;
}
void FooFree(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
delete foo;
}
void FooBar(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
foo->Bar();
}
with all that done, the Go file is:
// foo.go
package foo
// #include "foo.h"
import "C"
import "unsafe"
type GoFoo struct {
foo C.Foo;
}
func New()(GoFoo){
var ret GoFoo;
ret.foo = C.FooInit();
return ret;
}
func (f GoFoo)Free(){
C.FooFree(unsafe.Pointer(f.foo));
}
func (f GoFoo)Bar(){
C.FooBar(unsafe.Pointer(f.foo));
}
The makefile I used to compile this was:
// makefile
TARG=foo
CGOFILES=foo.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
foo.o:foo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
cfoo.o:cfoo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
CGO_LDFLAGS+=-lstdc++
$(elem)_foo.so: foo.cgo4.o foo.o cfoo.o
gcc $(_CGO_CFLAGS_$(GOARCH)) $(_CGO_LDFLAGS_$(GOOS)) -o $@ $^ $(CGO_LDFLAGS)
Try testing it with:
// foo_test.go
package foo
import "testing"
func TestFoo(t *testing.T){
foo := New();
foo.Bar();
foo.Free();
}
You'll need to install the shared library with make install, then run make test. Expected output is:
gotest
rm -f _test/foo.a _gotest_.6
6g -o _gotest_.6 foo.cgo1.go foo.cgo2.go foo_test.go
rm -f _test/foo.a
gopack grc _test/foo.a _gotest_.6 foo.cgo3.6
1
PASS
|
1,713,218 | 1,713,232 | Fastest way to read a file line by line with an arbitrary number of characters in each | Ok, I'm trying to figure out which way would be faster to read a text file that I'm working with. The contents of the file look like this
1982 3923 3542 4343
2344 3453 2
334 423423 32432 23423
They're basically just an arbitrary number of int numbers and I need to read line by line. Would it be better to use getline or the insertion (>>) operator? I, personally, think it would be a lot easier to implement by using the insertion operator but I don't know how I would make the program so that it reads all of the int numbers in the same line until it reaches the end. I was thinking of setting it up like the following:
ifstream input;
input.open("someFile.txt");
if (input) {
char* ch;
while (ch != '\n\)
getline(input, buffer, ' ')
The only problem is that I have to do a conversion to an int, then put each int in an array. My desired end goal is to produce a two-dimensional array where each line of int's is an array of int's. Any suggestions as to the best implementation is appreciated!
| I would keep it real simple:
ifstream in(...);
string line;
while (getline(in, line)) {
istringstream line_in(line);
while (line_in) {
int val = 0;
if (line_in >> val) {
// Do something with val
}
}
// eol
}
|
1,713,468 | 1,713,502 | Constructor with custom classes as arguments, throws 'No matching function for call to...' | I'm trying to create a constructor for a custom type, but for some reason, it's trying to call, what I'm guessing is the constructor in the constructor definition of another class.. Couldn't find anything which fits the same symptoms I'm having in any other questions, also as I may not know what I'm looking for.
When I call:
LatLngBounds clusterBounds(&boundsNorthEast, &boundsSouthWest);
in main.cpp, in LatLngBounds.cpp I get "No matching funciton for call to 'LatLng:LatLng()" thrown twice on the line for:
LatLngBounds::LatLngBounds(LatLng &newSouthWest, LatLng &newNorthEast)
Anyone got any ideas?
Drew J. Sonne.
IDE: Xcode 3.2 (Targeted to Debug 10.5)
OS: OSX 10.6
Compiler: GCC 4.2
Arch: x86_64
main.cpp:
std::vector<std::string> argVector;
... fill up my argVector with strings..
vector<double> boundsVector = explodeStringToDouble(argVector[i]);
LatLng boundsNorthEast(0, boundsVector[0], boundsVector[1]);
LatLng boundsSouthWest(0, boundsVector[2], boundsVector[3]);
LatLngBounds clusterBounds(&boundsNorthEast, &boundsSouthWest);
LatLngBounds.h
#ifndef __LATLNGBOUNDS
#define __LATLNGBOUNDS
#include "LatLng.h"
class LatLngBounds {
private:
LatLng northEast;
LatLng southWest;
public:
LatLngBounds(LatLng&,LatLng&);
};
#endif
LatLngBounds.cpp
#include "LatLngBounds.h"
#include "LatLng.h"
LatLngBounds::LatLngBounds(LatLng &newSouthWest, LatLng &newNorthEast)
{
this->southWest = newSouthWest;
this->northEast = newNorthEast;
};
LatLng.h
#ifndef __LATLNGDEF
#define __LATLNGDEF
class LatLng {
public:
LatLng(int,double,double);
private:
double lat, lng;
int id;
};
#endif
LatLng.cpp
#include "LatLng.h"
LatLng::LatLng(int newId, double newLat, double newLng)
{
/* Grab our arguments */
id = newId;
lat = newLat;
lng = newLng;
};
| In your class you have two instances of LatLng objects. In order to construct your object, the compiler also needs to construct them.
class LatLngBounds {
private:
LatLng northEast;
LatLng southWest;
Since class LatLng does not have a default constructor, you need to explicitly tell the compiler how to construct those object:
LatLngBounds::LatLongBounds( ..constructor args.. )
: northEast( ..args for northEast constructor call ..),
southWest( ..args for southWest constructor call ..)
{
}
|
1,713,476 | 1,713,494 | How should C++ methods that manipulate static data members be defined? | I have a C++ class which contains only static data members.
I noticed the compiler is OK if I define the access methods as const, as static, or as "regular" - so all seem to work.
My question is what is the correct/better practice in this case?
Thanks!
| Static accessors for static data members.
|
1,713,653 | 1,713,711 | BOOST_FOREACH & templates without typedef | When I work with BOOST_FOREACH, there isn't a problem with simple templates as vector. But when I try to iterate through map > for example I need to typedef the element type.
Is there any workaround?
| There is a problem because it is a macro, and therefore cannot handle types containing commas (preprocessor doesn't know about templates).
You can also declare the variable before the loop, see documentation.
std::map<int, double> my_map;
//1)
typedef std::pair<int, double> MyPair;
BOOST_FOREACH(MyPair p, my_map) { ... }
//2)
std::pair<int, double> p;
BOOST_FOREACH(p, my_map) { ... }
Edit:
There is a further complication with std::map in particular: the value_type is not std::pair<Key, Value>, but std::pair<const Key, Value>.
Hence, if you go with the typedef, a more proper way (and the only way if you want to use a reference in the foreach loop) is to use
typedef std::pair<const int, double> MyPair;
//or
typedef std::map<int, double>::value_type MyPair;
BOOST_FOREACH(MyPair& ref, my_map) { ... }
However, that won't work if you want to use a variable declared before the loop, since you can't assign to a std::pair<const int, double> instance later (can't assign to the const field), in which case you can only use pair<int, double> as boost's manual shows.
|
1,713,657 | 1,713,818 | Wrapping dynamic array into STL/Boost container? | I need to wrap a dynamically allocated array(from a = new double[100] for example) into std::vector(preferably) without copying the array.
This restriction is imposed by that the array I want to wrap is mmaped from a file, so just doing vector(a, a+size) will double the memory usage.
Is any tricks to do that?
| One of the best solutions for this is something like STLSoft's array_proxy<> template. Unfortunately, the doc page generated from the source code by doxygen isn't a whole lot of help understanding the template. The source code might actually be a bit better:
http://www.stlsoft.org/doc-1.9/array__proxy_8hpp-source.html
The array_proxy<> template is described nicely in Matthew Wilson's book, Imperfect C++. The version I've used is a cut-down version of what's on the STLSoft site so I didn't have to pull in the whole library. My version's not as portable, but that makes it much simpler than what's on STLSoft (which jumps through a whole lot of portability hoops).
If you set up a variable like so:
int myArray[100];
array_proxy<int> myArrayProx( myArray);
The variable myArrayProx has many of the STL interfaces - begin(), end(), size(), iterators, etc.
So in many ways, the array_proxy<> object behaves just like a vector (though push_back() isn't there since the array_proxy<> can't grow - it doesn't manage the array's memory, it just wraps it in something a little closer to a vector).
One really nice thing with array_proxy<> is that if you use them as function parameter types, the function can determine the size of the array passed in, which isn't true of native arrays. And the size of the wrapped array isn't part of the template's type, so it's quite flexible to use.
|
1,713,790 | 1,717,124 | QT drawing without erasing widget | I have a QWidget-derived class. In the constructor I say:
setPalette(QPalette(QColor(250,250,200)));
setAutoFillBackground(true);
Then in my widget's paintEvent() I say:
QPainter painter(this);
painter.drawRect(1,2,3,4);
There is also an updateNow() slot...which just calls update(). How can I make sure my palette doesn't get erased after that update call?
| I don't have any problems with the following:
#include <QApplication>
#include <QWidget>
#include <QPalette>
#include <QPaintEvent>
#include <QPainter>
class Test : public QWidget
{
public:
Test()
{
setPalette(QPalette(QColor(250, 250, 200)));
setAutoFillBackground(true);
}
protected:
virtual void paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.drawRect(10, 20, 30, 40);
}
virtual void mousePressEvent(QMouseEvent*)
{
update();
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Test myTest;
myTest.show();
return app.exec();
}
The rectangle draws, and stays after I click, which triggers update. What are you seeing?
|
1,714,168 | 1,714,881 | GStreamer gst_element_factory_make fails | I'm trying out a GStreamer test application, but at runtime the following line fails:
demuxer = gst_element_factory_make ("oggdemux", "ogg-demuxer"); // returns NULL
I am using MacOSX and installed GStreamer, libogg and vorbis-tools through MacPorts. So I don't see why it fails.
Any suggestions on how to make it work?
EDIT: SOLVED!
The problem was that I needed to install the autodetect plugin from the gst-plugins-good package.
Here's a list of actions that made it work:
Remove the MacPorts installation:
sudo port uninstall gstreamer
Add the following line to ~/.profile
export PKG_CONFIG_PATH=/opt/local/lib/pkgconfig:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig
Download gstreamer, gstreamer-plugins-base and gstreamer-plugins-good sources.
Build and install gstreamer (./configure, make, make install)
Build and install gstreamer-plugins-base (./configure, make, make install)
And for gstreamer-plugins-good I only built the autodetect package because building all resulted in errors for some plugins that I don't need or care about now. I did it like this:
./configure
cd gst/autodetect/
make
sudo make install
Right now the program builds and runs. I don't seem to be getting any audio output however :( but that's another issue.
| Reading gstelementfactory.c (GStreamer version 0.10.25) line 463 (gst_element_factory_make function definition), there are three errors which cause a NULL return:
The first argument ('factoryname') is NULL (obviously OK in your code)
The named element factory could not be found (the function gst_element_factory_find returned NULL)
The element instance could not created (the function gst_element_Factory_create returned NULL)
The code performs substantial logging so if you are able to turn this on then you may get further hints as to the underlying problem.
To check that the oggdemux plugin is configured correctly, try running:
gst-inspect oggdemux
If this doesn't return a result, try using gst-register to register it.
|
1,714,539 | 1,714,621 | Problem with libraries using winsock.h | I have a project that uses Boost.Asio and the Media-Decoding-Samples that come with the Intel IPP-Library. The problem is the following. If I compile the project without defining WIN32_LEAN_AND_MEAN, Asio complains with the infamous "winsock.h already included" error. If I define the macro, a header in the other library has undefined types, because it relies on windows.h including winsock.h. I tried adding winsock.h to that header manually, but this makes Boost.Asio cry out again. The only solution I can think of would be to go through every compilation unit and make sure that Asio is always included first. Due to the size and complexity of the project (and the uglyness of that solution) I would like to find a better way.
Thanks in advance !
| you can get around this if you split up your source and make sure not to use some kind of common header in your application in which you incude both Asio and IPP. So the source files needing Asio include Boost headers, the source files needing IPP include the IPP headers, but the header files for your classes that need to refer to both should not include any external headers, and use forward declarations if needed.
|
1,714,593 | 1,714,671 | C++ - is a pointer to a single value same as a size 1 dynamic array? | I have this snippet of code which I am considering to simplfy:
if (numberOfResults > 1)
{
trackResult_ = new TrackResult[numberOfResults];
for (int i=0; i < numberOfResults; i++)
{
// Make a deep copy
TrackResult tempResult = result[i];
TrackResult * clone = new TrackResult(tempResult);
trackResult_[i] = *clone;
}
storeJointResults(trackResult_, numberOfResults);
}
else
{
trackResult_ = new TrackResult(*result);
}
(I have 'no choice' but to use a simple dynamic array here. Vectors are deemed 'too complicated' at my workplace)
I am wondering if I can get away with
// even if we just have one result, we init an array size of one
trackResult_ = new TrackResult[numberOfResults];
However, I have in several points check for the number of results and act accordingly
if (numberOfResults_ == 1)
{
velocity = trackResult_.velocity;
}
Would those code still work? If not, why?
| The array of size 1 does not need to be a special case.
When you allocate a dynamic array you are given a pointer to the first element. If the array is of size 1, this is pretty much indistinguishable from just having allocated a single instance of the object.
Your special case usage would work if you changed the . to an ->
However I'd recommend not special-casing it and just use trackResult_[0].velocity
|
1,714,874 | 1,714,974 | Is returning a temp-object by reference possible | is it possible to return a reference from a function like in this example code:
string &erase_whitespace(string &text)
{
text.erase(**etc.**);
return text;
}
Call:
string text = erase_whitespace(string("this is a test"));
cout << test;
Does this code work? On Visual C++ it does not crash but it looks wrong.
Thanks
| From § 12.2.3 of the C++ 2003 standard (draft)
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.
§ 12.2.4:
There are two contexts in which temporaries are destroyed at a different point than the end of the full-
expression. ...
§ 12.2.5:
The second context is when a reference is bound to a temporary. The temporary to which the reference is
bound or the temporary that is the complete object to a subobject of which the temporary is bound persists
for the lifetime of the reference except as specified below. ... A temporary bound to a reference
parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.
§8.5.3.5 is what determines when the reference must be a const type. It is possible for a temporary to be bound to a non-const reference if the temporary is an instance of a class that has a conversion operator that returns an appropriate reference (that's a mouthful). An example might be easier to understand:
class Foo {
...
operator Bar&() const;
...
void baz(Bar &b);
...
baz(Foo()); // valid
baz(Bar()); // not valid
The last line isn't valid because of § 12.3.2.1, which states "A conversion function is never used to convert [an ...] object to the [...] same object type (or a reference to
it)". You might be able to make it work using casting via an ancestor of Bar and a virtual conversion function.
An assignment is an expression (§ 5.17), thus the full-expression (§ 1.9.12) in your code is the assignment. This gives the following sequence (forgetting for the moment that a temporary string probably can't be bound to a non-const reference):
A temporary string is created
The temporary is bound to the string& text argument of erase_whitespace
erase_whitespace does its thang.
erase_whitespace returns a reference to the temporary
The temporary is copied to string text
The temporary is destroyed.
So all is kosher in this case. The problem case, as Mike Seymour points out, would be assigning the result of erase_whitespace to a reference. Note that this likely wouldn't cause an immediate problem, as the area that stored the string probably contains the same data it did before the temporary was destroyed. The next time something is allocated on the stack or heap, however...
|
1,715,183 | 1,715,232 | Ill formed code snippets | can somebody please tell me the difference between the following two code snippets:
//Code snippet A: Compiles fine
int main()
{
if(int i = 2)
{
i = 2 + 3;
}
else
{
i = 0;
}
}
//Code Snippet B: Doesn't compile :(
int main()
{
if((int i = 2))
{
i = 2 + 3;
}
else
{
i = 0;
}
}
If you notice the diff is just an extra parenthesis at if statement. I am using g++ compiler.Error is "expected primary-expression before âintâ"
| Section 6.4 of the C++ standard (draft n2914 of c++0x) has this to say about the format of if statements:
Selection statements choose one of several flows of control.
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
condition:
expression
type-specifier-seq attribute-specifieropt declarator = initializer-clause
type-specifier-seq attribute-specifieropt declarator braced-init-list
That bit at the end means a condition can be either an expression or a decalarator-type construct.
And the minute the parser hits that second parenthesis, it becomes an expression, so no declarations allowed, I'm afraid.
The snippet:
if (int i = 2) { ... } else { ... }
is perfectly valid C++ in which the if section defines an integer i for the duration of the if/else and sets it to 2. It then uses that 2 as the input to the if (2 is always true, being non-zero).
The snippet if((int i = 2)) is no different syntactically to int x = (int i = 2;); if (x) which is not valid C++.
|
1,715,195 | 1,715,258 | How to create a Visual Studio 2008 C++ project template? | I've used the "Export Template" feature numerous times for C#, ASP.NET, WinForms, etc. projects. Today I tried to do it for a C++ project and noticed "Export Template" was grayed out in the File-menu.
Is it not possible to create C++ template projects in VS 2008 ?
| yes it is: the ones you see already when creating a new project are in $VsInstallDir)/vcprojects. To create one yourself, you basically create a .vsz and a.vsdir file in which you describe your project template, a bunch of script/html files for your own wizard, and the template files itself (.vcproj, additional content etc.). It is not very easy, but it is possible and very handy once done. Complete explanation is on MSDN, it's too much to elaborate on here.
Same goes for project items/classwizards, they all can be customised.
|
1,715,304 | 1,715,350 | Generating n-digit numbers sequenced by sum of individual digits (without recursion) | I'm looking to generate all possible values of n-digit number, in the following order, where the sequence is dictated by the sum of the individual digits.
For example, with n = 3:
111 sum = 3
112 sum = 4
121
211
122 sum = 5
212
221
113
131
311
114 sum = 6
141
411
:::
999 sum = 27
The order within the sum group is not important.
Any help, ideas would be appreciated
| You can always turn a recursive problem into an iterative one if you maintain your own stack of important data - that's if the reason for avoiding recursion is that the language doesn't support it.
But, if the language does support it, then recursive solutions are far more elegant.
The only other reason I can think of for avoiding recursion is limited stack depth. In that case an iterative conversion of a recursive solution will mitigate the problem by not requiring as much stack space.
But you need to understand that the stack depth for processing n numbers only grows relative to log10n. In other words, you only get an extra stack frame per digit (only 10 stack frames to handle the full range of 32-bit integers).
Aside: by the time you get to that point, you're algorithm will be taking so long to run, stack frames will be the least of your problems :-)
Here's a recursive Python solution:
def recur (numdigits,sum,pref="",prefsum=0):
if numdigits == 0:
if prefsum == sum:
print "%s, sum=%d"%(pref,prefsum)
else:
for i in range (1,10):
recur (numdigits-1,sum,"%s%d"%(pref,i),prefsum+i)
def do (n):
for i in range (1,n*9+1):
recur (n,i)
do (2)
do (3)
which outputs (for 2 and 3):
11, sum=2 111, sum=3
12, sum=3 112, sum=4
21, sum=3 121, sum=4
13, sum=4 211, sum=4
22, sum=4 113, sum=5
31, sum=4 122, sum=5
14, sum=5 131, sum=5
23, sum=5 212, sum=5
32, sum=5 221, sum=5
41, sum=5 311, sum=5
15, sum=6 114, sum=6
: : : :
89, sum=17 989, sum=26
98, sum=17 998, sum=26
99, sum=18 999, sum=27
Keep in mind that solution could still be optimized somewhat - I left it in its initial form to show how elegant recursion can be. A pure-iterative solution follows, but I still prefer the recursive one.
Run the following program and use sort and awk under UNIX to get the desired order. For example:
go | sort | awk '{print $2}'
Note that this uses external tools to do the sorting but you could just as easily sort within the C code (memory permitting).
#include <stdio.h>
int main (void) {
int i, sum, carry, size;
int *pDigit;
// Choose your desired size.
size = 2;
// Allocate and initialise digits.
if ((pDigit = malloc (size * sizeof (int))) == NULL) {
fprintf (stderr, "No memory\n");
return 1;
)
for (i = 0; i < size; i++)
pDigit[i] = 1;
// Loop until overflow.
carry = 0;
while (carry != 1) {
// Work out sum, then output it with number.
// Line is sssssssssssssssssss ddddd
// where sss...sss is the fixed-width sum, zero padded on left (for sort)
// and ddd...ddd is the actual number.
sum = 0;
for (i = 0; i < size; i++)
sum += pDigit[i];
printf ("%020d ", sum);
for (i = 0; i < size; i++)
printf ("%d", pDigit[i]);
printf ("\n");
// Advance to next number.
carry = 1;
for (i = 0; i < size; i++) {
pDigit[size-i-1] = pDigit[size-i-1] + carry;
if (pDigit[size-i-1] == 10)
pDigit[size-i-1] = 1;
else
carry = 0;
}
}
return 0;
}
|
1,715,390 | 1,715,527 | Should I use a const reference or a boost::shared_ptr? | I have created some C++ classes to model a Solitaire game as a learning exercise.
I have classes for the SolitaireGame, a CardStack (one of the 10 piles of cards on the board ) and a Card. My current model states that the SolitaireGame owns a vector of 104 Card objects - which I call the 'shoe'. The SolitaireGame also keeps track of 10 CardStacks which are essentially deque's of addresses of Card objects stored in the shoe. The Deck and Hand inherit from CardStack. I pass the cards from Deck, to Hand to Cascade by means of pointers to original objects stored in the Shoe.
According to a number of answers I received to this question, I should not be passing the Card's around by pointers, but should be using const references. The reason being that objects stored in vectors can have their addresses moved about, so storing their addresses anywhere is a no-no. I recently started looking at boost::sharedptr. What do people think about using shared_ptr to Card here?
Here are simplified versions of the classes:
class SolitaireGame
{
public:
SolitaireGame::SolitaireGame( int numsuits );
private:
vector<Card> _shoe;
Deck _deck;
Hand _hand;
CardStack _cols[NUM_COLUMNS];
int _numsuits;
GameState gamestate;
};
class CardStack
{
public:
CardStack(){ cout << "CardStack constructor" << endl; }
CardStack( const CardStack& );
CardStack( const deque<Card *> &d );
~CardStack(){ }
virtual Card * PullCard( Face f );
virtual void PushCard( Card * c );
Card * CardAt( int i ) const;
Card * Top() const;
deque<Card *>::iterator Begin() { return _cards.begin(); }
deque<Card *>::iterator End() { return _cards.end(); }
int Size() const;
CardStack& operator=( const CardStack& rhs );
friend std::ostream& operator<<(std::ostream &os, const CardStack &obj);
private:
deque<Card *> _cards;
};
|
The reason being that objects stored in vectors can have their addresses moved about, so storing their addresses anywhere is a no-no.
Storing (const) references is just as bad as storing pointers for the same reason. If the size of the vector does not change as long as other objects hold pointers to the objects therein, you should be safe.
When programming in C++, you should always decide who “owns” an object, e.g. who is responsible to delete it when it is no longer needed. If there is no natural object owner, you could resort to smart pointers like boost::shared_ptr that use reference counting or garbage collection to manage the object's lifetime.
In your case, it is pretty obvious that the SolitaryGame instance owns all cards. Moreover, the number of cards in the game is fixed. Therefore you can easily pass pointers of your cards to objects that are dependent of the game instance.
Once the game is deleted, all cards will get deleted and remaining pointers will be invalid, but at this time, other objects holding card pointers should get deleted, too.
|
1,715,626 | 1,715,652 | Is it possible to set an application's windows compatibility mode at run-time? | We are using a 3rd party library that sometimes does not work correctly on Win7. WE know how to configure this at installation time, but we'd also like to consider setting it at run time. Is this possible, or does that context have to be set prior to launch? (I think there is a slim to none chance, but figured I would ask anyway)
(C++ application - not that it really matters)
| The compatibility settings can't be changed once the application is running.
However, what you could do is have a launcher application that makes sure the compatibility settings are correct and then launches your application. Of course, you need to make sure the launcher application doesn't have compatibility problems.
|
1,715,674 | 1,715,709 | boost bind compilation error | class A
{
bool OutofRange(string& a, string& b, string c);
void Get(vector <string>& str, string& a, string& b);
}
void A::Get(vector <string>& str, string& a, string& b)
{
str.erase(
std::remove_if (str.begin(), str.end(), BOOST_BIND(&A::OutOfRange, a, b, _1)),
str.end()
);
}
I am getting errors like:
Error 7 error C2825: 'F': must be a class or namespace when followed by '::' File:bind.hpp
Error 8 error C2039: 'result_type' : is not a member of '`global namespace'' t:\3rdparty\cpp\boost\boost-1.38.0\include\boost\bind.hpp 67
Can someone tell me what I am doing wrong?
| A::OutOfRange is a function of 4 arguments - implicit *this being the first argument, which is missing in your bind clause
|
1,715,714 | 1,715,914 | Is there a better way? While loops and continues | There are many functions within the code I am maintaining which have what could be described as boilerplate heavy. Here is the boilerplate pattern which is repeated ad nausea throughout the application when handling DB I/O with a cursor:
if( !RowValue( row, m_InferredTable->YearColumn(), m_InferredTable->YearName(), m_InferredTable->TableName(), value )
|| !IsValidValue( value ) )
{
GetNextRow( cursor, m_InferredTable );
continue;
}
else
{
value.ChangeType(VT_INT);
element.SetYear( value.intVal );
}
The thing is not all of these statements like this deal with ints, this "element" object, the "year" column, etc. I've been asked to look at condensing it even further than it already is and I can't think of a way to do it. I keep tripping over the continue statement and the accessors of the various classes.
Edit: Thanks to all those that commented. This is why I love this site. Here is an expanded view:
while( row != NULL )
{
Element element;
value.ClearToZero();
if( !GetRowValue( row, m_InferredTable->DayColumn(), m_InferredTable->DayName(), m_InferredTable->TableName(), value )
|| !IsValidValue( value ) )
{
GetNextRow( cursor, m_InferredTable );
continue;
}
else
{
value.ChangeType(VT_INT);
element.SetDay( value.intVal );
}
And things continue onward like this. Not all values taken from a "row" are ints. The last clause in the while loop is "GetNextRow."
| Okay, from what you've said, you have a structure something like this:
while (row!=NULL) {
if (!x) {
GetNextRow();
continue;
}
else {
SetType(someType);
SetValue(someValue);
}
if (!y) {
GetNextRow();
continue;
}
else {
SetType(SomeOtherType);
SetValue(someOtherValue);
}
// ...
GetNextRow();
}
If that really is correct, I'd get rid of all the GetNextRow calls except for the last one. I'd then structure the code something like:
while (row != NULL) {
if (x) {
SetType(someType);
SetValue(someValue);
}
else if (y) {
SetType(someOtherType);
SetValue(SomeOtherValue);
}
// ...
GetNextRow();
}
Edit: Another possibility would be to write your code as a for loop:
for (;row!=NULL;GetNextRow()) {
if (!x)
continue;
SetTypeAndValue();
if (!y)
continue;
SetTypeandValue();
// ...
Since the call to GetNextRow is now part of the loop itself, we don't have to (explicitly) call it each time -- the loop itself will take care of that. The next step (if you have enough of these to make it worthwhile) would be to work on shortening the code to set the types and values. One possibility would be to use template specialization:
// We never use the base template -- it just throws to indicate a problem.
template <class T>
SetValue(T const &value) {
throw(something);
}
// Then we provide a template specialization for each type we really use:
template <>
SetValue<int>(int value) {
SetType(VT_INT);
SetValue(value);
}
template <>
SetValue<float>(float value) {
SetType(VT_FLOAT);
SetValue(value);
}
This lets you combine a pair of calls to set the type and the value into a single call.
Edit: As far as cutting processing short goes, it depends -- if parsing a column is expensive (enough to care about) you can simply nest your conditions:
if (x) {
SetTypeAndValue();
if (y) {
SetTypeAndValue();
if (z) {
SetTypeAndValue();
and so on. The major shortcoming of this is that it'll get pretty deeply nested if (as you've said) you have 20+ conditions in a single loop. That being the case, I'd probably think hard about the for-loop based version I gave above.
|
1,716,274 | 1,717,015 | Fill the holes in OpenCV | I have an edge map extracted from edge detection module in OpenCV (canny edge detection). What I want to do is to fill the holes in the edge map.
I am using C++, and OpenCV libraries. In OpenCV there is a cvFloodFill() function, and it will fill the holes with a seed (with one of the location to start flooding). However, I am trying to fill all the interior holes without knowing the seeds.(similar to imfill() in MATLAB)
Q1: how to find all the seeds, so that I could apply 'cvFloodFill()'?
Q2: how to implement a 'imfill()' equivalent?
Newbie in OpenCV, and any hint is appreciated.
| According to the documentation of imfill in MATLAB:
BW2 = imfill(BW,'holes');
fills holes in the binary image BW.
A hole is a set of background pixels that cannot be reached by filling in the background from the edge of the image.
Therefore to get the "holes" pixels, make a call to cvFloodFill with the left corner pixel of the image as a seed. You get the holes by complementing the image obtained in the previous step.
MATLAB Example:
BW = im2bw( imread('coins.png') );
subplot(121), imshow(BW)
% used here as if it was cvFloodFill
holes = imfill(BW, [1 1]); % [1 1] is the starting location point
BW(~holes) = 1; % fill holes
subplot(122), imshow(BW)
|
1,716,363 | 1,716,418 | First chance exception - long at memory location? | What is this and how can I handle/fix it?
First-chance exception at 0x756fb727 in Program.exe:
Microsoft C++ exception: long at memory location 0x0018f7a4.
I am getting about a thousand of these each time I run my application. How can I track this down and fix it/
| In visual studio go to the Debug menu and select "Exceptions...". Turn on all the first chance exception handlers (they default to off).
Now when you run in the debugger it will break at the point the exception is thrown.
|
1,716,456 | 1,716,722 | Lisp as a Scripting Language in a C++ app | Hey, I've been looking at the possibility of adding a scripting language into my framework and I heard about Lisp and thought I would give it a go. Is there a VM for Lisp like Lua and Python or am I in the wrong mindset. I found CLISP here, http://clisp.cons.org/, but am not sure if this is what I am looking for.
Can anyone point me in the right direction?
| CLISP is just one implementation of Common Lisp. It's a very good implementation, and it does have some support for being embedded in other (C-based) programs, but that's not its focus and it's GPLed, which may or may not be a deal-breaker for you.
You might be interested in checking out ECL. This implementation is specifically designed to be embedded (indeed, the "E" stands for "Embeddable"!), and has numerous features that might be useful to you, including the ability to compile Common Lisp programs to C (as well as providing byte-code compilation and an interpreter).
|
1,716,472 | 1,841,769 | Using libtool to load a duplicate function name from a shared library | I'm trying to create a 'debug' shared library (i.e., .so or .dll file) that calls another 'real' shared library that has the same C API as the debug library (in this case, to emulate the PKCS#11 API). However, I'm running into trouble where the link map of the debug library is colliding with that of the real library and causing the debug library to call its own functions instead of the corresponding functions in the real library. I found a solution to this problem by using the POSIX dlmopen command, but would like to understand if the same is possible using GNU's libtool.
On my Solaris 10 system, the following code fails the assertion when a test application statically links to the debug library:
#include <dlfcn.h>
int MyFunctionName() {
int (*function_ptr)();
void *handle = dlopen("realsharedlibrary.so", RTDL_LAZY);
*(void **)(&function_ptr) = dlsym(handle, "MyFunctionName");
ASSERT(function_ptr != MyFunctionName); // Fails
return (*function_ptr)();
}
In this case, I get a function pointer to the local 'MyFunctionName' (in the debug library) instead of MyFunctionName within the real shared library.
I've discovered that it's possible to get around this problem by using the command 'dlmopen' instead of 'dlopen', and telling dlmopen to create a new link map (with the LM_ID_NEWLM parameter) when loading the real library:
int MyFunctionName() {
int (*function_ptr)();
void *handle = dlmopen(LM_ID_NEWLM, "realsharedlibrary.so", RTDL_LAZY);
*(void **)(&function_ptr) = dlsym(handle, "MyFunctionName");
ASSERT(function_ptr != MyFunctionName); // succeeds
return function_ptr(); // call real function
}
Unfortunately, dlmopen does not seem to be included within libtool (i.e., I don't see an lt_dlmopen function in libtool).
Is it possible to do the same thing using libtool commands -- that is, to create a new link map when loading the new library so that it doesn't collide with the link map of the debug library?
| I haven't found a good way to use libtool to solve this problem yet, but there's a way to avoid the Solaris-specific 'dlmopen' function by using dlopen with these flags:
void *handle = dlopen("realsharedlibrary.so", RTLD_NOW | RTLD_GROUP | RTLD_LOCAL)
Apparently, the problem of symbol-collisions is solved by using RTLD_NOW instead of RTLD_LAZY and by adding RTLD_GROUP. The RTLD_LOCAL is there because POSIX requires using either RTLD_LOCAL or RTLD_GLOBAL, or the behavior is undefined. For Solaris, the behavior is to default to RTLD_LOCAL.
The open question, though, is whether it's possible to pass these types of flags to lt_dlopen.
|
1,716,485 | 1,716,654 | Coding practices in C++, what is your pick and why? | I have a big object say MyApplicationContext which keeps information about MyApplication such as name, path, loginInformation, description, details and others..
//MyApplicationCtx
class MyApplicationCtx{
// ....
private:
std::string name;
std::string path;
std::string desciption;
struct loginInformation loginInfo;
int appVersion;
std::string appPresident;
//others
}
this is my method cloneApplication() which actually sets up a new application. there are two ways to do it as shown in Code 1 and Code 2. Which one should I prefer and why?
//Code 1
public void cloneApplication(MyApplicationCtx appObj){
setAppName(appObj);
setAppPath(appObj);
setAppAddress(&appObj); // Note this address is passed
setAppDescription(appObj);
setAppLoginInformation(appObj);
setAppVersion(appObj);
setAppPresident(appObj);
}
public void setAppLoginInformation(MyApplicationCtx appObj){
this->loginInfo = appObj.loginInfo; //assume it is correct
}
public void setAppAddress(MyApplicationCtx *appObj){
this->address = appObj->address;
}
.... // same way other setAppXXX(appObj) methods are called.
Q1. Does passing the big object appObj everytime has a performance impact?
Q2. If I pass it using reference, what should be the impact on performance?
public void setAppLoginInformation(MyApplicationCtx &appObj){
this->loginInfo = appObj.loginInfo;
}
//Code 2
public void setUpApplication(MyApplicationCtx appObj){
std::string appName;
appName += appOj.getName();
appName += "myname";
setAppName(appName);
std::string appPath;
appPath += appObj.getPath();
appPath += "myname";
setAppPath(appPath);
std::string appaddress;
appaddress += appObj.getAppAddress();
appaddress += "myname";
setAppAddress(appaddress);
... same way setup the string for description and pass it to function
setAppDescription(appdescription);
struct loginInformation loginInfo = appObj.getLoginInfo();
setAppLoginInformation(loginInfo);
... similarly appVersion
setAppVersion(appVersion);
... similarly appPresident
setAppPresident(appPresident);
}
Q3. Compare code 1 and code 2, which one should I use? Personally i like Code 1
| Short answer:
Q1: Given the size of your MyAppCtx class, yes, a significant performance hit will take place if the data is dealt with very frequently.
Q2: Minimal, you're passing a pointer.
Q3: Neither, for large objects like that you should use reference semantics and access the data through accessors. Don't worry about function call overhead, with optimizations turned on, the compiler can inline them if they meet various criteria (which I leave up to you to find out).
Long answer:
Given functions:
void FuncByValue(MyAppCtx ctx);
void FuncByRef1(MyAppCtx& ctx);
void FuncByRef2(MyAppCtx* ctx);
When passing large objects like your MyApplicationCtx, it's a good idea to use reference semantics (FuncByRef1 & FuncByRef2), passing by reference is identical in performance to passing a pointer, the difference is only the syntax. If you pass the object by value, the object is copy-constructed into the function, such that the argument you pass into FuncByValue is different from the parameter FuncByValue receives. This is where you have to be careful of pointers (if any) contained in an object that was passed by value, because the pointer will have been copied as well, so it's very possible that more than one object will point to one element in memory at a given time, which could lead to memory leaks, corruption, etc.
In general, for objects like your MyAppCtx, I would recommend passing by reference and using accessors as appropriate.
Note, the reason I differentiated between argument and parameter above is that there is a difference between a function argument and a function parameter, it is as follows:
Given (template T is used simply to demonstrate that object type is irrelevent here):
template<typename T>
void MyFunc(T myTobject);
When calling MyFunc, you pass in an argument, eg:
int my_arg = 3;
MyFunc(my_arg);
And MyFunc receives a parameter, eg:
template<typename T>
void MyFunc(T myTobject)
{
T cloned_param = T(myTobject);
}
In other words, my_arg is an argument, myTobject is a parameter.
Another note, in the above examples, there are essentially three versions of my_arg in memory: the original argument, the copy-constructed parameter myTobject, plus cloned_param which was explicitly copied as well.
|
1,716,885 | 1,716,941 | get number of CPUs in C++ MFC application | I write a little raytracer and i'd like to query how many cpu cores (or virtual cpu cores if the cpu uses hyperthreading) the current computer offers, such that i can instanciate as many threads to get better parallel rendering.
How can I do that using C++?
thanks!
| You can get the number of physical processors by calling GetSystemInfo and checking the dwNumberOfProcessors field of the SYSTEM_INFO structure. You can get the number of logical processors by calling GetLogicalProcessorInformation.
|
1,717,023 | 1,717,149 | Is this a design flaw? | Consider two classes
class A{
public:
A(){
}
~A(){
}
};
class AImpl : public A{
public:
AImpl(){
a = new AInternal();
}
AImpl(AInternal *a){
this->_a = a;
}
~AImpl(){
if(a){
delete a;
a = null;
}
}
private:
AInternal *a;
};
I am trying to hide the AInternal's implementation and expose only A's interface. Two things I see here
class A is totally empty.
Hiding is achieved basically through inheritance. I have to actually use downcasting and upcasting from A to AImpl and vice versa.
Is this a good design. Being very inexperienced in designing, I cannot see the pitfalls of it and why it is bad?
|
I am trying to hide the AInternal's implementation and expose only A's interface.
I think you are trying to do something like factory.
Here is an example:
class IA {
public:
IA() {}
virtual ~IA() {}
virtual void dosth() =0;
};
class Factory {
private:
class A : public IA {
public:
A () {}
virtual ~A() {}
void dosth() { cout << "Hello World"; }
};
public:
Factory () {}
virtual ~Factory() {}
IA*newA() { return new A; }
};
And the usage of Factory class:
Factory f;
IA*a = f.newA();
a->dosth();
return 0;
|
1,717,475 | 1,717,628 | Template class with different order or variables (Color/Pixel class) | I got two class templates Color3_t and Color4_t that store 3 and 4 color channels and look like this:
template <typename TYPE>
struct Color3_t
{
TYPE Red;
TYPE Green;
TYPE Blue;
void Zero()
{
Red = Green = Blue = 0;
}
(...)
}
Both templates have several function for inverting, swapping etc. color channels and I got another specialized templates that inherit these classes - in case the TYPE is a half float or float instead of integer.
The problem is that the order of color channels : Red,Green and Blue is currently fixed - which means that I would have to create a version of Color3_t class template for each other order of color channels (like BGR, GRB etc.). How can provide and argument with different color order - most likely that points to a color structure like below.
Color data structures for RGB and BGR color order:
template <typename TYPE>
struct ColorRGB_t
{
TYPE Red;
TYPE Green;
TYPE Blue;
};
template <typename TYPE>
struct ColorBGR_t
{
TYPE Blue;
TYPE Green;
TYPE Red;
};
and something I'd like to have - which is obviously wrong and incorrect but should give an idea what I want to achieve.
template <typename TYPE, class COLORORDER<TYPE>>
struct Color3_t : public COLORORDER<TYPE>
{
void Zero()
{
Red = Green = Blue = 0;
}
(...)
};
I also would like to access each color channel directly:
typedef Color3_t<BYTE,ColorBGR_t<BYTE>> ColorRGB8bpc;
ColorRGB8bpc oColor;
oColor.Red = 0;
instead of:
oColor.SomoObject.Red = 0;
| You Need to push the type that is stored for red/green/blue down into the Color***_t classes like so:
template <typename TYPE>
struct ColorRGB_t
{
typedef TYPE value_type;
value_type Red;
value_type Green;
value_type Blue;
};
template <typename TYPE>
struct ColorBGR_t
{
typedef TYPE value_type;
value_type Blue;
value_type Green;
value_type Red;
};
Then Color3 just take one template parameter that is one of your Color***_t types:
template <typename Order_t>
struct Color3 : public Order_t
{
typedef typename Order_t::value_type value_type;
void Zero()
{
//static cast zero here to avoid compiler warnings when value_type is a float or double
Order_t::Red = Order_t::Green = Order_t::Blue = static_cast<value_type>(0);
}
};
And you declare objects as:
Color3<ColorBGR_t<float> > c1;
Color3<ColorRGB_t<float> > c2;
Does that work for you? It avoids the overhead of indexing into an array at runtime and the Red/Green/Blue members are available directly like c1.Red = 0.0.
|
1,717,540 | 1,717,656 | Qt portable IPC: only QSharedMemory? | I'm looking for suggestions about choosing a portable way to achieve local IPC in a robust way, since i'm new to C++ and would like to avoid common pitfalls of fiddling with shared memory and locks; therefore I was thinking about message-passing style ipc.
I was planning to use qt for other reasons anyway, thus i took a peek to Qt ipc options.
if i understand correctly qt doesn't offer a completely portable message-passing ipc feature. it can use d-bus, but using it on windows would be a problem. other ways are limited to embedded linux platforms (and i would like to port this thing to AIX).
I could not find a "signal and slots" or message-passing style implementation that uses QSharedMemory and QSystemSemaphores
Thus: Am I limited to implement a feature on QSM/QSS?
what other options could i study?
posix pipes? protocol buffers? boost queues and messages ?
I'm considering to release the code under LGPL/GPL style license, does this rule out protocol buffers or boost libs?
please, again, the interface must be simple and newbie-proof (otherwise i definitely will screw up things big time for sure :) ), and so should the serialization/deserialization of types, error handling and resource disposal.
| Take a look at Boost.Interprocess which provides a lot of IPC functionality. I have used the interprocess message_queue that provides a pretty clean and easy way to do what I think you want to do.
|
1,717,650 | 1,717,742 | sort vector by more than 1 field | How do I sort the below code by name, age and score... all three fields
#include <string>
#include <vector>
#include <algorithm>
struct student_t
{
std::string name;
int age, score;
};
bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
// sort by name, age and score
}
int main()
{
std::vector< student_t > students;
// populate students
std::sort( students.begin(), students.end(), by_more_than_1_field );
}
| You have to be carefull that your sorting criteria is transitive: if x ' y then y !< x.
If it is not transitive, the sort operation result depends on the ordering of the array before the call, which you probably don't want.
bool by_more_than_1_field( student_t const &lhs, student_t const &rhs )
{
if (lhs.name < rhs.name)
return true;
else if (rhs.name < lhs.name)
return false;
else // name equals.
if (lhs. age < rhs. age )
return true;
else if (rhs. age < lhs. age )
return false;
else // age and names equals
return lhs.score < rhs.score;
}
|
1,717,665 | 1,717,707 | C++ throwing compilation error on sizeof() comparison in preprocessor #if | I have this which does not compile with the error "fatal error C1017: invalid integer constant expression" from visual studio. How would I do this?
template <class B>
A *Create()
{
#if sizeof(B) > sizeof(A)
#error sizeof(B) > sizeof(A)!
#endif
...
}
| The preprocessor does not understand sizeof() (or data types, or identifiers, or templates, or class definitions, and it would need to understand all of those things to implement sizeof).
What you're looking for is a static assertion (enforced by the compiler, which does understand all of these things). I use Boost.StaticAssert for this:
template <class B>
A *Create()
{
BOOST_STATIC_ASSERT(sizeof(B) <= sizeof(A));
...
}
|
1,717,721 | 1,717,955 | Examples of PHP In C++ | Well I want to learn C++ and at the moment I'm only familiar with PHP and Javascript. And I thought a good way to start learning would be to transfer methods in PHP to C++.
So basically I want the code snippets below in C++
The post with the best comments will get a big green tick.
Also, if you know of a good beginners tutorial please leave a comment.
So here are the bits of code I want in C++
First
$array = array('I\'m', 'learning', 'C++');
foreach($array as $word){
echo $word.' ';
}
Second
function foo($num,$ber, $add = true){
if(is_numeric($num) && is_numeric($ber)){
if(!$add){
echo $num*$ber;
}
else{
echo $num + $ber;
}
}
else{
echo 'They aren\'t numbers!';
}
}
foo(2,4, false);
| never try to learn any complex subject by 'translating' from another one, no matter how well you know the old one.
You'd only get inconsistent concepts, with the limitations of both and the advantages of none.
|
1,717,773 | 1,717,830 | Which sorting algorithm is used by STL's list::sort()? | I have a list of random integers. I'm wondering which algorithm is used by the list::sort() method. E.g. in the following code:
list<int> mylist;
// ..insert a million values
mylist.sort();
EDIT: See also this more specific question.
| The standard doesn't require a particular algorithm, only that it must be stable, and that it complete the sort using approximately N lg N comparisons. That allows, for example, a merge-sort or a linked-list version of a quick sort (contrary to popular belief, quick sort isn't necessarily unstable, even though the most common implementation for arrays is).
With that proviso, the short answer is that in most current standard libraries, std::sort is implemented as a intro-sort (introspective sort), which is basically a Quicksort that keeps track of its recursion depth, and will switch to a Heapsort (usually slower but guaranteed O(n log n) complexity) if the Quicksort is using too deep of recursion. Introsort was invented relatively recently though (late 1990's). Older standard libraries typically used a Quicksort instead.
stable_sort exists because for sorting array-like containers, most of the fastest sorting algorithms are unstable, so the standard includes both std::sort (fast but not necessarily stable) and std::stable_sort (stable but often somewhat slower).
Both of those, however, normally expect random-access iterators, and will work poorly (if at all) with something like a linked list. To get decent performance for linked lists, the standard includes list::sort. For a linked list, however, there's not really any such trade-off -- it's pretty easy to implement a merge-sort that's both stable and (about) as fast as anything else. As such, they just required one sort member function that's required to be stable.
|
1,717,780 | 1,718,009 | How to programmatically disable the auto-focus of a webcam? | I am trying to do computer vision using a webcam (the model is Hercules Dualpix). I know it is not the ideal camera to use, but I have no choice here.
The problem is the auto-focus makes it hard/impossible to calibrate the camera. Anyone knows a way to disable the auto-focus feature. Or, if someone has an idea to deal with it and calibrate the camera with the auto-focus.
| The Hercules cameras are UVC compliant, so they should work with the DirectShow Interface IAMCameraControl. You can set the focus to a specific value, and use the flags to set that you do not want it to be automatic. You can use IAMCameraControl::Get to poll the current state, because not all cameras do support turning off the focus.
IAMCameraControl *pCameraControl;
HRESULT hr;
hr = pFilter->QueryInterface(IID_IAMCameraControl, (void **)&pCameraControl);
if (hr == S_OK) {
long defaultFocusValue;
hr = pCameraControl->GetRange(CameraControl_Focus,
NULL, // min
NULL, // max
NULL, // minstep
&defaultFocusValue, // default
NULL); // capflags
hr = pCameraControl->Set(CameraControl_Focus, // property
defaultFocusValue, // value
CameraControl_Flags_Manual);
}
Focus has a range which is defined by each camera separately, so you should query it as shown to find the default value and the min, max if you want.
In this example the pFilter is a pointer to the input filter that you have from DirectShow. You can get it by enumerating the devices and finding the one you want.
|
1,717,991 | 1,718,124 | Throwing an exception from within a signal handler | We have a library that deals with many aspects of error reporting. I have been tasked to port this library to Linux. When running though my little test suite, one of the tests failed. A simplified version of the test appears below.
// Compiler: 4.1.1 20070105 RedHat 4.1.1-52
// Output: Terminate called after throwing an instance of 'int' abort
#include <iostream>
#include <csignal>
using namespace std;
void catch_signal(int signalNumber)
{
signal(SIGINT, SIG_DFL);
throw(signalNumber);
}
int test_signal()
{
signal(SIGINT, catch_signal);
try
{
raise(SIGINT);
}
catch (int &z)
{
cerr << "Caught exception: " << z << endl;
}
return 0;
}
int main()
{
try
{
test_signal();
}
catch (int &z)
{
cerr << "Caught unexpected exception: " << z << endl;
}
return 0;
}
My expectation is that the Caught exception: message will be displayed. What actually happens is that the program terminates as no catch handler appears to be present for the thrown int.
There are a few questions on SO that seem related.
I found a number of Google pages that were related.
The 'wisdom' seems to boil down to.
Ya can't throw exceptions from signal handlers, cause the signal
handler runs with its own stack, so there are no handlers defined on it.
Ya can throw exceptions from signal handlers, just reconstruct a fake
frame on the stack, and you are good to go.
Ya, we do it all the time. It works for me on platform X
Ya, that used to be available with gcc, but doesn't seem to work any
more. Try the -fnon-call-exceptions option, maybe that will work
The code works as expected on our AIX/TRU64/MSVC compiler/environments. It fails in our Linux environment.
I am looking for suggestions to help resolve this issue so the library behavior on Linux will match my other platforms, or some sort or workaround that might achieve the same sort of functionality.
Letting the program core dump on signal, is not a viable option.
| Signals are totally different than C++ exceptions. You can't use a C++ try/catch block to handle a signal. Specifically, signals are a POSIX concept, not a C++ language concept. Signals are delivered asynchronously to your application by the kernel, whereas C++ exceptions are synchronous events defined by the C++ standard.
You are quite limited in what you can do portably in a POSIX signal handler. A common strategy is to have a global flag of type sig_atomic_t which will be set to 1 in the signal handler, and then possibly longjmp to the appropriate execution path.
See here for help writing proper signal handlers.
|
1,718,430 | 2,391,016 | default WM_DESTROY not properly cleaning up child windows | I have a WTL 8.0 SDI application for Windows Mobile 5. In this contrived example below, I create a view, destroy it, then re-create it. But, when it's re-created assertions in the WM_INITDIALOG handler fail because the control's HWND isn't valid.
I note that I can fix this by handling WM_DESTROY in CMyView and manually destroying every child control. But, I didn't think I should have to. MSDN even says:
This message is sent first to the
window being destroyed and then to the
child windows (if any) as they are
destroyed.
Anybody have an idea as to what's going on?
Edit: If I handle WM_NCDESTROY in CMyView, all of the the child control handles are still valid! (some_control_.IsWindow()==TRUE) That's not how it's supposed to be...
Thanks,
PaulH
class CMyView : public CDialogImpl< CMyView >,
public CWinDataExchange< CMyView >
{
// <snip> Message Map and other standard WTL macros </snip>
LRESULT OnInitDialog( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/ )
{
DoDataExchange( FALSE );
// assertion fails within the SetWindowText() call
// atlwin.h line 876
// ATLASSERT(::IsWindow(m_hWnd));
some_control_.SetWindowText( _T( "Foo" ) );
return 0;
};
private:
CEdit some_control_;
}; // class CMyView
class CMainFrame : public CFrameWindowImpl< CMainFrame >,
public CUpdateUI< CMainFrame >,
public CMessageFilter,
public CIdleHandler
{
public:
// <snip> Message Map and other standard WTL macros </snip>
BOOL CMainFrame::PreTranslateMessage( MSG* pMsg )
{
if( CFrameWindowImpl< CMainFrame >::PreTranslateMessage( pMsg ) )
return TRUE;
return my_view_.PreTranslateMessage( pMsg );
};
LRESULT OnCreate( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/ )
{
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT( pLoop != NULL );
pLoop->AddMessageFilter( this );
pLoop->AddIdleHandler( this );
m_hWndClient = my_view_.Create( m_hWnd );
my_view_.DestroyWindow();
m_hWndClient = my_view_.Create( m_hWnd );
};
private:
CMyView my_view_;
}; // class CMainFrame
| It is not good practice to Create, Destroy and re-Create the same window, you should consider hiding it and reinitializing your contents when showing it again.
Anyhow your code will not ASSERT at re-creation with:
virtual void CMyView::OnFinalMessage(HWND)
{
some_control_.m_hWnd = 0;
}
|
1,718,615 | 1,718,668 | Container of Pointers vs Container of Objects - Performance | I was wondering if there is any difference in performance when you compare/contrast
A) Allocating objects on the heap, putting pointers to those objects in a container, operating on the container elsewhere in the code
Ex:
std::list<SomeObject*> someList;
// Somewhere else in the code
SomeObject* foo = new SomeObject(param1, param2);
someList.push_back(foo);
// Somewhere else in the code
while (itr != someList.end())
{
(*itr)->DoStuff();
//...
}
B) Creating an object, putting it in a container, operating on that container elsewhere in the code
Ex:
std::list<SomeObject> someList;
// Somewhere else in the code
SomeObject newObject(param1, param2);
someList.push_back(newObject);
// Somewhere else in the code
while (itr != someList.end())
{
itr->DoStuff();
...
}
Assuming the pointers are all deallocated correctly and everything works fine, my question is...
If there is a difference, what would yield better performance, and how great would the difference be?
| There is a performance hit when inserting objects instead of pointers to objects.
std::list as well as other std containers make a copy of the parameter that you store (for std::map both key and value is copied).
As your someList is a std::list the following line copies your object:
Foo foo;
someList.push_back(foo); // copy foo object
It will get copied again when you retrieve it from list. So you are making of copies of the whole object compared to making copies of pointer when using:
Foo * foo = new Foo();
someList.push_back(foo); // copy of foo*
You can double check by inserting print statements into Foo's constructor, destructor, copy constructor.
EDIT: As mentioned in comments, pop_front does not return anything. You usually get reference to front element with front then you pop_front to remove the element from list:
Foo * fooB = someList.front(); // copy of foo*
someList.pop_front();
OR
Foo fooB = someList.front(); // front() returns reference to element but if you
someList.pop_front(); // are going to pop it from list you need to keep a
// copy so Foo fooB = someList.front() makes a copy
|
1,718,854 | 1,718,900 | Correct use of s/rand or Boost::random | I know this kind of question has been asked a few times, but alot of them answers boil down to RTFM, but I'm hoping if I can ask the right question... I can get a quasi-definitive answer for everyone else as well, regarding implementation.
I'm trying to generate a sequence of random numbers in one of the two following ways:
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "Cluster.h"
#include "LatLng.h"
srand((unsigned)time(0));
double heightRand;
double widthRand;
for (int p = 0; p < this->totalNumCluster; p++) {
Option 1.
heightRand = myRand();
widthRand = myRand();
Option 2.
heightRand = ((rand()%100)/100.0);
widthRand = ((rand()%100)/100.0);
LatLng startingPoint( 0, heightRand, widthRand );
Cluster tempCluster(&startingPoint);
clusterStore.insert( clusterStore.begin() + p, tempCluster);
}
Where myRand() is:
#include <boost/random.hpp>
double myRand()
{
boost::mt19937 rng;
boost::uniform_int<> six(1,100);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(rng, six);
int tempDie = die();
double temp = tempDie/100.0;
return temp;
}
Every time I run Option 1, I get the same number on each execution of each loop. But different on each run of the program.
When I run Option 2, I get 82 from the boost libraries, so 0.81999999999999 is returned. I could understand if it was 42, but 82 is leaving me scratching my head even after reading the boost random docs.
Any ideas?
DJS.
| With option 2, you shouldn't create a new instance of rng and die for each call.
I'm also not sure if I understand the problem with option 1 correctly: you are calling srand() only once, but each call to rand() gives you the same number? That's.. "unusual". Try to reduce the loop to the minimum, and print the value returned from rand().
|
1,718,957 | 1,718,980 | When returning a pointer, what to return if it's not found? C++ | I'm not sure what to return as a default?
myDrugs is a private vector<Drug*> container
Drug* DrugDealer::getFirstDrugInSack(DrugType drugtobuy)
{
for (int i = 0; i < myDrugs.size(); i++)
{
if (myDrugs[i]->getType() == drugtobuy)
return myDrugs[i];
}
return 0; // is this right?
}
So I would call it like:
Drug *d = DrugDealer->getFirstDrugInSack(DrugType::Weed);
if (d != 0)
// do something
else
// onose?
Or is there a better way to do this?
| Returning NULL is Ok. You may also consider passing a pointer to pointer as a parameter and returning boolean value, true if it is found and false if it is not:
bool DrugDealer::getFirstDrugInSack(DrugType drugtobuy, Drug** out)
{
for (int i = 0; i < myDrugs.size(); i++)
{
if (myDrugs[i]->getType() == drugtobuy) {
*out = myDrugs[i];
return true;
}
}
return false;
}
Calling:
Drug* d;
if (dealer->getFirstDrugInSack(dragType, &d)) {
// Found it, use it
}
|
1,719,051 | 1,719,073 | array of pointers as function parameter | I have a basic question on array and pointer in C/C++.
Say I have:
Foo* fooPtrArray[4];
How to pass the fooPtrArray into a function?
I have tried:
int getResult(Foo** fooPtrArray){} // failed
int getResult(Foo* fooPtrArray[]){} // failed
How can I deal with pointer array?
EDIT: I once thought the error msg is from passing the wrong pointer array, but from all the responses, I realize that it's something else... (pointer assignment)
Error msg:
Description Resource Path Location Type incompatible types in assignment of
`Foo**' to `Foo*[4]' tryPointers.cpp tryPointers line 21 C/C++ Problem
I don't quite get why it says: Foo* * to Foo*[4]. If as function parameter they are inter-change with each other, why during assignment, it give me compilation error?
I tried to duplicate the error msg with minimum code as follows:
#include <iostream>
using namespace std;
struct Foo
{
int id;
};
void getResult(Foo** fooPtrArray)
{
cout << "I am in getResult" << endl;
Foo* fooPtrArray1[4];
fooPtrArray1 = fooPtrArray;
}
int main()
{
Foo* fooPtrArray[4];
getResult(fooPtrArray);
}
| Both
int getResult(Foo** fooPtrArray)
and
int getResult(Foo* fooPtrArray[])
as well as
int getResult(Foo* fooPtrArray[4])
will work perfectly fine (they are all equivalent).
It is not clear from your question what was the problem. What "failed"?
When passing arrays like that it normally makes sense to pass the element count as well, since the trick with allowing the array type to decay to pointer type is normally used specifically to allow passing arrays of different sizes:
int getResult(Foo* fooPtrArray[], unsigned n);
...
Foo* array3[3];
Foo* array5[5];
getResult(array3, 3);
getResult(array5, 5);
But if you are always going to pass arrays of strictly 4 elements, it might be a better idea to use a differently-typed pointer as a parameter:
int getResult(Foo* (*fooPtrArray)[4])
In the latter case the function call will loook as follows
Foo* array[4];
getResult(&array);
(note the & operator applied to the array object).
And, finally, since this question is tagged as C++, in the latter case a reference can also be used instead of a pointer
int getResult(Foo* (&fooPtrArray)[4]);
...
Foo* array[4];
getResult(array);
|
1,719,055 | 1,731,970 | Just Want to know what this error message really means! |
expected unqualified-id before '{'
Where is this error on my code? Thanks everyone!
#include <iostream>
using std::cout;
using std::endl;
//function prototypes
void findsmallest (int[], int &);
void findsmallest (int scores [], int & min);
int main()
{
//declare variables
int smallest = 0;
int scores[20] = { 90, 54, 23, 75, 67,
89, 99, 100, 34, 99,
97, 76, 73, 72, 56,
73, 72, 65, 86, 90 };
findsmallest(scores, smallest);
return 0;
//call function find smallest
findsmallest (scores, smallest);
cout << "Minimum value in the array is " << smallest << endl;
system ("pause");
return 0;
}
//function definition
void findsmallest(int scores [], int & min);
{
min = scores[0];
int i;
for(i = 0; i < 20; i++)
{
if(scores[i] < min)
{
min = scores[i];
}
}
}
//end display findsmallest
system ("pause");
return 0;
| The error is in the first line of the findsmallest() function definition. Get rid of the semicolon and it should work (barring other errors in the code -- I didn't check it for correctness).
void findsmallest(int scores [], int & min); <-------semicolon
{
vs
void findsmallest(int scores [], int & min) <--------no semicolon
{
The error is telling you that the open brace ({) that follows the semicolon is lacking a preceding class/struct/union/function declaration, so the compiler doesn't know what to do with it. Remove the semicolon and now the compiler knows that it's the body of a function definition.
|
1,719,070 | 1,719,155 | What is the right approach when using STL container for median calculation? | Let's say I need to retrieve the median from a sequence of 1000000 random numeric values.
If using anything but std::list, I have no (built-in) way to sort sequence for median calculation.
If using std::list, I can't randomly access values to retrieve middle (median) of sorted sequence.
Is it better to implement sorting myself and go with e.g. std::vector, or is it better to use std::list and use std::list::iterator to for-loop-walk to the median value? The latter seems less overheadish, but also feels more ugly..
Or are there more and better alternatives for me?
| Any random-access container (like std::vector) can be sorted with the standard std::sort algorithm, available in the <algorithm> header.
For finding the median, it would be quicker to use std::nth_element; this does enough of a sort to put one chosen element in the correct position, but doesn't completely sort the container. So you could find the median like this:
int median(vector<int> &v)
{
size_t n = v.size() / 2;
nth_element(v.begin(), v.begin()+n, v.end());
return v[n];
}
|
1,719,096 | 1,719,133 | How can I receive emails in C++ via POP3? | I've been trying to find a POP3 C++ client on the internet but I haven't found any luck.
We are working on a project for school that is essentially a C++ course (so I can't use C#...), and we are making a Email client that has to support sending and receiving emails and attachments. We are also working with .NET (because apparently MFC is terrible, although I haven't used it, anyone have an opinion on this?), and so I would prefer a Microsoft built in library solution to this. So far we've been able to get sending of email working using SMPTclient, but no POP3 luck.
If anyone has a solution in .NET that would be great, otherwise I'll have to write my own POP3 client code, and if anyone has a link for that to get me in the right direction it would be much appreciated.
| POCO has POP3- and SMTP-support in its Net-library.
|
1,719,216 | 1,719,230 | static member variable and method | If I have a C++ class which contains a static member variable, does the accessor method for this variable need to be static as well? Also, are there any issues that might occur if I inline this method?
| It doesn't need to be static, but unless it's doing something specific to a particular instance of the class, there's no real reason not to make it static anyway.
This shouldn't effect inlining in any way.
|
1,719,325 | 1,730,862 | FLTK in Cygwin using Eclipse (Linking errors) | I have this assignment due that requires the usage of FLTK. The code is given to us and it should compile straight off of the bat, but I am having linking errors and do not know which other libraries I need to include.
I currently have "opengl32", "fltk_gl", "glu32", and "fltk" included (-l), each of which seem to reduce the number of errors. I compiled FLTK using make with no specified options. Including all of the produced library files doesn't fix the problem, and I'm convinced that it's just some Windows specific problem.
Compile log:
**** Build of configuration Debug for project CG5 ****
make all
Building target: CG5.exe
Invoking: Cygwin C++ Linker
g++ -o"CG5.exe" ./src/draw_routines.o ./src/gl_window.o ./src/my_shapes.o ./src/shape.o ./src/shapes_ui.o ./src/tesselation.o -lopengl32 -lfltk_z -lfltk_gl -lglu32 -lfltk
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x197): undefined reference to `_SelectPalette@12'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x1a7): undefined reference to `_RealizePalette@4'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x1fe): undefined reference to `_glDrawBuffer@4'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x20d): undefined reference to `_glReadBuffer@4'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x23a): undefined reference to `_glGetIntegerv@8'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x2c3): undefined reference to `_glOrtho@48'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libfltk_gl.a(Fl_Gl_Window.o):Fl_Gl_Window.cxx:(.text+0x2f3): undefined reference to `_SwapBuffers@4'
...and lots more
Thanks a ton for the help.
EDIT: These first few lines are obviously OpenGL related, although I'm still not sure what additional libraries need to be included.
| Sorry for the lack of closure, but I just booted into my Linux netbook and got it working.
-lfltk -lfltk_gl -lGLU -lGL -lXext -lX11 -lm
|
1,719,358 | 1,719,893 | How can I manage a group of derived but otherwise Unrelated Classes | It seems the more I talk about this problem the better I understand it. I think my previous question didn't convey what I am trying to do correctly. My apologies for that.
In my design I have GameObjects which are essentially an aggregation class, all functionality in a GameObject is implemented by adding various "Features" to it. A Feature is a Subclass of the Feature class that has it's own members and functions. All Features can receive Messages
class Feature
{
public:
virtual void takeMessage(Message& message) = 0;
};
class VisualFeature : public Feature
{
public:
void takeMessage(Message& message);
private:
RenderContext m_renderer;
};
... Additional Features ...
FeatureServers are objects that are responsible for coordinating the various Features. GameObjects can subscribe to FeatureServers to receive messages from them, and Features can Subscribe to GameObjects to handle the messages it is interested in.
So for example in this code:
GameObject Square;
VisualFeature* SquareSprite = new VisualFeature();
Square.subscribe(SquareSprite, "MESSAGE_RENDER");
Square.addFeature(SquareSprite);
m_VisualFeatureServer.subscribe(Square, "MESSAGE_RENDER");
The VisualFeatureServer sends the message tied to "MESSAGE_RENDER" which may look something like this
class Message
{
public:
std::string getID() {return m_id;}
bool isConsumed() {return m_consumed;}
void consume() {m_consumed = true;}
protected:
bool isConsumed;
std::string m_id;
}
class Message_Render : public Message
{
public:
Message_Render() : m_id("MESSAGE_RENDER"), m_consumed(false) {}
RenderTarget& getRenderTarget() {return m_target;}
private:
RenderTarget& m_target;
};
When the VisualFeatureServer sends the Message_Render class to the Square GameObject it then forwards it to any FeatureComponents that are subscribed to receive that particular message. In this case the VisualFeature class receives the Message_Render message. Here is where my problem is, the VisualFeature class is going to receive a Message& that it can tell is a Message_Render by it's ID, I want to be able to treat it as a Message_Render rather then a Message like so:
void VisualFeature::takeMessage(Message& message)
{
//Here's the problem, I need a pattern to handle this elegantly
derivedMessage = convertMessageToDerivedType(message);
this->handleDerivedMessageType(derivedMessage);
}
void VisualFeature::handleDerivedMessageType(Message_Render& message)
{
message.getRenderTarget().render(m_renderer);
message.consume();
}
Is there a way to elegantly deal with the takeMessage portion of this design?
| The other answer was getting too bloated with edits, so I started a new one.
The casting you are doing in the receiveMessage() functions is definitely a code smell.
I think you need to use a combination of:
Abstract factory pattern to instantiate your objects (messages and components)
Observer pattern to respond to messages
The idea is that each component type will only subscribe to messages of its own type, and will therefore only receive messages intended for it. This should eliminate the need for casting.
The notifying object could, as an example, use a vector of notifier objects indexed by the message ID. The observing object (the derived component class) could subscribe to the particular notifier indexed by its own message ID.
Do you think this design pattern would help?
|
1,719,501 | 1,719,528 | How do I convert a c++ string to a .NET String^? | I've been trying to figure out how to convert a string to a String in Visual Studio 2005 with no luck.
Here is the relevant code:
#include <string>
using namespace std;
#using <System.dll>
using namespace System;
string test = "a test string";
So I'm trying to convert test into a String^ to use inside other .NET classes, can anyone help me with this?
| String^ str = gcnew String(test)
|
1,719,530 | 1,719,540 | Can an ifstream variable be a global variable? | // stream from file.
ifstream file;
int main (int argc, char * argv[]) {
// get argument passed from command line
// This is file name
if (argc != 2 ) {
cout << "use: ./executable <filename>";
}else {
//cout << "You are using filename: " << argv[1];
// start the file stream
file (argv[1]);
}
Is there any reason why file(argv[1]) would be giving an error? Can I have a ifstream as a global variable?
| You're trying to call the ifstream's () operator (which doesn't exist), when you should be using file.open(argv[1]).
Besides that, there's nothing illegal about having a global ifstream.
|
1,719,607 | 1,719,647 | Is the memory allocated by new operated consecutive? | as the title says, I want to know in c++, whether the memory allocated by one new operation is consecutive...
| BYTE* data = new BYTE[size];
In this code, whatever size is given, the returned memory region is consecutive. If the heap manager can't allocate consecutive memory of size, it's fail. an exception (or NULL in malloc) will be returned.
Programmers will always see the illusion of consecutive (and yes, infinite :-) memory in a process's address space. This is what virtual memory provides to programmers.
Note that programmers (other than a few embedded systems) always see virtual memory. However, virtually consecutive memory could be mapped (in granularity of 'page' size, which is typically 4KB) in physical memory in arbitrary fashion. That mapping, you can't see, and mostly you don't need to understand it (except for very specific page-level optimizations).
What about this?
BYTE* data1 = new BYTE[size1];
BYTE* data2 = new BYTE[size2];
Sure, you can't say the relative address of data1 and data2. It's generally non-deterministic. It depends on heap manager (such as malloc, often new is just wrapped malloc) policies and current heap status when a request was made.
|
1,719,818 | 1,719,847 | Difference between reference and const reference as function parameter? | Here is a simple snippet of C++ code:
A foo(){
A a; // create a local A object
return a;
}
void bar(const A & a_r){
}
bar(foo());
Why does the argument of function bar have to be a const reference,not just a reference?
Edit1: I know that reference is to avoid copying overhead. and const is for read-only. But here I have to make it a const reference, otherwise if I remove the "const", g++ will throw an error to me.
Edit2: My guess is that the return object of foo() is a temporary object, and it's not allowed to change the value of a temporary object ?
| Without the error message, I'm not exactly sure what the compiler might be complaining about, but I can explain the reason logically:
In the line:
bar(foo());
The return value of foo() is a temporary A; it is created by the call to foo(), and then destructed as soon as bar() returns. Performing a non-const operation (i.e. an operation that changes the temporary A) doesn't make sense, as the object A is destructed right afterwards.
Looking a little more, this is a virtual dup of this question:
How come a non-const reference cannot bind to a temporary object?
which has an excellent answer.
|
1,719,928 | 1,719,952 | Why is this syntax invalid? vectorPointer->[0] | In C++, why is the following element access in a vector invalid?
void foo(std::vector<int>* vecPtr) {
int n = vecPtr->size(); // ok
int a = vecPtr->[0]; // invalid
}
Instead, we have to write the more cumbersome
(*vecPtr)[0] = 1;
I think, the operator[] call should just have the same syntax like a method call, and I hate the extra star and parentheses. (I know C++ has a lot more serious issues, but this one annoys me every time when I have to type it ...)
| It's because the language expects a member to appear after ->. That's how the language is made up. You can use the function call syntax, if you like
// not really nicer
vecPtr->operator[](0);
If you have to do this a lot in sequence, using [0] instead of the parentheses can improve readability greatly
vecPtr[0][0]
Otherwise, for one level, i find (*vecPtr)[0] is perfectly readable to me.
|
1,720,271 | 1,720,335 | C++ Server is terminating if the front end Tomcat is killed. Error "Received untrapped signal [13] - SIGPIPE" | I am facing a problem in my C++ server program. The request XML comes from the front end (Java) and the back end server (C++) process the request and returns the reply XML.
As part of testing after submitting the request to back-end we killed the Tomcat server. The back-end application (threaded server application) after processing the request failed to sent the response as the Tomcat server was down. The server terminated by throwing the error "received untrapped signal [13] - [SIGPIPE]". We have implemented the sigalrm and sigterm functions.
The above signal error is not captured. Will implementing sigaction help? Also, once the signal is captured what needs to be done to return back to the main loop where the server is listening?
Edit:
We have found that the send() function is having a parameter MSG_NOSIGNAL. On passing this parameter the send function will not thrown the SIGPIPE signal if the connection terminates.
| The easiest thing to do is just ignore the signal:
struct sigaction new_action, old_action;
/* Set up the structure to specify the new action. */
new_action.sa_handler = SIG_IGN;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction(SIGPIPE, &new_action, &old_action);
Once you do this, the read or write call that was causing the signal, it now going to return with an error and your code needs to be prepared to handle that.
|
1,720,609 | 1,930,851 | Supporting multi-add/delete (and undo/redo) with a QAbstractItemModel (C++) | Greetings,
I've been writing some nasty code to support the undo/redo of deletion of an arbitrary set of objects from my model. I feel like I'm going about this correctly, as all the other mutators (adding/copy-pasting) are subsets of this functionality.
The code is nastier than it needs to me, mostly because the only way to mutate the model involves calling beginInsertRows/beginRemoveRows and removing the rows in a range (just doing 1 row at a time, no need to optimize "neighbors" into a single call yet)
The problem with beginInsertRows/beginRemoveRows is that removal of a row could affect another QModelIndex (say, one cached in a list). For instance:
ParentObj
->ChildObj1
->ChildObj2
->ChildObj3
Say I select ChildObj1 and ChildObj3 and delete them, if I remove ChildObj1 first I've changed ChildObj3's QModelIndex (row is now different). Similar issues occur if I delete a parent object (but I've fixed this by "pruning" children from the list of objects).
Here are the ways I've thought of working around this interface limitation, but I thought I'd ask for a better one before forging ahead:
Move "backwards", assuming a provided list of QModelIndices is orderered from top to bottom just go from bottom up. This really requires sorting to be reliable, and the sort would probably be something naive and slow (maybe there's a smart way of sorting a collection of QModelIndexes? Or does QItemSelectionModel provide good (ordered) lists?)
Update other QModelIndeces each time an object is removed/added (can't think of a non-naive solution, search the list, get new QModelIndeces where needed)
Since updating the actual data is easy, just update the data and rebuild the model. This seems grotesque, and I can imagine it getting quite slow with large sets of data.
Those are the ideas I've got currently. I'm working on option 1 right now.
Regards,
Dan O
| Think of beginRemoveRows/endRemoveRows, etc. as methods to ask the QAbstractItemModel base class to fix up your persistent model indexes for you instead of just a way of updating views, and try not to confuse the QAbstractItemModel base class in its work on those indexes. Check out http://labs.trolltech.com/page/Projects/Itemview/Modeltest to exercise your model and see if you are keeping the QAbstractItemModel base class happy.
Where QPersistentModelIndex does not help is if you want to keep your undo/redo data outside of the model. I built a model that is heavily edited, and I did not want to try keeping everything in the model. I store the undo/redo data on the undo stack. The problem is that if you edit a column, storing the persistent index of that column on the undo stack, and then delete the row holding that column, the column's persistent index becomes invalid.
What I do is keep both a persistent model index, and a "historical" regular QModelIndex. When it's time to undo/redo, I check if the persistent index has become invalid. If it has, I pass the historical QModelIndex to a special method of my model to ask it to recreate the index, based on the row, column, and internalPointer. Since all of my edits are on the undo stack, by the time I've backed up to that column edit on the undo stack, the row is sure to be there in the model. I keep enough state in the internalPointer to recreate the original index.
|
1,720,712 | 1,720,734 | Speed difference: separate functor VS operator() inside a big class with *this | I'm using the c++ STL heap algorithms, and I wrote a wrapper class around it so I could do some other stuff. When I tried to use the code below, for example:
//! Min-heap wrapper class.
class FMMHeap{
public:
FMMHeap(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),*this); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
Vector &_phi;
}
It was wayyyyy slower than when I had a separate function object like this:
struct HeapSort{
public:
HeapSort(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
private:
Vector &_phi;
};
class FMMHeap{
public:
FMMHeap(Vector &phi) : cmp(phi) {}
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),cmp); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
HeapSort cmp;
}
I'm not sure why this is. Is the slowdown coming from *this because the class has a lot of data? That seems odd. Or is it something to do with how the function object is used?
| I'm not certain: but maybe pop_heap ends up copying the functor object you pass in.
The copy for your FMMHeap would be more expensive than the simple HeapSort
|
1,720,953 | 1,720,994 | Why not resize and clear works in GotW 54? | Referring to article Gotw 54 by HerbSutter, he explains about
The Right Way To "Shrink-To-Fit" a
vector or deque and
The Right Way to Completely Clear a vector or
deque
Can we just use container.resize()
and container.clear() for the above task
or am I missing something?
| There are two different things that a vector holds: size Vs capacity. If you just resize the vector, there is no guarantee that the capacity(how much memory is reserved) must change. resize is an operation concerned with how much are you using, not how much the vector capacity is.
So for example.
size == how much you are using
capacity == how much memory is reserved
vector<int> v(10);
v.resize(5); // size == 5 but capacity (may or may) not be changed
v.clear() // size == 0 but capacity (may or may) not be changed
In the end, capacity should not changed on every operation, because that would bring a lot of memory allocation/deallocation overhead. He is saying that if you need to "deallocate" the memory reserved by vector, do that.
|
1,721,241 | 1,721,396 | What programming language is IIS written in? | I'd like to know this information for IIS versions 6.0, 7.0 and 7.5.
| It is made in C++, microsoft has given isapi extension which is api for IIS and programmers can explore classes using this api
|
1,721,351 | 1,721,526 | How can I measure the execution time of a for loop? | I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it?
I know these platforms so i am talking about these:
for (i = 0; i < 1000000; i++)
{
}
I don't want to measure anything within the loop.
Little bit modification:
@all Some of the friends of mine are saying compiler will optimize this code making this loop a useless loop. I agree with this. we can add a small statement like some incremental statement, but the fact is I just want to calculate the execution time of per iteration in a loop in various languages. By adding a incremental statement will add up the execution time and that will effect the results, cause on various platforms, execution time for incrementing a value also differ and that will make a result useless.
In short, in better way I should ask:
I WANT TO CALCULATE THE EXECUTION TIME OF PER ITERATION IN A LOOP on Various PLATFORMS..HOW CAN DO THIS???
edit---
I came to know about Python Profilers
Profiler modules ...which evaluate cpu time... absolute time.. Any suggestions???Meanwhile i am working on this...
| Note that it also depends on what exactly you want to achieve: do you care about the time your program waits due to it being preempted by the system scheduler? All the solutions above take actual time elapsed into consideration, but that also involves the time when other processes run instead of your own.
If you don't care about this, all of the solutions above are good. If you do care, you probably need some profiling software to actually see how long the loop takes.
I'd start with a program that does nothing but your loop and (in a linux environment at least) do time you-prg-executable.
Then I'd investigate if there are tools which work like time. Not sure, but I'd look at JRat for java, and gcc's gcov for C and C++. No doubt there are similar tools for the other languages. But, of course, you need to see if they give actual time or not.
|
1,721,488 | 1,721,535 | c++ array access through pointer | A simple question about accessing array information through pointers that I can't seem to figure out. I'm passing a bunch of multi-dimentional arrays into a function. Now they are not dynamic but even if static, I have to pass them as pointers right? (If I'm wrong, please do correct me)
So once I do pass them into a function, how do I access it?
int main()
{
int anArray[5][5] = // member intializations
foo(*anArray);
}
void foo(int * anArray) //or should that be int ** anArray ??
{
cout << anArray[2][2] << endl; // how should i address this..?
}
| If your arrays are of fixed size, you can do it this way:
void foo(int arr[5][5])
{
cout << arr[2][2] << endl;
}
|
1,721,543 | 1,721,575 | Continue to debug after failed assertion on Linux? | When an assertion fails with Visual C++ on Windows, the debugger stops, displays the message, and then lets you continue (or, if no debugging session is running, offers to launch visual studio for you).
On Linux, it seems that the default behavior of assert() is to display the error and quit the program. Since all my asserts go through macros, I tried to use signals to get around this problem, like
#define ASSERT(TEST) if(!(TEST)) raise(SIGSTOP);
But although GDB (through KDevelop) stops at the correct point, I can't seem to continue past the signal, and sending the signal manually within GDB just leaves me hanging, with control of neither GDB nor the debugged process.
| You really want to recreate the behavior of DebugBreak. This stops the program in the debugger.
My googling of "DebugBreak linux" has turned up several references to this piece of inline assembly which is supposed to do the same.
#define DEBUG_BREAK asm("int $3")
Then your assert can become
#define ASSERT(TEST) if(!(TEST)) asm("int $3");
According to Andomar int 3 causes the cpu to raise interrupt 3. According to drpepper a more portable way to do this would be to call:
raise(SIGTRAP);
|
1,721,834 | 1,721,943 | C++ STL unordered_map problems and doubts | after some years in Java and C# now I'm back to C++. Of course my programming style is influenced by those languages and I tend to feel the need of a special component that I used massively: the HASH MAP. In STL there is the hash_map, that GCC says it's deprecated and I should use unordered_map. So I turned to it. I confess I'm not sure of the portability of what I am doing as I had to use a compiler switch to turn on the feature -std=c++0x that is of the upcoming standard. Anyway I'm happy with this. As long as I can't get it working since if I put in my class
std::unordered_map<unsigned int, baseController*> actionControllers;
and in a method:
void baseController::attachActionController(unsigned int *actionArr, int len,
baseController *controller) {
for (int i = 0; i < len; i++){
actionControllers.insert(actionArr[i], controller);
}
}
it comes out with the usual ieroglyphs saying it can't find the insert around... hints?
| Just use:
actionControllers[ actionArr[i] ] = controller;
this is the operator overloading java owe you for ages :)
|
1,721,980 | 1,722,022 | Calculating variance with large numbers | I haven't really used variance calculation that much, and I don't know quite what to expect. Actually I'm not too good with math at all.
I have a an array of 1000000 random numeric values in the range 0-10000.
The array could grow even larger, so I use 64 bit int for sum.
I have tried to find code on how to calc variance, but I don't know if I get correct output.
The mean is 4692 and median is 4533. I get variance 1483780.469308 using the following code:
// size is the element count, in this case 1000000
// value_sum is __int64
double p2 = pow( (double)(value_sum - (value_sum/size)), (double)2.0 );
double variance = sqrt( (double)(p2 / (size-1)) );
Am I getting a reasonable value?
Is anything wrong with the calculation?
| Note: It doesn't look like you're calculating the variance.
Variance is calculated by subtracting the mean from every element and calculating the weighted sum of these differences.
So what you need to do is:
// Get mean
double mean = static_cast<double>(value_sum)/size;
// Calculate variance
double variance = 0;
for(int i = 0;i<size;++i)
{
variance += (MyArray[i]-mean)*(MyArray[i]-mean)/size;
}
// Display
cout<<variance;
Note that this is the sample variance, and is used when the underlying distribution is unknown (so we assume a uniform distribution).
Also, after some digging around, I found that this is not an unbiased estimator. Wolfram Alpha has something to say about this, but as an example, when MATLAB computes the variance, it returns the "bias-corrected sample variance".
The bias-corrected variance can be obtained by dividing by each element by size-1, or:
//Please check that size > 1
variance += (MyArray[i]-mean)*(MyArray[i]-mean)/(size-1);
Also note that, the value of mean remains the same.
|
1,722,260 | 1,722,277 | What creates the stack? | Suppose in a program we have implemented a stack. But who creates the stack ? Is it the processor, or operating system, or compiler?
| If you mean the data structure: The processor executes the code. The code makes calls to the operating system to get the memory for the stack, and then manipulates it to form it into a stack. The compiler just turns the code you wrote into code the processor can understand.
If you mean the execution stack: The OS is responsible for loading a process into memory and setting up its memory space to form the stack.
|
1,722,381 | 1,722,428 | c++ virtual class, subclass and selfreference | consider this class:
class baseController {
/* Action handler array*/
std::unordered_map<unsigned int, baseController*> actionControllers;
protected:
/**
* Initialization. Can be optionally implemented.
*/
virtual void init() {
}
/**
* This must be implemented by subclasses in order to implement their action
* management
*/
virtual void handleAction(ACTION action, baseController *source) = 0;
/**
* Adds an action controller for an action. The actions specified in the
* action array won't be passed to handleAction. If a controller is already
* present for a certain action, it will be replaced.
*/
void attachActionController(unsigned int *actionArr, int len,
baseController *controller);
/**
*
* checks if any controller is attached to an action
*
*/
bool checkIfActionIsHandled(unsigned int action);
/**
*
* removes actions from the action-controller filter.
* returns false if the action was not in the filter.
* Controllers are not destoyed.
*/
bool removeActionFromHandler(unsigned int action);
public:
baseController();
void doAction(ACTION action, baseController *source);
};
}
and this subclass
class testController : public baseController{
testController tc;
protected:
void init(){
cout << "init of test";
}
void handleAction(ACTION action, baseController *source){
cout << "nothing\n";
}
};
The compiler comes out with an error on the subclass on the member
testController tc;
..saying
error: field ‘tc’ has incomplete type
but if I remove that and I instatiate the class it works... is there a way to avoid this error??? It looks so strange to me....
| Your code is trying to embed an entire instance of testController inside itself, which is impossible. Instead, you want a reference:
testController &tc;
or a pointer
testController *tc;
|
1,722,386 | 1,722,551 | xerces-c 2.8 : error while loading shared libraries | I'm trying to compile a program running on an HP UX server on a Red Hat Linux.
It uses xerces-c library to parse xml files. Compilation is ok, but when i try to run it, I get the following message
./a.out: error while loading shared
libraries: libxerces-c.so.28: cannot
open shared object file: No such file
or directory
I wrote a very simple program to try and understand whats going on:
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/parsers/SAXParser.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
int main(int argc, char* argv[])
{
return 0;
}
And compiled it like this:
g++ test.cpp
-L./xml/xerces-c_2_8_0/lib -lxerces-c -I./xml/xerces-c_2_8_0/include
Surprisingly the file is actually there:
lib]$ ls
libxerces-c.a libxerces-c.so.28 libxerces-depdom.a libxerces-depdom.so.28
libxerces-c.so libxerces-c.so.28.0 libxerces-depdom.so libxerces-depdom.so.28.0
Any thoughts ? I feel i'm missing something, but don't know what.
Thanks in advance.
| run ldd a.out and see if the linker can resolve the right .so file
export LD_LIBRARY_PATH to include the current folder (in the same manner as the PATH variable) and check ldd again
|
1,722,387 | 1,722,519 | Looking for an implemenentation of binomial tree in c++ | If anyone can point me into direction where i can find an easy to understand impl. of binomial tree, that would be very helpful. thx
tree should look like in this article: http://software.intel.com/en-us/articles/high-performance-computing-with-binomial-option-pricing-part-1/
| I have used this example in the past to develop a project that required us to use a binomial tree model, however, this example is in C#.
http://www.codeproject.com/KB/recipes/binomialtree.aspx
|
1,722,670 | 1,722,722 | Common way to call mother-class operator= in C++? | Let's suppose I have a class Dog that inherits from class Animal,
you might want to insert a call to Animal::operator= in Dog::operator=.
What is the most readable/common way to write it?
I think I know those two...
static_cast<Animal*>(this)->operator=(other);
and
this->Animal::operator=(other);
| Since you are doing it from within a child class method
Animal::operator=(other);
No need for this->. The scope resolution syntax does exactly what was requested. I don't see a point in doing it "indirectly" with a cast.
Note also that doing it with a cast might not produce the expected result in general case, since it will not disable the dynamic resolution of virtual method call. (And, BTW, assignment operator can be declared virtual). An obvious consequence of that is that with virtual methods the "cast" variant might easily result in endless recursion.
|
1,722,916 | 1,722,931 | how to link c++ program with HTML page? | i am working on php...!!
Is it possible to link HTML page to c++/c at back end.
means instead of php script i want to run c/c++
if Yes How??
| Check CGI and FastCGI technologies.
|
1,723,084 | 1,723,235 | Does Blitz++ use BLAS routines when it is possible and appropriate to | I know that Blitz++ gets its performance plus by extensive usage of expression templates and template metaprogramms. But at some point you can't get more out of your code by using these techniques - you have to multiply and sum some floats up. At this point you can get a final performance kick by using the highly optimized (especially for special architectures) BLAS routines. Does the current implementation of Blitz++ use BLAS routines whenever it is possible?
| Only for benchmarks you must specify it when you configure blitz++:
./configure -with-blas=...
Blitz does not use Blas routines.
|
1,723,229 | 1,723,405 | Which allocator are available in STLPORT, and how to use them | We're using STLPORT and we'd like to change stlport's default allocator:
instead of vector<int>, we'd like to try vector<int, otherallocator>
Which alternative allocator are available in stlport, and what are their features?
How do I use them?
| Take a look here for switching the default allocator. I think you'll find the available allocator implementations are under include/stlport/stl/ in your installation.That said, it's a standard interface and you can implement your own.
|
1,723,288 | 1,723,385 | How to handle different situations in mouse event handler properly? | In my Qt application in the event handler for mouse press events I have such ugly code
void Render::Viewer::mousePressEvent(QMouseEvent* e)
{
switch (e->button())
{
case Qt::LeftButton:
switch (mode_)
{
case Render::Viewer::ModeView:
switch (e->modifiers())
{
case Qt::NoModifier:
...
break;
...
default:
break;
}
break;
case Render::Viewer::ModeEdit:
...
break;
}
break;
case Qt::RightButton:
...
break;
}
}
Even without switching on mode_ variable the code looks terrible. =( Two many degrees of freedom: button type, modifiers, ... Absolutely unreadable.
Is there any ways to overcome such a "heap of switches"?
| It would be easier to read and maintain if you broke up tasks into their own functions:
void Render::Viewer::mousePressEvent(QMouseEvent* e)
{
switch (e->button())
{
case Qt::LeftButton:
handleLeftButton(e);
break;
case Qt::RightButton:
handleRightButton(e);
break;
}
}
void Render::Viewer::handleLeftButton(QMouseEvent* e)
{
switch (mode_)
{
case Render::Viewer::ModeView:
switch (e->modifiers())
{
case Qt::NoModifier:
...
break;
...
default:
break;
}
break;
case Render::Viewer::ModeEdit:
...
break;
}
}
void Render::Viewer::handleRightButton(QMouseEvent* e)
{
...
}
Break it up into however many functions you need to make it readable.
|
1,723,419 | 1,723,520 | Configuration structs vs setters | I recently came across classes that use a configuration object instead of the usual setter methods for configuration. A small example:
class A {
int a, b;
public:
A(const AConfiguration& conf) { a = conf.a; b = conf.b; }
};
struct AConfiguration { int a, b; };
The upsides:
You can extend your object and easily guarantee reasonable default values for new values without your users ever needing to know about it.
You can check a configuration for consistency (e.g. your class only allows some combinations of values)
You save a lot of code by ommiting the setters.
You get a default constructor for specifying a default constructor for your Configuration struct and use A(const AConfiguration& conf = AConfiguration()).
The downside(s):
You need to know the configuration at construction time and can't change it later on.
Are there more downsides to this that I'm missing? If there aren't: Why isn't this used more frequently?
| Whether you pass the data individually or per struct is a question of style and needs to be decided on a case-by-case basis.
The important question is this: Is the object is ready and usable after construction and does the compiler enforce that you pass all necessary data to the constructor or do you have to remember to call a bunch of setters after construction who's number might increase at any time without the compiler giving you any hint that you need to adapt your code. So whether this is
A(const AConfiguration& conf) : a(conf.a), b(conf.b) {}
or
A(int a_, int b_) : a(a_), b(b_) {}
doesn't matter all that much. (There's a number of parameters where everyone would prefer the former, but which number this is - and whether such a class is well designed - is debatable.) However, whether I can use the object like this
A a1(Configuration(42,42));
A a2 = Configuration(4711,4711);
A a3(7,7);
or have to do this
A urgh;
urgh.setA(13);
urgh.setB(13);
before I can use the object, does make a huge difference. Especially so, when someone comes along and adds another data field to A.
|
1,723,469 | 1,723,507 | Interface Inheritance in C++ | I have the following class structure:
class InterfaceA
{
virtual void methodA =0;
}
class ClassA : public InterfaceA
{
void methodA();
}
class InterfaceB : public InterfaceA
{
virtual void methodB =0;
}
class ClassAB : public ClassA, public InterfaceB
{
void methodB();
}
Now the following code is not compilable:
int main()
{
InterfaceB* test = new ClassAB();
test->methodA();
}
The compiler says that the method methodA() is virtual and not implemented. I thought that it is implemented in ClassA (which implements the InterfaceA).
Does anyone know where my fault is?
| That is because you have two copies of InterfaceA. See this for a bigger explanation: https://isocpp.org/wiki/faq/multiple-inheritance (your situation is similar to 'the dreaded diamond').
You need to add the keyword virtual when you inherit ClassA from InterfaceA. You also need to add virtual when you inherit InterfaceB from InterfaceA.
|
1,723,515 | 1,723,737 | Insert into an STL queue using std::copy | I'd like to use std::copy to insert elements into a queue like this:
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
queue<int> q;
copy( v.begin(), v.end(), insert_iterator< queue<int> >( q, q.front() ) );
But this fails to compile, complaining that begin is not a member of std::queue.
Note: I tried it with std::inserter too - this also failed, this time saying that 'reference' is not a member of 'std::queue'. std::back_inserter and std::back_insert_iterator also fail with the same error.
Am I missing something obvious, or do insert_iterators just not work with queues?
| Unfortunately std::queue 'adapts' the function known as push_back to just push which means that the standard back_insert_iterator doesn't work.
Probably the simplest way (albeit conceptually ugly) is to adapt the container adapter with a short lived container adapter adapter[sic] (eugh!) that lives as long as the back insert iterator.
template<class T>
class QueueAdapter
{
public:
QueueAdapter(std::queue<T>& q) : _q(q) {}
void push_back(const T& t) { _q.push(t); }
private:
std::queue<T>& _q;
};
Used like this:
std::queue<int> qi;
QueueAdapter< std::queue<int> > qiqa( qi );
std::copy( v.begin(), v.end(), std::back_inserter( qiqa ) );
|
1,723,537 | 1,723,667 | Template specialization of a single method from a templated class | Always considering that the following header, containing my templated class, is included in at least two .CPP files, this code compiles correctly:
template <class T>
class TClass
{
public:
void doSomething(std::vector<T> * v);
};
template <class T>
void TClass<T>::doSomething(std::vector<T> * v) {
// Do something with a vector of a generic T
}
template <>
inline void TClass<int>::doSomething(std::vector<int> * v) {
// Do something with a vector of int's
}
But note the inline in the specialization method. It is required to avoid a linker error (in VS2008 is LNK2005) due to the method being defined more then once. I understand this because AFAIK a full template specialization is the same as a simple method definition.
So, how do I remove that inline? The code should not be duplicated in every use of it. I've searched Google, read some questions here in SO and tried many of the suggested solutions but none successfully built (at least not in VS 2008).
Thanks!
| As with simple functions you can use declaration and implementation.
Put in your header declaration:
template <>
void TClass<int>::doSomething(std::vector<int> * v);
and put implementation into one of your cpp-files:
template <>
void TClass<int>::doSomething(std::vector<int> * v) {
// Do somtehing with a vector of int's
}
Don't forget to remove inline (I forgot and thought this solution will not work :) ).
Checked on VC++2005
|
1,723,572 | 1,723,592 | What is the best solution for suppressing warning from a MS include (C4201 in mmsystem.h) | I am tired of having to look at warnings during our compilations - warnings that come from MS include files.
"C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\mmsystem.h(1840): warning C4201: nonstandard extension used : nameless struct/union"
I have seen this thread that suggests changing the header itself (but then each of my team mates has to do it and we have to do it on the build server - not to mention it is a glorious HACK)
Is there a better way? I don't want to turn it off globally - just to suppress it for certain files or directories.
Any suggestions?
EDIT
For some stupid reason I didn't think I could set warning levels across include files. Thanks - that does the trick.
| Something like
#pragma warning(push, disable: 4201)
#include <mmsystem.h>
#pragma warning(pop)
|
1,723,575 | 1,723,938 | How to perform a bitwise operation on floating point numbers | I tried this:
float a = 1.4123;
a = a & (1 << 3);
I get a compiler error saying that the operand of & cannot be of type float.
When I do:
float a = 1.4123;
a = (int)a & (1 << 3);
I get the program running. The only thing is that the bitwise operation is done on the integer representation of the number obtained after rounding off.
The following is also not allowed.
float a = 1.4123;
a = (void*)a & (1 << 3);
I don't understand why int can be cast to void* but not float.
I am doing this to solve the problem described in Stack Overflow question How to solve linear equations using a genetic algorithm?.
| At the language level, there's no such thing as "bitwise operation on floating-point numbers". Bitwise operations in C/C++ work on value-representation of a number. And the value-representation of floating point numbers is not defined in C/C++ (unsigned integers are an exception in this regard, as their shift is defined as-if they are stored in 2's complement). Floating point numbers don't have bits at the level of value-representation, which is why you can't apply bitwise operations to them.
All you can do is analyze the bit content of the raw memory occupied by the floating-point number. For that you need to either use a union as suggested below or (equivalently, and only in C++) reinterpret the floating-point object as an array of unsigned char objects, as in
float f = 5;
unsigned char *c = reinterpret_cast<unsigned char *>(&f);
// inspect memory from c[0] to c[sizeof f - 1]
And please, don't try to reinterpret a float object as an int object, as other answers suggest. That doesn't make much sense, and is not guaranteed to work in compilers that follow strict-aliasing rules in optimization. The correct way to inspect memory content in C++ is by reinterpreting it as an array of [signed/unsigned] char.
Also note that you technically aren't guaranteed that floating-point representation on your system is IEEE754 (although in practice it is unless you explicitly allow it not to be, and then only with respect to -0.0, ±infinity and NaN).
|
1,723,629 | 1,723,781 | What happens when QueryPerformanceCounter is called? | I'm looking into the exact implications of using QueryPerformanceCounter in our system and am trying to understand it's impact on the application. I can see from running it on my 4-core single cpu machine that it takes around 230ns to run. When I run it on a 24-core 4 cpu xeon it takes around 1.4ms to run. More interestingly on my machine when running it in multiple threads they don't impact each other. But on the multi-cpu machine the threads cause some sort of interaction that causes them to block each other. I'm wondering if there is some shared resource on the bus that they all query? What exactly happens when I call QueryPerformanceCounter and what does it really measure?
| Windows QueryPerformanceCounter() has logic to determine the number of processors and invoke syncronization logic if necessary. It attempts to use the TSC register but for multiprocessor systems this register is not guaranteed to be syncronized between processors (and more importantly can vary greatly due to intelligent downclocking and sleep states).
MSDN says that it doesn't matter which processor this is called on so you may be seeing extra syncronization code for such a situation cause overhead. Also remember that it can invoke a bus transfer so you may be seeing bus contention delays.
Try using SetThreadAffinityMask() if possible to bind it to a specific processor. Otherwise you might just have to live with the delay or you could try a different timer (for example take a look at http://en.wikipedia.org/wiki/High_Precision_Event_Timer).
|
1,723,801 | 1,723,816 | IOServiceAddMatchingNotification issue | void functions::start()
{
io_iterator_t enumerator;
...some code...
result = IOServiceAddMatchingNotification(
mNotifyPort,
kIOMatchedNotification,
IOServiceMatching( "IOFireWireLocalNode" ),
serviceMatchingCallback,
(void *)0x1234,
&enumerator ); <=====
}
functions.cpp:83: error: argument of
type 'void (functions::)(void*,
io_iterator_t)' does not match 'void
()(void, io_iterator_t)'
does anyone know what this error mean? I am calling start() from main() through an object of functions ( eg, f->start(); )
i am using xcode and it highlights the line where the arrow points.
Thank you.
| What is serviceMatchingCallback? Judging by the error, it seems to be a member function. You can't pass a member function as a callback in this manner. See this recent discussion on calling a class member function from a callback.
|
1,723,977 | 1,724,126 | Accessing protected member functions from test code in C++ | I've been racking my brain trying to think of the best way to access a protected member function from some test code in C++, here's my problem:
//in Foo.h
Class Foo
{
protected:
void DoSomething(Data data);
}
//in Blah.h
Class Blah
{
public:
Foo foo;
Data data;
};
//in test code...
Blah blah;
blah.foo.DoSomething(blah.data); // Here's my problem!
Some possible solutions so far:
Make the test code class a friend of Foo, but this pollutes Foo with test code
Make DoSomething a public function
I've looked at creating a test wrapper for Foo, as suggested in this post, however this won't work as Blah contains the instance of Foo.
All advice/insight/opinions are most welcome!
Thanks
| Ok, since you said it is only a test code I am going to suggest something seriously hacky but would work:
struct tc : protected Foo
{
tc(Foo *foo, Data& data)
{
((tc*)foo)->DoSomething(data);
}
};
Blah blah;
tc t(&blah.foo, blah.data);
|
1,724,009 | 1,724,039 | Why doesn't my custom iterator work with the STL copy? | I wrote an OutputIterator for an answer to another question. Here it is:
#include <queue>
using namespace std;
template< typename T, typename U >
class queue_inserter {
queue<T, U> &qu;
public:
queue_inserter(queue<T,U> &q) : qu(q) { }
queue_inserter<T,U> operator ++ (int) { return *this; }
queue_inserter<T,U> operator * () { return *this; }
void operator = (const T &val) { qu.push(val); }
};
template< typename T, typename U >
queue_inserter<T,U> make_queue_inserter(queue<T,U> &q) {
return queue_inserter<T,U>(q);
}
This works great for this little copy function:
template<typename II, typename OI>
void mycopy(II b, II e, OI oi) {
while (b != e) { *oi++ = *b++; }
}
But it doesn't work at all for the STL copy from algorithms. Here are the wonderful C++ errors I get:
i.cpp:33: error: specialization of ‘template<class _Iterator> struct std::iterator_traits’ in different namespace
/usr/include/c++/4.0.0/bits/stl_iterator_base_types.h:127: error: from definition of ‘template<class _Iterator> struct std::iterator_traits’
/usr/include/c++/4.0.0/bits/stl_algobase.h: In function ‘_OI std::__copy_aux(_II, _II, _OI) [with _II = int*, _OI = queue_inserter<int, std::deque<int, std::allocator<int> > >]’:
/usr/include/c++/4.0.0/bits/stl_algobase.h:335: instantiated from ‘static _OI std::__copy_normal<true, false>::copy_n(_II, _II, _OI) [with _II = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _OI = queue_inserter<int, std::deque<int, std::allocator<int> > >]’
/usr/include/c++/4.0.0/bits/stl_algobase.h:387: instantiated from ‘_OutputIterator std::copy(_InputIterator, _InputIterator, _OutputIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _OutputIterator = queue_inserter<int, std::deque<int, std::allocator<int> > >]’
i.cpp:53: instantiated from here
/usr/include/c++/4.0.0/bits/stl_algobase.h:310: error: no type named ‘value_type’ in ‘struct std::iterator_traits<queue_inserter<int, std::deque<int, std::allocator<int> > > >’
/usr/include/c++/4.0.0/bits/stl_algobase.h:315: error: no type named ‘value_type’ in ‘struct std::iterator_traits<queue_inserter<int, std::deque<int, std::allocator<int> > > >’
/usr/include/c++/4.0.0/bits/stl_algobase.h:315: error: ‘__value’ is not a member of ‘<declaration error>’
/usr/include/c++/4.0.0/bits/stl_algobase.h:335: instantiated from ‘static _OI std::__copy_normal<true, false>::copy_n(_II, _II, _OI) [with _II = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _OI = queue_inserter<int, std::deque<int, std::allocator<int> > >]’
/usr/include/c++/4.0.0/bits/stl_algobase.h:387: instantiated from ‘_OutputIterator std::copy(_InputIterator, _InputIterator, _OutputIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _OutputIterator = queue_inserter<int, std::deque<int, std::allocator<int> > >]’
i.cpp:53: instantiated from here
/usr/include/c++/4.0.0/bits/stl_algobase.h:317: error: ‘__simple’ is not a valid template argument for type ‘bool’ because it is a non-constant expression
/usr/include/c++/4.0.0/bits/stl_algobase.h:317: error: ‘copy’ is not a member of ‘<declaration error>’
Here is the driver:
int main() {
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
queue<int> q;
copy( v.begin(), v.end(), make_queue_inserter(q) );
while (q.size() > 0) {
cout << q.front() << endl;
q.pop();
}
}
Why in the world is it specializing iterator_traits. What's wrong with my iterator? Can't I just write my own simple iterators?
| Your queue_inserter needs to be derived from std::iterator so that all the typedefs such as value_type are properly defined since these are used inside STL algorithms This definition works:
template< typename T, typename U >
class queue_inserter : public std::iterator<std::output_iterator_tag, T>{
queue<T, U> &qu;
public:
queue_inserter(queue<T,U> &q) : qu(q) { }
queue_inserter<T,U> operator ++ (int) { return *this; }
queue_inserter<T,U> operator ++ () { return *this; }
queue_inserter<T,U> operator * () { return *this; }
void operator = (const T &val) { qu.push(val); }
};
|
1,724,036 | 2,143,606 | Splitting templated C++ classes into .hpp/.cpp files--is it possible? | I am getting errors trying to compile a C++ template class which is split between a .hpp and .cpp file:
$ g++ -c -o main.o main.cpp
$ g++ -c -o stack.o stack.cpp
$ g++ -o main main.o stack.o
main.o: In function `main':
main.cpp:(.text+0xe): undefined reference to 'stack<int>::stack()'
main.cpp:(.text+0x1c): undefined reference to 'stack<int>::~stack()'
collect2: ld returned 1 exit status
make: *** [program] Error 1
Here is my code:
stack.hpp:
#ifndef _STACK_HPP
#define _STACK_HPP
template <typename Type>
class stack {
public:
stack();
~stack();
};
#endif
stack.cpp:
#include <iostream>
#include "stack.hpp"
template <typename Type> stack<Type>::stack() {
std::cerr << "Hello, stack " << this << "!" << std::endl;
}
template <typename Type> stack<Type>::~stack() {
std::cerr << "Goodbye, stack " << this << "." << std::endl;
}
main.cpp:
#include "stack.hpp"
int main() {
stack<int> s;
return 0;
}
ld is of course correct: the symbols aren't in stack.o.
The answer to this question does not help, as I'm already doing as it says.
This one might help, but I don't want to move every single method into the .hpp file—I shouldn't have to, should I?
Is the only reasonable solution to move everything in the .cpp file to the .hpp file, and simply include everything, rather than link in as a standalone object file? That seems awfully ugly! In that case, I might as well revert to my previous state and rename stack.cpp to stack.hpp and be done with it.
| It is not possible to write the implementation of a template class in a separate cpp file and compile. All the ways to do so, if anyone claims, are workarounds to mimic the usage of separate cpp file but practically if you intend to write a template class library and distribute it with header and lib files to hide the implementation, it is simply not possible.
To know why, let us look at the compilation process. The header files are never compiled. They are only preprocessed. The preprocessed code is then clubbed with the cpp file which is actually compiled. Now if the compiler has to generate the appropriate memory layout for the object it needs to know the data type of the template class.
Actually it must be understood that template class is not a class at all but a template for a class the declaration and definition of which is generated by the compiler at compile time after getting the information of the data type from the argument. As long as the memory layout cannot be created, the instructions for the method definition cannot be generated. Remember the first argument of the class method is the 'this' operator. All class methods are converted into individual methods with name mangling and the first parameter as the object which it operates on. The 'this' argument is which actually tells about size of the object which incase of template class is unavailable for the compiler unless the user instantiates the object with a valid type argument. In this case if you put the method definitions in a separate cpp file and try to compile it the object file itself will not be generated with the class information. The compilation will not fail, it would generate the object file but it won't generate any code for the template class in the object file. This is the reason why the linker is unable to find the symbols in the object files and the build fails.
Now what is the alternative to hide important implementation details? As we all know the main objective behind separating interface from implementation is hiding implementation details in binary form. This is where you must separate the data structures and algorithms. Your template classes must represent only data structures not the algorithms. This enables you to hide more valuable implementation details in separate non-templatized class libraries, the classes inside which would work on the template classes or just use them to hold data. The template class would actually contain less code to assign, get and set data. Rest of the work would be done by the algorithm classes.
I hope this discussion would be helpful.
|
1,724,051 | 1,724,176 | Const correctness for value parameters | I know there are few question about const correctness where it is stated that the declaration of a function and its definition do not need to agree for value parameters. This is because the constness of a value parameter only matters inside the function. This is fine:
// header
int func(int i);
// cpp
int func(const int i) {
return i;
}
Is doing this really a best practice? Because I've never seen anyone do it. I've seen this quotation (not sure of the source) in other places this has been discussed:
"In fact, to the compiler, the function signature is the same whether you include this const in front of a value parameter or not."
"Avoid const pass-by-value parameters in function declarations. Still make the parameter const in the same function's definition if it won't be modified."
The second paragraph says to not put the const in the declaration. I assume this is because the constness of a value parameter is meaningless as part of a interface definition. It is an implementation detail.
Based on this recommendation, is it also recommended for the pointer values of pointer parameters? (It is meaningless on a reference parameter since you can't reassign a reference.)
// header
int func1(int* i);
int func2(int* i);
// cpp
int func1(int* i) {
int x = 0;
*i = 3; // compiles without error
i = &x; // compiles without error
return *i;
}
int func2(int* const i) {
int x = 0;
*i = 3; // compiles without error
i = &x; // compile error
return *i;
}
Summary: Making value parameters is useful to catch some logic errors. Is it a best practice? Do you go to the extreme of leaving the const out of the header file? Is it just as useful to const pointer values? Why or why not?
Some references:
C++ const keyword - use liberally?
Use of 'const' for function parameters
An example of when const value parameters are useful:
bool are_ints_equal(const int i, const int j) {
if (i = j) { // without the consts this would compile without error
return true;
} else {
return false;
}
// return i = j; // I know it can be shortened
}
| My take on it:
It's not a bad idea, but the issue is minor and your energy might be better spent on other things.
In your question you provided a good example of when it might catch an error, but occasionally you also end up doing something like this:
void foo(const int count /* … */)
{
int temp = count; // can't modify count, so we need a copy of it
++temp;
/* … */
}
The pros and cons are minor either way.
|
1,724,186 | 1,724,514 | C++ std::string and NULL const char* | I am working in C++ with two large pieces of code, one done in "C style" and one in "C++ style".
The C-type code has functions that return const char* and the C++ code has in numerous places things like
const char* somecstylefunction();
...
std::string imacppstring = somecstylefunction();
where it is constructing the string from a const char* returned by the C style code.
This worked until the C style code changed and started returning NULL pointers sometimes. This of course causes seg faults.
There is a lot of code around and so I would like to most parsimonious way fix to this problem. The expected behavior is that imacppstring would be the empty string in this case. Is there a nice, slick solution to this?
Update
The const char* returned by these functions are always pointers to static strings. They were used mostly to pass informative messages (destined for logging most likely) about any unexpected behavior in the function. It was decided that having these return NULL on "nothing to report" was nice, because then you could use the return value as a conditional, i.e.
if (somecstylefunction()) do_something;
whereas before the functions returned the static string "";
Whether this was a good idea, I'm not going to touch this code and it's not up to me anyway.
What I wanted to avoid was tracking down every string initialization to add a wrapper function.
| Probably the best thing to do is to fix the C library functions to their pre-breaking change behavior. but maybe you don't have control over that library.
The second thing to consider is to change all the instances where you're depending on the C lib functions returning an empty string to use a wrapper function that'll 'fix up' the NULL pointers:
const char* nullToEmpty( char const* s)
{
return (s ? s : "");
}
So now
std::string imacppstring = somecstylefunction();
might look like:
std::string imacppstring( nullToEmpty( somecstylefunction());
If that's unacceptable (it might be a lot of busy work, but it should be a one-time mechanical change), you could implement a 'parallel' library that has the same names as the C lib you're currently using, with those functions simply calling the original C lib functions and fixing the NULL pointers as appropriate. You'd need to play some tricky games with headers, the linker, and/or C++ namespaces to get this to work, and this has a huge potential for causing confusion down the road, so I'd think hard before going down that road.
But something like the following might get you started:
// .h file for a C++ wrapper for the C Lib
namespace clib_fixer {
const char* somecstylefunction();
}
// .cpp file for a C++ wrapper for the C Lib
namespace clib_fixer {
const char* somecstylefunction() {
const char* p = ::somecstylefunction();
return (p ? p : "");
}
}
Now you just have to add that header to the .cpp files that are currently calling calling the C lib functions (and probably remove the header for the C lib) and add a
using namespace clib_fixer;
to the .cpp file using those functions.
That might not be too bad. Maybe.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.