question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,916,492 | 2,916,657 | Can boost::program_options Use A Delimiter Other Than "-"? | I am using boost::program_options like this:
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,?", "Show Options")
("capture-file,I", po::value<string>(), "Capture File")
("capture-format,F", po::value<string>()->default_value("pcap"), "Capture File Format")
("output-file,O", po::value<string>()->default_value("CONOUT$"), "Output File");
po::variables_map vm;
po::store(po::command_line_parser(ac, av).options(desc)./*positional(pd).*/run(), vm);
If I pass the command line parameter -I hithere it works, but it I pass /I hithere boost throws a boost::bad_any_cast with a what() of " failed conversion using boost::any_cast".
Is it possible to use program_options to parse either /-delimitted or --delimitted options? Bonus question, can it be configured so that / and - set the same option, but are binary opposites of each other? For example, /verbose might mean verbose logging while -verbose might mean less verbose logging.
| To use / and -, use command_line_parser's style() method with the appropriate combination of style_t flags. For example:
po::store(po::command_line_parser(ac, av)
.options(desc)
.style(po::command_line_style::default_style
| po::command_line_style::case_insensitive
| po::command_line_style::allow_slash_for_short
| po::command_line_style::allow_long_disguise)
/*.positional(pd)*/
.run(), vm);
(allow_long_disguise lets / start a long option.)
You could probably make / and - opposites by adding your own additional parser; however, this would be very nonstandard and therefore potentially confusing to end users, so I'm not sure it's a good idea.
|
2,916,549 | 2,916,779 | ~1s latency control app: is this suitable for Java? | At my work we recently finished the system architecture for a control application which has a maximum latency of roughly one to two seconds. It is distributed on small ARM on-chip boxes communicating via an IP LAN.
We initially foresee that we would use C or C++, since it is a classical control system language. After discussing how to implement the application we now realize that C++ has a quite limited amount of libraries, lacks introspection, and has some other properties which might slow down development. My colleague then suggested that Java might be up for the job.
I'm really scared about the latency of running a GC for a control app, and I'm also reluctant to drop RAII, since the app will use a lot of external resources (sockets, file handles, handles from external libs etc).
The pro/con list is currently as follows:
C++
+ RAII - Easy resource management - it will be a complex system
+ System language - speed if we cant't find a JIT VM for our ARM
+ No GC - no big worst case latencies from the GC
+ Easy to integrate with some shared mem libs that we have to interface with
- Fewer free as in beer libs
- Lacks introspection - Mapping classes to DB and external data formats (XML)
would benefit from this (ORM /JAXB) approach
- Easy to shoot one self in the foot - hard and expensive to find programmers
which don't make big mistakes
- Memory fragmentation - needs tuning and workarounds
Java
+ Huge amount of libs
+ Introspection - serialization becomes a breeze (see C++ section)
+ Easier to find 'good enough' programmers
- No RAII - Client has to remember finally or you leak
resources. IMO Java programmers tend to ignore this
problem unless they have server app background.
- No System Language - possibly slower although ARMj could alleviate this
- GC - latency might go up (don't know if parallel GC will work - seems that
you might get fragmentation, see note below).
- Need to write JNI for the shared mem libs that we interface with
- Maybe ORACLE will eat us
The memory fragmentation with parallel GC was mentioned in this AMD article
I would love to use Java if GC latency wasn't a problem and we could get RAII. Therefore
I've also looked into other langs which have RAII and could serve as good alternatives, and so far I've found that D,Ada,VB,Perl,Python(C),PHP,tcl and Lua seem to have some sort of out-of-scope callback. My spontainous reaction that perhaps D, Python, and ADA could be suitable for a control app. D and ADA are my favourites.
So, my question is: do you have any recommendations on this? Is Java a viable option, and if you could choose any language, what would it be?
| The GC is only used for reclaiming memory from discarded objects. Discard very little resources and you will get very little, shorter GCs.
You might use lots of sockets, file handles, handles from external libs, but how fast do you discard them?
A full GC is designed to remove fragmentation. It does this by copying all the memory so it is used continously. This is why its is expensive, so you want to minimise these if latency is important to you. That said, if your full GCs are taking more than 100 ms, you have a serious performance issue. It shouldn't be that high.
IMHO, I short you should be able to develop a control system with a latency which is well under 10 ms, 99%+ of the time.
|
2,916,592 | 2,916,866 | Qt Won't Compile (10.5 Intel Mac) | I am trying to compile the latest version of Qt for the mac (from Gitorius). When I try to compile this (by doing ./configure and then make), I get the following error while running make:
../../include/QtCore/../../src/corelib/kernel/qvariant.h: In function ‘T qvariant_cast(const QVariant&) [with T = QVariant]’:
../../include/QtCore/../../src/corelib/kernel/qvariant.h:592: error: ‘QVariant’ is not a member of ‘QMetaType’
make[2]: *** [.pch/debug-shared/QtCore_debug.gch/objective-c++] Error 1
make[1]: *** [debug-all] Error 2
make: *** [sub-corelib-make_default-ordered] Error 2
Thanks.
| Did you downloaded a stable version? Because you might accidentaly downloaded a beta/unstable version from Gitorious, which might not compile
Also, just download an appropiate stable version tarball from ftp.trolltech.com and compile it.
|
2,916,675 | 4,251,093 | Programmatically obtain DNS servers of host | Using C++, I would like to obtain the DNS servers being used by a host for three operating systems: OS X, FreeBSD, and Windows. I'd like confirmation that the approaches below are indeed best practice, and if not, a superior alternative.
OS X: already answered; updated link at developer.apple.com
Windows: GetNetworkParams
FreeBSD: /etc/resolv.conf
Thanks in advance for your help!
| On many unix systems (linux, bsd) you can use the resolver functions to obtain the list of DNS servers: man 3 resolver.
After calling res_init() the resolver structure is initialized. The resolver structure stores all the information you need. The list of DNS servers are stored in the struct entry nsaddr_list.
The exact specification of the resolver structure can most likely be found in resolv.h.
Using the resolver functions is the preferred way to obtain the list of DNS servers. res_init() will most likely fill the resolver structure with the information found in /etc/resolv.conf.
Also see Use of resolv.h
|
2,916,691 | 2,916,842 | Visual C++: Compiler Error C4430 | The code of Game.h:
#ifndef GAME_H
#define GAME_H
class Game
{
public:
const static string QUIT_GAME; // line 8
virtual void playGame() = 0;
};
#endif
The error:
game.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
game.h(8): error C2146: syntax error : missing ';' before identifier 'QUIT_GAME'
game.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
What am I doing wrong?
| Here is what you need to fix your issues:
1. Include the string header file:
#include <string>
2. Prefix string with its namespace:
const static std::string QUIT_GAME;
or insert a using statement:
#include <string>
using std::string;
3. Allocate space for the variable
Since you declared it as static within the class, it must be defined somewhere in the code:
const std::string Game::QUIT_GAME;
4. Initialize the variable with a value
Since you declared the string with const, you will need to initialize it to a value (or it will remain a constant empty string).:
const std::string Game::QUIT_GAME = "Do you want to quit?\n";
|
2,916,759 | 2,916,893 | undefined reference to static member variable | I have this class that has a static member. it is also a base class for several other classes in my program. Here's its header file:
#ifndef YARL_OBJECT_HPP
#define YARL_OBJECT_HPP
namespace yarlObject
{
class YarlObject
{
// Member Variables
private:
static int nextID; // keeps track of the next ID number to be used
int ID; // the identifier for a specific object
// Member Functions
public:
YarlObject(): ID(++nextID) {}
virtual ~YarlObject() {}
int getID() const {return ID;}
};
}
#endif
and here's its implementation file.
#include "YarlObject.hpp"
namespace yarlObject
{
int YarlObject::nextID = 0;
}
I'm using g++, and it returns three undefined reference to 'yarlObject::YarlObject::nextID linker errors. If I change the ++nextID phrase in the constructor to just nextID, then I only get one error, and if I change it to 1, then it links correctly. I imagine it's something simple, but what's going on?
| Make sure you are linking against the generated .o file. Double-check the makefile.
|
2,917,168 | 2,917,221 | functional, bind1st and mem_fun | Why won't this compile?
#include <functional>
#include <boost/function.hpp>
class A {
A() {
typedef boost::function<void ()> FunctionCall;
FunctionCall f = std::bind1st(std::mem_fun(&A::process), this);
}
void process() {}
};
Errors:
In file included from /opt/local/include/gcc44/c++/bits/stl_function.h:712,
from /opt/local/include/gcc44/c++/functional:50,
from a.cc:1:
/opt/local/include/gcc44/c++/backward/binders.h: In instantiation of 'std::binder1st<std::mem_fun_t<void, A> >':
a.cc:7: instantiated from here
/opt/local/include/gcc44/c++/backward/binders.h:100: error: no type named 'second_argument_type' in 'class std::mem_fun_t<void, A>'
/opt/local/include/gcc44/c++/backward/binders.h:103: error: no type named 'first_argument_type' in 'class std::mem_fun_t<void, A>'
/opt/local/include/gcc44/c++/backward/binders.h:106: error: no type named 'first_argument_type' in 'class std::mem_fun_t<void, A>'
/opt/local/include/gcc44/c++/backward/binders.h:111: error: no type named 'second_argument_type' in 'class std::mem_fun_t<void, A>'
/opt/local/include/gcc44/c++/backward/binders.h:117: error: no type named 'second_argument_type' in 'class std::mem_fun_t<void, A>'
/opt/local/include/gcc44/c++/backward/binders.h: In function 'std::binder1st<_Operation> std::bind1st(const _Operation&, const _Tp&) [with _Operation = std::mem_fun_t<void, A>, _Tp = A*]':
a.cc:7: instantiated from here
/opt/local/include/gcc44/c++/backward/binders.h:126: error: no type named 'first_argument_type' in 'class std::mem_fun_t<void, A>'
In file included from /opt/local/include/boost/function/detail/maybe_include.hpp:13,
from /opt/local/include/boost/function/detail/function_iterate.hpp:14,
from /opt/local/include/boost/preprocessor/iteration/detail/iter/forward1.hpp:47,
from /opt/local/include/boost/function.hpp:64,
from a.cc:2:
/opt/local/include/boost/function/function_template.hpp: In static member function 'static void boost::detail::function::void_function_obj_invoker0<FunctionObj, R>::invoke(boost::detail::function::function_buffer&) [with FunctionObj = std::binder1st<std::mem_fun_t<void, A> >, R = void]':
/opt/local/include/boost/function/function_template.hpp:913: instantiated from 'void boost::function0<R>::assign_to(Functor) [with Functor = std::binder1st<std::mem_fun_t<void, A> >, R = void]'
/opt/local/include/boost/function/function_template.hpp:722: instantiated from 'boost::function0<R>::function0(Functor, typename boost::enable_if_c<boost::type_traits::ice_not::value, int>::type) [with Functor = std::binder1st<std::mem_fun_t<void, A> >, R = void]'
/opt/local/include/boost/function/function_template.hpp:1064: instantiated from 'boost::function<R()>::function(Functor, typename boost::enable_if_c<boost::type_traits::ice_not::value, int>::type) [with Functor = std::binder1st<std::mem_fun_t<void, A> >, R = void]'
a.cc:7: instantiated from here
/opt/local/include/boost/function/function_template.hpp:153: error: no match for call to '(std::binder1st<std::mem_fun_t<void, A> >) ()'
| Because bind1st requires a binary function object. However you pass an unary function object. The function object binders of C++03 aren't as sophisticated as the one found in boost or tr1. In fact, they suffer from basic problems like not being able to handle functions with reference parameters.
Since you already use boost, i recommend to use boost::bind
FunctionCall f = boost::bind(&A::process, this); // yay!
|
2,917,436 | 2,917,470 | Why are enums considered compound types? | Arrays, functions, pointers, references, classes, unions, enumerations and pointers to members are compound types.
My understanding of a compound type is that is based on other type(s). For example, T[n], T* and T& are all based on T. Then what other type(s) is an enumeration based on?
Or if my understanding of compound types is incorrect, what exactly is it about a type that makes it a compound type? Is compound simply a synonym for user-defined?
| In C++ enum types are scalar types, yet at the same time they are compound types since they are built on top of some fundamental integral type. In case of an array or pointer you specify "base" type explicitly, but in case of an enum the specific underlying integral type is chosen implicitly and automatically by the implementation. You have no manual control over the underlying integral type, which still doesn't disqualify enum types from being compound in nature.
Some compilers (as well as future C++ standard C++0x) allow user to specify the underlying integer type for given enum type, which makes it more obvious that it is in fact a compound type. See here for examples like
enum class Color : char { red, blue };
|
2,917,828 | 2,917,870 | Noise with multi-threaded raytracer | This is my first multi-threaded implementation, so it's probably a beginners mistake. The threads handle the rendering of every second row of pixels (so all rendering is handled within each thread). The problem persists if the threads render the upper and lower parts of the screen respectively.
Both threads read from the same variables, can this cause any problems? From what I've understood only writing can cause concurrency problems...
Can calling the same functions cause any concurrency problems? And again, from what I've understood this shouldn't be a problem...
The only time both threads write to the same variable is when saving the calculated pixel color. This is stored in an array, but they never write to the same indices in that array. Can this cause a problem?
Multi-threaded rendered image
(Spam prevention stops me from posting images directly..)
Ps. I use the exactly same implementation in both cases, the ONLY difference is a single vs. two threads created for the rendering.
|
Both threads read from the same variables, can this cause any problems? From what I've understood only writing can cause concurrency problems...
This should be ok. Obviously, as long the data is initialized before the two threads start reading and destroyed after both threads have finished.
Can calling the same functions cause any concurrency problems? And again, from what I've understood this shouldn't be a problem...
Yes and no. Too hard to tell without the code. What does the function do? Does it rely on shared state (e.g. static variables, global variables, singletons...)? If yes, then this is definitely a problem. If there is never any shared state, then you're ok.
The only time both threads write to the same variable is when saving the calculated pixel color. This is stored in an array, but they never write to the same indices in that array. Can this cause a problem?
Maybe sometimes. An array of what? It's probably safe if sizeof(element) == sizeof(void*), but the C++ standard is mute on multithreading, so it doesn't force your compiler to force your hardware to make this safe. It's possible that your platform could be biting you here (e.g. 64bit machine and one thread writing 32bits which might overwrite an adjacent 32bit value), but this isn't an uncommon pattern. Usually you're better off using synchronization to be sure.
You can solve this in a couple of ways:
Each thread builds its own data, then it is aggregated when they complete.
You can protect the shared data with a mutex.
The lack of commitment in my answers are what make multi-threaded programming hard :P
For example, from Intel® 64 and IA-32 Architectures Software Developer's Manuals, describes how different platforms gaurantee different levels of atomicity:
7.1.1 Guaranteed Atomic Operations
The Intel486 processor (and newer
processors since) guarantees that the
following basic memory operations will
always be carried out atomically:
Reading or writing a byte
Reading or writing a word aligned on a 16-bit boundary
Reading or writing a doubleword aligned on a 32-bit boundary
The Pentium processor (and newer
processors since) guarantees that the
following additional memory operations
will always be carried out atomically:
Reading or writing a quadword aligned on a 64-bit boundary
16-bit accesses to uncached memory locations that fit within a 32-bit data bus
The P6 family processors (and newer
processors since) guarantee that the
following additional memory operation
will always be carried out atomically:
Unaligned 16-, 32-, and 64-bit accesses to cached memory that fit within a cache line
Accesses to cacheable memory that are
split across bus widths, cache lines,
and page boundaries are not guaranteed
to be atomic by the Intel Core 2 Duo,
Intel Atom, Intel Core Duo, Pentium M,
Pentium 4, Intel Xeon, P6 family,
Pentium, and Intel486 processors. The
Intel Core 2 Duo, Intel Atom, Intel
Core Duo, Pentium M, Pentium 4, Intel
Xeon, and P6 family processors provide
bus control signals that permit
external memory subsystems to make
split accesses atomic; however,
nonaligned data accesses will
seriously impact the performance of
the processor and should be avoided.
|
2,917,897 | 2,918,160 | How should I pass an object wrapping an API to a class using that API? | This is a revised/better written version of the question I asked earlier today -- that question is deleted now.
I have a project where I'm getting started with Google Mock. I have created a class, and that class calls functions whithin the Windows API. I've also created a wrapper class with virtual functions wrapping the Windows API, as described in the Google Mock CheatSheet. I'm confused however at how I should pass the wrapper into my class that uses that object. Obviously that object needs to be polymorphic, so I can't pass it by value, forcing me to pass a pointer. That in and of itself is not a problem, but I'm confused as to who should own the pointer to the class wrapping the API.
So... how should I pass the wrapper class into the real class to facilitate mocking?
Here's an example of what I mean:
struct A {
virtual void SomeMethod(int x, int y)
{
::SomeMethod(x, y);
};
};
class Client
{
A * method_;
public:
Client(A * method = new A) : method_(method) {};
void DoSomething()
{
method_->SomeMethod(42, 34);
}
};
struct Mock : public A
{
MOCK_METHOD2(SomeMethod, void(int, int));
};
TEST(MyTest, MyTestWithMock)
{
Mock * mock = new Mock();
EXPECT_CALL(*mock, SomeMethod(42, 34)).Times(1);
Client client(mock); //Should *client* be responsable for deleting mock?
client.DoSomething();
};
EXAMPLE 2:
struct A {
virtual void SomeMethod(int x, int y)
{
::SomeMethod(x, y);
};
};
class Client
{
A * method_;
public:
Client(A * method) : method_(method) {};
static Client Create()
{
static A;
return Client(&A);
}
void DoSomething()
{
method_->SomeMethod(42, 34);
}
};
struct Mock : public A
{
MOCK_METHOD2(SomeMethod, void(int, int));
};
TEST(MyTest, MyTestWithMock)
{
Mock mock;
EXPECT_CALL(mock, SomeMethod(42, 34)).Times(1);
Client client(&mock);
client.DoSomething();
};
| There's always the option of using shared_ptr; that would certainly solve the ownership problem.
|
2,917,904 | 2,917,914 | Show descrition text (WINAPI) | I was wondering how I can show description text. By this I mean, for example if you hover over the Start button a small description will appear saying "Start". How are these invoked?
Thanks
| You are looking for Tooltip Controls
|
2,918,008 | 2,918,140 | Getting values of an object after a call to rotatef c++ | I need to access the X,Y values of a vertex object after Ive rotated it (with glRotate3f). How is it possible? I need em to solve an object collision problem where collisions will be sending objects in an angle related direction based upon objects rotation degrees.
edit::
Ok, Ive come close to find a way. Lets assume X and Y and degrees 0, 90 , 180, 270. I set a point as the center of the object, lets assume X=30, Y=70 and the X_size is 60 and Y_size is 140.
If I make new_X = Xcos(angle) - Ysen(angle) and new_Y = Xsen(angle) + Ycos(angle) if then I add or subtract the object center X and Y to new_X and new_Y I actually get to the new point except when angle is 180 where I would need to go with -new_X + X.
Is this the way to solve it?
| You are misunderstanding things a bit.
You didn't rotate anything by calling glRotatef. When you call glRotate, you modify transformation matrix, the object data remains unchanged. When you render object, the vertex data goes through vertex processing pipeline, gets multiplied by transformation matrix (every time you render object) and technically, you can't get result of calculations back - because object wasn't changed.
Well, if you really want it, you could try using gl feedback buffers (see glFeedbackBuffer), but I don't see a reason for that. I think that "OpenGL red book" may have feedback buffer examples, but I'm not sure about that. Feedback buffers MAY provide functionality you need, but I really haven't used them much, so I'm not sure about it either.
Also, moving lots of data back and forward between system memory and video memory (when your object is stored in video memory) leads to performance losses, so you shouldn't do that even if you can.
If you want to get object state after rotation, you will have to multiply it by hand - using object's matrix and store a copy in system memory. Since OpenGL combines object matrix with view matrix (when you call glRotatef), then you'll need to store rotation matrix separately.
Is this the way to solve it?
Maybe only if you're working with 2D, and rendering one triangle or two.
Normally when you do transformations, you build combined rotation/translations matrix, then multiply data you need using that matrix - this will be more efficient, because it allows to combine multiple transformations into one. And if you work with non-graphical 3D routines (collision detection), you do matrix multiplications/vector transformation in your code, yourself.
AFAIK OpenGL doesn't provide matrix manipulation routines (similar to D3DXMatrixMultiply in D3DX), but they are easy to write from scratch, and can be taken from multiple places. And you can use D3DX matrix functions, if you're desperate (D3D matrices have same memory layout). Besides, if you're serious about working with 3D, you'll have to learn matrices eventually.
|
2,918,202 | 2,918,235 | Where is shared_ptr? | I am so frustrated right now after several hours trying to find where shared_ptr is located. None of the examples I see show complete code to include the headers for shared_ptr (and working). Simply stating std, tr1 and <memory> is not helping at all! I have downloaded boosts and all but still it doesn't show up! Can someone help me by telling exactly where to find it?
Thanks for letting me vent my frustrations!
EDIT:
I see my title has been changed. Sorry about that.
So... it was also because it was not clear to me that shared_ptr is "C++ version dependant" --> that's why I did not state my environment --> therefore probably why it was so difficult for me to find it.
I am working on MSVS2008.
EDIT 2:
I don't know why, but I was including [memory] and [boost/tr1/memory.hpp] and [boost/tr1/tr1/memory] while looking everywhere for the shared_ptr.. of course, i couldn't.
Thanks for all the responses.
| There are at least three places where you may find shared_ptr:
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.
If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.
Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.
|
2,918,225 | 2,921,065 | CImg compile problems in Codegear 2009 | I wish to use the CImg library for image processing in my current project. I am using Codegear C++ Builder 2009. I include CImg.h in the source file and put in the following code:
int rows =5;
int cols = 5;
CImg<double> img(rows,cols);
I get the following error:
[BCC32 Error] CImg.h(39159): E2285 Could not find a match for 'CImg<unsigned char>::move_to<t>(const CImg<unsigned char>)'
Does anyone know if there is a #define I should be using when building in Codegear C++ Builder 2009. Or is it simply not compatible?
| A 40,000 line library that's contained in a single header file? That seems like a bad idea...
Anyway, unfortunately, C++Builder 2009 isn't a very good C++ compiler, so it will often fail to handle otherwise legal C++ constructs. (It's not unusual for C++ compilers to fail to properly handle one aspect or another of the C++ standard, just because C++ is such a complicated language.)
When this happens, your main choices are to find another library, find another compiler, wait for a new and hopefully better version of C++Builder, or try and tweak the library to make it work.
In this case, if you decide to try and make the library work, the following changes should get you started:
For the template version of `move_to` (line 9145 in CImg 1.3.4), C++Builder fails to detect t as a template parameter to the `move_to` parameter. Change the function declaration from its current type-safe version:
template<typename t>
CImg<t>& move_to(CImg<t>& img) {
to the simpler
template<typename t>
t& move_to(t& image) {
Help C++Builder figure out the proper template parameters for the draw_text call on line 39163: replace draw_text(...) with draw_text<unsigned char,unsigned char>(...).
There are more compiler errors than just these two; you'll have to similarly adjust the CImg source code for those.
If you're able to get everything working, then once you're done, you can see if the CImg project is interested in incorporating your changes to add C++Builder support to their official release.
|
2,918,351 | 2,918,359 | How can I pass Arguments to a C++ program started by the Registry? | I'm creating a Win32 program that will be executed every time the computer turns on. I manage to do this by adding the .exe path into the registry. The problem is; I want to make the program appear minimized in the system tray when the computer is turned on but if I double click it [after the computer turns on and the program is not currently running] the program should appear on its normal [maximized] size.
Question, I was thinking on whether is was possible to pass an argument to the program when the program is executed from the registry. Is this possible? If yes/no, how would I manage to do this?
(Using windows XP) Thanks.
| Even if it's not possible to launch your program with command line arguments from the registry, you can use a batch script to do so. Just create a batch script that launches your program with the appropriate arguments, and use the registry to run that batch script instead.
|
2,918,353 | 2,918,470 | Obtaining command line arguments in a Qt application | The following snippet is from a little app I wrote using the Qt framework. The idea is that the app can be run in batch mode (i.e. called by a script) or can be run interactively.
It is important therefore, that I am able to parse command line arguments in order to know which mode in which to run etc.
[Edit]
I am debugging using Qt Creator 1.3.1 on Ubuntu Karmic. The arguments are passed in the normal way (i.e. by adding them via the 'Project' settings in the Qt Creator IDE).
When I run the app, it appears that the arguments are not being passed to the application. The code below, is a snippet of my main() function.
int main(int argc, char *argv[])
{
//Q_INIT_RESOURCE(application);
try {
QApplication the_app(argc, argv);
//trying to get the arguments into a list
QStringList cmdline_args = QCoreApplication::arguments();
// Code continues ...
}
catch (const MyCustomException &e) { return 1; }
return 0;
}
[Update]
I have identified the problem - for some reason, although argc is correct, the elements of argv are empty strings.
I put this little code snippet to print out the argv items - and was horrified to see that they were all empty.
for (int i=0; i< argc; i++){
std::string s(argv[i]); //required so I can see the damn variable in the debugger
std::cout << s << std::endl;
}
Does anyone know how I can retrieve the command line args in my application?
| If your argc and argv are good, I'm surprised this would be possible as QApplication::arguments() is extremely simple. Note the source code. Filtering the #ifdefs for Linux, it's just:
QStringList QCoreApplication::arguments()
{
QStringList list;
if (!self) {
qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
return list;
}
const int ac = self->d_func()->argc;
char ** const av = self->d_func()->argv;
for (int a = 0; a < ac; ++a) {
list << QString::fromLocal8Bit(av[a]);
}
return list;
}
That's all you've got. There's a Unicode caveat which I would not think would apply to Karmic:
"On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit(); hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based."
You might try a copy of that code against your argc and argv directly and see what happens.
|
2,918,380 | 2,918,627 | Can my thread help the OS decide when to context switch it out? | I am working on a threaded application on Linux in C++ which attempts to be real time, doing an action on a heartbeat, or as close to it as possible.
In practice, I find the OS is swapping out my thread and causing delays of up to a tenth of a second while it is switched out, causing the heartbeat to be irregular.
Is there a way my thread can hint to the OS that now is a good time to context switch it out? I could make this call right after doing a heartbeat, and thus minimize the delay due to an ill timed context switch.
| It is hard to say what the main problem is in your case, but it is most certainly not something that can be corrected with a call to sched_yield() or pthread_yield(). The only well-defined use for yielding, in Linux, is to allow a different ready thread to preempt the currently CPU-bound running thread at the same priority on the same CPU under SCHED_FIFO scheduling policy. Which is a poor design decision in almost all cases.
If you're serious about your goal of "attempting to be real-time" in Linux, then first of all, you should be using a real-time sched_setscheduler setting (SCHED_FIFO or SCHED_RR, FIFO preferred).
Second, get the full preemption patch for Linux (from kernel.org if your distro does not supply one. It will also give you the ability to reschedule device driver threads and to execute your thread higher than, say, hard disk or ethernet driver threads.
Third, see RTWiki and other resources for more hints on how to design and set up a real-time application.
This should be enough to get you under 10 microseconds response time, regardless of system load on any decent desktop system. I have an embedded system where I only squeeze out 60 us response idle and 150 us under heavy disk/system load, but it's still orders of magnitude faster than what you're describing.
|
2,918,414 | 2,918,545 | C++ Templates: Convincing self against code bloat | I have heard about code bloats in context of C++ templates. I know that is not the case with modern C++ compilers. But, I want to construct an example and convince myself.
Lets say we have a class
template< typename T, size_t N >
class Array {
public:
T * data();
private:
T elems_[ N ];
};
template< typename T, size_t N >
T * Array<T>::data() {
return elems_;
}
Further, let's say types.h contains
typedef Array< int, 100 > MyArray;
x.cpp contains
MyArray ArrayX;
and y.cpp contains
MyArray ArrayY;
Now, how can I verify that the code space for MyArray::data() is same for both ArrayX and ArrayY?
What else I should know and verify from this (or other similar simple) examples? If there is any g++ specific tips, I am interested for that too.
PS: Regarding bloat, I am concerned even for the slightest of bloats, since I come from embedded context.
Addition: Does the situation change anyhow if the template classes are explicitly instantiated?
| You're asking the wrong question - any "bloat" in your example has nothing to do with templates. (the answer to your question, btw, is to take the address of the member function in both modules and you'll see they're the same)
What you really want to ask is, for each template instantiation, does the resulting executable grow linearly? The answer is no, the linker/optimizer will do magic.
Compile an exe that creates one type:
Array< int, 100 > MyArray;
Note the resulting exe size. Now do it again:
Array< int, 100 > MyArray;
Array< int, 99 > MyArray;
And so on, for 30 or so different versions, charting the resulting exe sizes. If templates were as horrible as people think, the exe size would grow by a fixed amount for each unique template instantiation.
|
2,918,579 | 2,918,594 | Read all files inside a folder including files in subfolders using C++ | I want to read all files inside a given folder(path to folder) using FindFirstFile method provide in windows API. Currently I'm only succeeded in reading files inside the given folder. I could not read files inside sub folders. Can anyone help me to do this??
| When you call FindFirstFile/FindNextFile, some of the "files" it returns will actually be directories.
You can check if something is a directory or not by looking at the dwFileAttributes field of the WIN32_FIND_DATA structure that gets returned to you.
If you find one that is a directory, then you can simply call your file finding function recursively to go into the subfolders.
Note: Make sure to put in a special case for the . and .. psuedo-directories, otherwise your function will recurse into itself and you'll get a stack overflow
Here's the documentation if you haven't already found it:
FindFirstFile
WIN32_FIND_DATA
possible values for dwFileAttributes (remember these are all bit flags, so you'll have to use & to check)
|
2,919,120 | 2,919,187 | How can I call Objective-C code (specifically code from Mac system libraries) from C++/Qt? | Also, what is the difference between a .m and a .mm file? Or is that just some convention that Nokia uses for Qt?
| .m refers to an Objective-C file, whereas .mm is an Objective-C++. I'm not sure whose convention that is.
As for calling Objective-C from C++, this might help:
http://sseyod.blogspot.com/2009/02/objective-c.html
|
2,919,161 | 2,919,189 | what is the Different categories of pointers? | Can any body explains about the different categories of pointer(like wild pointers)?
|
Valid pointer: one pointing to a real object in memory
Invalid pointer: one pointing to memory that is not what it is supposed to be.
NULL pointer: A pointer whose value is 0 and thus points at nothing.
Dangling pointer (also sometimes wild pointer): one pointing to memory that has been deleted/freed.
Smart pointer: Not really a pointer at all, but rather an object which acts like a pointer, but manages the memory for you.
|
2,919,254 | 2,919,336 | Any tips for how to build a LED system thet will light up to music? | So basically I would like somehow that given an audio file as input (most likely mp3 or I can use some audio engine that will handle other types too) from my computer to control some LED lights so they will be something like an oscilloscope, like the one in winamp.
What would I need to be able to do this? I'm interested in building thing up all by myself, coding, hardware, etc..
I'm going with C++ on Windows.
| Here is a possible approach (high level description):
You could have a simple micro controller (MCU) in a basic circuit with a number of LEDs connected. LED connection circuitry should be easy to find. Most MCU manufacturers will also give a sample test/LED flash circuit in the product datasheet, along with a sample program.
The MCU could interface with your PC via a parallel port (I have used an ATmega8 for which the input pins were level compatible with the parallel port pins). It could also interface using a more sophisticated/higher level approach - via serial/usb port using a UART to serial or UART to USB module with your MCU. You could then output different values via the parallel/serial/usb from a PC application to the MCU, and have the MCU code flash the LEDs as required. There are some articles around that power LEDs from the parallel port itself though this is not recommended. I have used inpout32.dll for accessing the parallel port registers directly. The .NET framework provides a SerialPort class you could use if not using the parallel port approach.
As for the music side of things, I've never dealt with audio files in software. There should be some libraries around and you could perhaps scale amplitude/frequency variations over time to a numerical scale displayable on the LEDs you have. Since this implies you want a basic audio player I am sure you could find some info on the audio side of things for PC apps.
EDIT:
With my answer I assumed this is for a personal project and proposed an approach that would be easy on the budget - a few $ at the local electronics store should get you everything. This is a good start, but as the other answers suggest there are likely better solutions that scale. Starting with a kit - pre-made MCU board might be easier but more expensive! It would likely be worth the cost if it is for a professional project though!
Good luck!
|
2,919,378 | 2,919,398 | How to enable core dump in my Linux C++ program | My program is written in C++. compiled with gcc, using -g3 -O0 -ggdb flags. When it crashes, I want to open its core dump. Does it create core dump file, or I need to do something to enable core dump creation, in the program itself, or on computer where it is executed? Where this file is created, and what is its name?
| You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.
|
2,919,446 | 2,919,474 | What is it in MVVM that makes it particularly appealing for managed WPF and Silverlight but not native C++? |
What is it in WPF and Silverlight that makes MVVM suit them so well?
What is it in C++, or what does C++ lack, that makes MVVM and C++ never be mentioned together?
| MVVM (Model - View - ViewModel) is an adaptation of the MVP (Model -View - Presenter) or MVC (Model - View - Controller) patterns, both of which are very popular design patterns for C++ applications. The main changes to the design pattern are to better support WPF and Silverlight so it isn't so much that WPF suits MVVM, more that MVVM suits WPF.
Primarily the changes revolve around cleanly supporting the binding and command architecture present in the XAML technologies through use of INotifyPropertyChanged and ICommand objects. Once again these changes wouldn't help in C++ since it doesn't have any native support for these high-level concepts. That isn't to say that you couldn't mimic all this functionality in C++, but on the way you would pass through using a basic MVP/C pattern and in most cases that is "good enough".
|
2,919,525 | 2,926,820 | CComModule::Unlock(); | I've been trying to determine what this function does, however I cannot seem to find it anywhere under the MSDN documentation of the CComModule class.
Could anyone tell me what it is used for?
| This function is for DllCanUnloadNow() to work properly.
You know that when you call CoCreateInstance() for an in-proc server COM automagically calls LoadLibraryEx() to load the COM server DLL if necessary. But how long is the DLL kept loaded? In fact COM calls DllCanUnloadNow() for every loaded COM server DLL periodically. If it returns S_OK COM is allowed to call FreeLibrary().
When is it safe to unload the DLL? Obviously you can't unload it until all the objects implemented by the DLL are destroyed. So here comes "lock count" - an global integer variable counting the number of live objects implemented by the DLL.
When a new COM object is created - CComModule::Lock() is called from its constructor (usually CComObject constructor) and increments the variable, when an object is destroyed - CComModule::Unlock() is called from its destructor and decrements the variable. When CComModule::GetLockCount() returns zero it means that there no live objects and it's safe to unload the DLL.
So the lock count is very similar to the reference count implemented by IUnknown. The reference count is per object, the lock count is per COM in-proc server.
|
2,919,584 | 2,920,576 | Override number of parameters of pure virtual functions | I have implemented the following interface:
template <typename T>
class Variable
{
public:
Variable (T v) : m_value (v) {}
virtual void Callback () = 0;
private:
T m_value;
};
A proper derived class would be defined like this:
class Derived : public Variable<int>
{
public:
Derived (int v) : Variable<int> (v) {}
void Callback () {}
};
However, I would like to derive classes where Callback accepts different parameters (eg: void Callback (int a, int b)).
Is there a way to do it?
| This is a problem I ran in a number of times.
This is impossible, and for good reasons, but there are ways to achieve essentially the same thing. Personally, I now use:
struct Base
{
virtual void execute() = 0;
virtual ~Base {}
};
class Derived: public Base
{
public:
Derived(int a, int b): mA(a), mB(b), mR(0) {}
int getResult() const { return mR; }
virtual void execute() { mR = mA + mB; }
private:
int mA, mB, mR;
};
In action:
int main(int argc, char* argv[])
{
std::unique_ptr<Base> derived(new Derived(1,2));
derived->execute();
return 0;
} // main
|
2,919,629 | 2,920,327 | Mac OS X linker error in Qt; CoreGraphics & CGWindowListCreate | Here is my .mm file
#include "windowmanagerutils.h"
#ifdef Q_OS_MAC
#import </System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/Headers/CGWindow.h>
QRect WindowManagerUtils::getWindowRect(WId windowId)
{
CFArrayRef windows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
return QRect();
}
QRect WindowManagerUtils::getClientRect(WId windowId)
{
return QRect();
}
QString WindowManagerUtils::getWindowText(WId windowId)
{
return QString();
}
WId WindowManagerUtils::rootWindow()
{
QApplication::desktop()->winId();
}
WId WindowManagerUtils::windowFromPoint(const QPoint &p, WId parent, bool(*filterFunction)(WId))
{
return NULL;
}
void WindowManagerUtils::setTopMostCarbon(const QWidget *const window, bool topMost)
{
if (!window)
{
return;
}
// Find a Cocoa equivalent for this Carbon function
// [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
// OSStatus ret = HIViewSetZOrder(this->winId(), kHIViewZOrderAbove, NULL);
}
#endif
The linker is telling me "_CGWindowListCreate" is undefined. What libraries must I link to? Apple's documentation is not very helpful on telling what to include or link to, like MSDN is. Also I couldn't just do #import <CGWindow.h>, I had to specify the absolute path to it... any way around that?
| The CGWindowListCreate function is part of the Quartz Window Services. The corresponding framework is ApplicationServices which is located under /System/Library/Frameworks/.
So, you can just include <ApplicationServices/ApplicationServices.h> at the top of the file and link with the -framework ApplicationServicesoption.
|
2,919,715 | 2,919,910 | Is there such a thing as a C# style extension method in C++? | I'm currently learning C++ and i run into the simple problem of converting an int to a string. I've worked around it using:
string IntToString(int Number)
{
stringstream Stream;
Stream << Number;
return Stream.str();
}
but though it would be more elegant to use something like:
int x = 5;
string y = x.toString();
but how do i add the toString() method to a built in type?
or am i missing something totally fundamental?
| I would not derive any class from basic_string/string. This is not recommended and no method in string is virtual, it does not have a virtual destructor (hence deriving could reault in memory leaks)
Make it pretty for yourself:
You could create a static class (class containing only static methods) in order keep it all in the one place. Use method overloading for int, float, double, etc.
class Converter {
private:
Converter() {}
public:
static string toString(int i) {
... your implementation ...
}
static string toString(float f) {
... same but floats.
}
.... other overloads ....
};
... somewhere else in your code ....
string c = Converter::toString(5);
|
2,919,797 | 3,018,771 | Good simple C/C++ FTP and SFTP client library recommendation for embedded Linux | Could anyone recommend FTP / SFTP client C/C++ library for Linux-based embedded system? I know about Curl library but I need something as simple as possible just to download files from FTP / SFTP servers. Is there any recommendation to look for? Yes, SFTP support is critical. Actually I can even sacrifice multi-threading because I need only one stream at a time. And I'd like it to be able to work through memory buffers but this should be not a problem.
Thank you in advance.
UPDATE:
After spent some time with libcurl I decided not to go this way in favor of direct usage of libssh2 for SFTP and reuse proprietary FTP library from different project. libcurl seems too linked to curl command line tool approach. For example try to get remote file size before starting download operation - it was definitely not planned.
But actually another propositions are welcome especially I see no really simple good public C or C++ FTP client library at all. Everything is either very old and not supported or fresh and wet.
| libssh2 is a great lib for SFTP - and it also happens to be the lib that (lib)curl uses for SFTP.
|
2,919,847 | 2,954,691 | Insert MANY key value pairs fast into berkeley db with hash access | i'm trying to build a hash with berkeley db, which shall contain many tuples (approx 18GB of key value pairs), but in all my tests the performance of the insert operations degrades drastically over time. I've written this script to test the performance:
#include<iostream>
#include<db_cxx.h>
#include<ctime>
#define MILLION 1000000
int main () {
long long a = 0;
long long b = 0;
int passes = 0;
int i = 0;
u_int32_t flags = DB_CREATE;
Db* dbp = new Db(NULL,0);
dbp->set_cachesize( 0, 1024 * 1024 * 1024, 1 );
int ret = dbp->open(
NULL,
"test.db",
NULL,
DB_HASH,
flags,
0);
time_t time1 = time(NULL);
while ( passes < 100 ) {
while( i < MILLION ) {
Dbt key( &a, sizeof(long long) );
Dbt data( &b, sizeof(long long) );
dbp->put( NULL, &key, &data, 0);
a++; b++; i++;
}
DbEnv* dbep = dbp->get_env();
int tmp;
dbep->memp_trickle( 50, &tmp );
i=0;
passes++;
std::cout << "Inserted one million --> pass: " << passes << " took: " << time(NULL) - time1 << "sec" << std::endl;
time1 = time(NULL);
}
}
Perhaps you can tell me why after some time the "put" operation takes increasingly longer and maybe how to fix this.
Thanks for your help,
Andreas
| You may want to look at the information provided by the db_stat utility and the HASH-specific tuning functions that are available. Please see BDB Reference Guide section on configuring a HASH database.
I would expect you to get 10s of thousands of inserts per second on commodity hardware. What are you experiencing and what is your performance target?
Regards,
Dave
|
2,920,164 | 2,920,254 | c++ container allowing you to sort items by when they where last accessed? | Does such a thing exist? or could anyone please recommend how I could implement such a container?
basically I have a std::map which uses a 64bit integer as its key and a custom datatype as the containing item.
I need to be able to periodically remove items that havent been accessed in a while in the most optimal way. does anyone have any suggestions for this?
cheers
| One idea: maintain a std::deque which gets an iterator into your map element pushed to the front whenever accessing the map. You can then easily look at the deque to tell which elements have been used most recently.
Some C++ sketch (void of error checking, the point is to demonstrate that the deque is updated when accessing the map, and you can lateron trim the map).
class MyMap {
typedef std::map<int64_t, void *> Map;
Map m_map;
std::deque<Map::iterator> m_recentlyUsedItems;
public:
void *getItem( int64_t key ) {
Map::iterator it = m_map.find( key );
if ( it == m_map.end() ) {
return 0;
}
m_recentlyUsedItems.push_front( it );
return it->second;
}
void removeAllButMostRecentlyUsedItems( int n ) {
std::deque<Map::iterator> it = m_recentlyUsedItems.begin();
advance( it, n );
std::deque<Map::iterator> it2 = it;
for ( ; it2 != m_recentlyUsedItems.end(); ++it2 ) {
m_map.erase( *it2 );
}
m_recentlyUsedItems.erase( it, m_recentlyUsedItems.end() );
}
};
|
2,920,315 | 2,920,347 | Permutation of array | For example I have this array:
int a[] = new int[]{3,4,6,2,1};
I need list of all permutations such that if one is like this, {3,2,1,4,6}, others must not be the same. I know that if the length of the array is n then there are n! possible combinations. How can this algorithm be written?
Update: thanks, but I need a pseudo code algorithm like:
for(int i=0;i<a.length;i++){
// code here
}
Just algorithm. Yes, API functions are good, but it does not help me too much.
| If you're using C++, you can use std::next_permutation from the <algorithm> header file:
int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
// print a's elements
} while(std::next_permutation(a, a+size));
|
2,920,371 | 2,920,926 | Why my linux signal handler run only once | #include <iostream>
#include <signal.h>
#include <fenv.h>
#include <string.h>
void signal_handler(int sig, siginfo_t *siginfo, void* context)
{
std::cout << " signal_handler " << fetestexcept(FE_ALL_EXCEPT) << std::endl;
throw "exception";
}
void divide() {
float a = 1000., b = 0., c, f = 1e-300;
c = a / b;
std::cout << c << " and f = " << f << std::endl;
}
void init_sig_hanlder() {
feenableexcept(FE_ALL_EXCEPT);
struct sigaction sa, initial_sa;
sa.sa_sigaction = &signal_handler ;
sigemptyset( &sa.sa_mask ) ;
sa.sa_flags = SA_SIGINFO; // man sigaction(3) // allows for void(*)(int,siginfo_t*,void*) handler
sigaction(SIGFPE, &sa, &initial_sa);
}
int main(int argc, char** argv) {
init_sig_hanlder();
while(true)
{
try {
sleep(1);
divide();
}
catch(const char * a) {
std::cout << "Exception in catch: " << a << std::endl;
}
catch(...) {
std::cout << "Exception in ..." << std::endl;
}
}
return 0;
}
Produce the following results on Linux/g++4.2:
signal_handler 0
Exception in catch: exception
inf and f = 0
inf and f = 0
inf and f = 0
inf and f = 0
So, signal handler is executed the first time but the next fp exception does not trigger the handler again. Where am I wrong ?
| I don't think throwing an exception inside a signal handler is good practice. The operating system expects the signal handler to return, because the signal is blocked while the handler for it is called. By throwing an exception you prevent the system from unblocking the signal.
|
2,920,497 | 2,921,709 | Thread-safety of boost RNG | I have a loop which should be nicely parallelized by insering one openmp pragma:
boost::normal_distribution<double> ddist(0, pow(retention, i - 1));
boost::variate_generator<gen &, BOOST_TYPEOF(ddist)> dgen(rng, ddist);
// Diamond
const std::uint_fast32_t dno = 1 << i - 1;
// #pragma omp parallel for
for (std::uint_fast32_t x = 0; x < dno; x++)
for (std::uint_fast32_t y = 0; y < dno; y++)
{
const std::uint_fast32_t diff = size/dno;
const std::uint_fast32_t x1 = x*diff, x2 = (x + 1)*diff;
const std::uint_fast32_t y1 = y*diff, y2 = (y + 1)*diff;
double avg =
(arr[x1][y1] + arr[x1][y2] + arr[x2][y1] + arr[x2][y2])/4;
arr[(x1 + x2)/2][(y1 + y2)/2] = avg + dgen();
}
(unless I make an error each execution does not depend on others at all. Sorry that not all of code is inserted).
However my question is - are boost RNG thread-safe? They seems to refer to gcc code for gcc so even if gcc code is thread-safe it may not be the case for other platforms.
| Browsing through the Boost mailing list archives gives:
Boost.Random does not maintain global
state that would need protection from
multi-threading.
Boost.Random is thread-safe as long as
you don't access any given object from
two threads simultaneously. (Accessing
two different objects is ok, as long
as they don't share an engine). If you
require that kind of safety, it's
trivial to roll that on your own with
an appropriate mutex wrapper.
|
2,920,592 | 2,920,769 | rect in c or c++ language | Is there a type called rect in C or class Rect in C++ language.
| Write
template<class T>
struct podrect
{
T left;
T top;
T right;
T bottom;
};
template<class T>
struct rect
{
rect() : left(), top(), right(), bottom() {}
rect(T left, T top, T right, T bottom) :
left(left), top(top), right(right), bottom(bottom) {}
template<class Point>
rect(Point p, T width, T height) :
left(p.x), right(p.y), right(p.x + width), bottom(p.y + height) {}
T left;
T top;
T right;
T bottom;
};
typedef rect<int> intrect;
typedef rect<float> floatrect;
or something like this. It's very simple.
|
2,920,600 | 2,920,629 | Strange Template error : error C2783: could not deduce template argument | I have created a simple function with 2 diffrernt template arguments t1, t2 and return type t3.
So far no compilation error. But when Itry to call the function from main, I encounter error C2783.
I needed to know If the following code is legally ok? If not how is it fixed?
please help!
template <typename t1, typename t2, typename t3>
t3 adder1 (t1 a , t2 b)
{
return int(a + b);
};
int main()
{
int sum = adder1(1,6.0); // error C2783 could not deduce template argument for t3
return 0;
}
| There is no way for the compiler to deduce t3 from the function arguments. You need to pass this argument explicitly. Change the order of the parameters to make this possible
template <typename t3, typename t1, typename t2>
t3 adder1 (t1 a , t2 b)
{
return t3(a + b); // use t3 instead of fixed "int" here!
};
Then you can call it with adder1<int>(1, 6.0). It's more difficult if you want to deduce t3 to the actual result of the addition. C++0x (next C++ version's codename) will allow to do this by saying that the return type is equal to the type of the addition the following way
template <typename t1, typename t2>
auto adder1 (t1 a , t2 b) -> decltype(a+b)
{
return a + b;
};
Then you could cast explictly at the point of use
int sum = (int) adder1(1,6.0); // cast from double to int
Simulate this in the current C++ version isn't going to be easy. You can use my promote template to do that. If you feel that this rather confuses the matter for you and that you are OK with explictly providing the return type, i think it's better to stay with explicitly providing it. Like Herb Sutter says "Write What You Know, and Know What You Write"
Nontheless you can do the above like this with that template
template <typename t1, typename t2>
typename promote<t1, t2>::type adder1 (t1 a, t2 b)
{
return (a + b);
};
|
2,920,773 | 2,920,799 | What exactly is a variable in C++? | The standard says
A variable is introduced by the declaration of an object. The variable's name denotes the object.
But what does this definition actually mean?
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects? Or is a variable the name itself?
Or is a variable a named object in the sense that every variable is also an object?
Or is a variable just a "proxy" with a name that "delegates" all operations to the real object?
To confuse things further, many C++ books seem to treat variables and objects as synonyms.
What is your take on this?
About entities, quoting from the C++0x draft:
An entity is a value, object, reference, function [...]
Every name that denotes an entity is introduced by a declaration.
A variable is introduced by the declaration of an object
From these statements I draw the conclusion that a variable is a name and thus cannot be an object. This is really confusing the hell out of me :)
| Variables are named objects. The following create objects that are not variables
new int // create one int object
std::string() // create one string object
The following creates one array variable with name "foo" and 5 unnamed (sub-) objects of type "int"
int foo[5];
The following is not a variable in C++03, but has become a variable in C++0x (declared references are variables in C++0x, for details see the link)
extern int &r;
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects?
Variables are objects (or references respectively). The entity list (3/3 in C++03) of C++ contains multiple such is-a relationships. For instance, a sub-object is-a object and an array element is-a object and a class-member is-a object or function or type or template or enumerator.
The entity list of C++0x looks a bit cleaner to me, and it doesn't contain "variables", "instance of a function" (what that kind of entity even is has never been apparent to me), "sub-object" and "array element" anymore. Instead it added "template specialization" which either are functions, classes or templates (partial specializations).
The C++ object model at 1.8 says
An object can have a name (clause 3).
So if you like, you can formulate the statement as "The object's name denotes the object.".
|
2,921,002 | 2,921,077 | How do I create a create and execute an SQL command using OleDB directly? | I want to use the OleDB interfaces directly to open a connection to a DB, create a command and executing it (for example using the ICommandText interface).
The main thing I can't find is how to create the connection and the command object and how to connect the object that implements the ICommandText to the connection.
In ADO I would just use the ActiveConnection property but I want to do this directly on the OleDB interfaces.
Also, if anyone can recommend a tutorial to OleDB, ether online or a book, free or not that would be great (but a tutorial and not just a reference / API)
I'm using C++ but any native code would be fine.
| MSDN has a lot on this. http://msdn.microsoft.com/en-us/library/502e07a7.aspx is a sort of index into it, including several pages of concepts and others of samples. Should get you started.
http://msdn.microsoft.com/en-us/library/8kaf36d4.aspx specifically starts a File, New, Project and gets you connected to the db and selecting some data.
|
2,921,068 | 2,921,150 | Cannot press QPushButton in a simple program | Basically, I want a simple pushButton with a colorful text which when pressed exits the application.
Why cant I press PushButton in this simple program. I am using QT 4.6 on Arch x86_64.
#include <QtGui/QApplication>
#include <QLabel>
#include <QPushButton>
#include<QtGui>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *Main=new QMainWindow;
QPushButton *button = new QPushButton(Main);
QLabel *label = new QLabel(Main);
label->setText("<h2><i>Hello</i> ""<font color=red>Qt!</font></h2>");
label->setVisible(true);
QObject::connect(button, SIGNAL(clicked()),label, SLOT(close()));
label->setAlignment(Qt::AlignCenter|Qt::AlignVCenter);
label->setWindowTitle("HelloWorld Test Program");
Main->show();
return a.exec();
}
| Beside the use of a button class that will allow you to display rich text, you also need to make sure your connections are correct.
In your example, you're connecting the clicked signal of the button to the clear() slot of the label, which is non-sense.
To exit your app when the button is clicked, you need to close the main window. Here is the code to get the right connection :
QObject::connect(button, SIGNAL(clicked()),Main, SLOT(close()));
Changing this single line of code in your example is not enough, because your label is drawn on top of your button, so it's not possible to graphically click on it. You need to hide your label and put some text into your button :
button->setText("Hello");
label->setVisible(false);
Regarding the rich text feature in a QPushButton, AFAIK it is not possible to do it with a QPushButton.
UPDATE :
Here is a way to put some richtext on a QPushButton. It uses the solution described by my comment : painting a QTextDocument onto a pixmap and setting this pixmap as the button's icon.
#include <QtGui/QApplication>
#include <QLabel>
#include <QPushButton>
#include <QtGui>
#include <QTextDocument>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *Main=new QMainWindow;
QPushButton *button = new QPushButton(Main);
QTextDocument Text;
Text.setHtml("<h2><i>Hello</i> ""<font color=red>Qt!</font></h2>");
QPixmap pixmap(Text.size().width(), Text.size().height());
pixmap.fill( Qt::transparent );
QPainter painter( &pixmap );
Text.drawContents(&painter, pixmap.rect());
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
QObject::connect(button, SIGNAL(clicked()),Main, SLOT(close()));
Main->show();
return a.exec();
}
|
2,921,349 | 2,922,104 | priority_queue with dynamic priorities | I have a server application which accepts incomming queries and executes them. If there are too many queries they should be queued and if some of the other queries got executed the queued queries should be executed as well. Since I want to pass queries with different priorities I think using a priority_queue would be the best choice.
e.g. The amout of the axcepting queries (a) hit the limt and new queries will be stored in the queue. All queries have a priority of 1 (lowest) if some of the queries from (a) get executed the programm will pick the query with the highest priority out of the queue and execute it. Still no problem. Now someone is sending a query with a priority of 5 which gets added to the queue. Since this is the query with the highest priority the application will execute this query as soon as the running queries no longer hit the limit. There might be the worst case that 500 queries with a priority of 1 are queued but wont be executed since someone is always sending queries with a priority of 5 hence these 500 queries will be queued for a looooong time. In order to prevent that I want to increase the prioritiy of all queries which have a lower priority than the query with the higher priority, in this example which have a priority lower than 5. So if the query with a priority of 5 gets pulled out of the queue all other queries with a priority < 5 should be increased by 0.2. This way queries with a low priority wont be queued for ever even if there might be 100 queries with a higher priority.
I really hope someone can help me to solve the problem with the priorities:
Since my queries consist of an object I thought something like this might work:
class Query {
public:
Query( std::string p_stQuery ) : stQuery( p_stQuery ) {};
std::string getQuery() const {return stQuery;};
void increasePriority( const float fIncrease ) {fPriority += fIncrease;};
friend bool operator < ( const Query& PriorityFirst, const Query& PriorityNext ) {
if( PriorityFirst.fPriority < PriorityNext.fPriority ) {
if( PriorityFirst.fStartPriority < PriorityNext.fStartPriority ) {
Query qTemp = PriorityFirst;
qTemp.increasePriority( INCREASE_RATE );
}
return true;
} else {
return false;
}
};
private:
static const float INCREASE_RATE = 0.2;
float fPriority; // current priority
float fStartPriority; // initialised priority
std::string stQuery;
};
| How many discrete priority values do you want to implement? If their number is small (say, 256 levels), then instead of a single priority queue it makes more sense to have 256 simple queues (this is how priority process schedulers are implemented in some OSes). Initially your events sent with priority 1 are placed on queue #1. Then someone sends a prio=25 event, and it is placed on queue #25. The reader reads the event from the highest non-empty queue (in this case #25) and the events on all non-empty queues under 25 are moved up a slot (the entire queue #1 is moved to queue #2, etc). I am pretty sure this could all be done in O(k) (where k is the number of priority levels), either with std::move or with std::swap or with list::splice.
Moving queue #1 to the position earlier taken by queue #2 should be O(1) with move or swap, and if the remainder of prio=25 queue is not empty, then moving all elements up from queue #24 into queue #25 is O(1) if the queues are std::list's and list::splice() is used.
|
2,921,775 | 2,921,930 | need a library to get performance counters data under Win CE, c++ code | Under WindowsCE, C++ project, I'd like to get CPU utilization and memory allocation data real time - for logging and troubleshooting. Is there a library or activeX available that i could include in my code and use [without bringing my process to a halt, preferably], anyone knows?
thanks much for any insight!
O.
| If you are running on an arm based system (don't know enough about x86 systems) then you need to calculate cpu load on your own by spawning an idle thread and check how much time it consumes.
You can use the ToolHelpApi (a nice blog post that demonstrates this) to extract more information about processes.
|
2,921,861 | 2,921,884 | Why would MessageBox fail silently? | Does anyone know how MessageBox(...) could fail silently?
MessageBox(g_hMainhWnd, buffer, "Oops!", MB_OK | MB_ICONERROR);
ShellExecute(0, "open", "http://intranet/crash_handler.php", NULL, "", SW_SHOWNORMAL);
For a little context, this code is called inside our own exception handler, which was registered with SetUnhandledExceptionFilter()
Most of the time, I see the message box, and then it launches a web browser.
However, I have an exe, which as far as I'm aware uses this exact code, and it successfully launches the web browser, but I do not see the message box first.
Thanks
Tim
Cracked it. I tried deliberately passing in a garbage HWND and the message box didn't appear.
Thanks Brian!
| Just an idea but maybe g_hMainhWnd is invalid? See if it works when you put NULL for the first parameter.
I would suggest to call GetLastError after the call and write the output to a file. That way you can see what Windows thinks the error is. The MSDN MessageBox documentation mentions that it sets GetLastError for this API and if it fails it returns zero.
|
2,921,864 | 2,921,908 | Are 'const' variables precomputed by default in C++? | Suppose I have variables for positions like
const float latitude = 51.+11./60.+33.0461/3600.;
const float longitude = 12.+50./60.+31.9369/3600.;
and use them frequently in the program. Does the compiler precompute that?
(This example should not produce much overhead, but you get the point.)
Bonus point for pointing out location. ;)
TIA
| I don't believe it is required for the compiler to compute the result of arithmetic constant expressions in general.
The compiler is, however, required to compute the result of an integral constant expression (basically, a constant expression composed only of integers and other values converted to integers) in cases where it needs the result--that is, when an integral constant expression is used as an array size, as a case expression, as an enumerator value, etc.
I'd be surprised, however, if any modern compiler didn't compute the result of a constant expression.
|
2,921,915 | 2,921,949 | Should the name of my classes begin with 'Q' in Qt? | When I first started working with Qt, it was extremely annoying that every class has a name beginning with 'Q', but now I've got used to it.
I'm using Qt Creator, and it highlights code quite well.
However, it only highlights class names beginning with 'Q'. And it highlights everything beginning with 'Q' even if there is no such type.
It doesn't highlight custom class names.
That makes me wonder, should I also begin all my class names with 'Q'?
Or at least the reusable ones?
(I mean, those that I put in a class library, or reuse in another app.)
I've seen several places where they named their classes this way. Is it a good thing?
I found this page about Qt's naming conventions, but it doesn't deal with this question.
Also, I don't understand why Qt doesn't use namespaces.
EDIT:
Big thank you to everyone who shared his thoughts with me.
EDIT 2:
It seems that the newer versions of Qt Creator now also highlight the class names not beginning with 'Q'. Nice!
| Personnally, I wouldn't prefix my own classes. As Qt has its own implementation of lots of thing (string, list...) it helps to know what you're using.
The correct way would be to use namespaces. I think that Qt didn't use them because it's quite old. C++ changed a lot lately.
And generally, adapting your naming conventions according to syntax colouring is a bad idea (even if I understand that it only made you wonder about your nameming).
|
2,922,175 | 2,922,348 | File IO, Handling CRLF | I am writing a program that takes a file and splits it up into multiple small files of a user specified size, then join the multiple small files back again.
the code must work for C and C++
I am compiling with multiple compilers.
I am reading and writing to the files by using the functions fread() and fwrite()
fread() and fwrite() handle bytes, not strings.
The problem I am having pertains to CRLF. If the file I am reading from contains CRLF, then I want to retain it when i split and join the files back together. If the file contains LF, then i want to retain LF.
Unfortunately, fread() seems to store CRLF as \n (I think), and whatever is written by fwrite() is compiler-dependent.
How do I approach this problem?
| #include <stdio.h>
int main() {
FILE * f = fopen( "file.txt", "rb" );
char c;
while( fread( &c, 1, 1, f ) ) {
if ( c == '\r' ) {
printf( "CR\n" );
}
else if ( c == '\n' ) {
printf( "LF\n" );
}
else {
printf( "%c\n" , c );
}
}
fclose( f );
}
|
2,922,328 | 2,922,563 | Accept templated parameter of stl_container_type<string>::iterator | I have a function where I have a container which holds strings (eg vector<string>, set<string>, list<string>) and, given a start iterator and an end iterator, go through the iterator range processing the strings.
Currently the function is declared like this:
template< typename ContainerIter>
void ProcessStrings(ContainerIter begin, ContainerIter end);
Now this will accept any type which conforms to the implicit interface of implementing operator*, prefix operator++ and whatever other calls are in the function body.
What I really want to do is have a definition like the one below which explicitly restricts the amount of input (pseudocode warning):
template< typename Container<string>::iterator>
void ProcessStrings(Container<string>::iterator begin, Container<string>::iterator end);
so that I can use it as such:
vector<string> str_vec;
list<string> str_list;
set<SomeOtherClass> so_set;
ProcessStrings(str_vec.begin(), str_vec.end()); // OK
ProcessStrings(str_list.begin(), str_list.end()); //OK
ProcessStrings(so_set.begin(), so_set.end()); // Error
Essentially, what I am trying to do is restrict the function specification to make it obvious to a user of the function what it accepts and if the code fails to compile they get a message that they are using the wrong parameter types rather than something in the function body that XXX function could not be found for XXX class.
| You can get close to this with a template template parameter:
template<template<class> class CONTAINER>
void ProcessStrings(CONTAINER<string>&);
This will process a whole container, and give a compile error if it doesn't contain strings.
ProcessStrings(str_vec); // OK
ProcessStrings(so_set); // Error
If you want to work with iterator ranges, then the best I could manager is
template<template<class> class CONTAINER>
void ProcessStrings(typename CONTAINER<string>::iterator,
typename CONTAINER<string>::iterator);
Unfortunately, type inference won't work on the function arguments, so you'll have to explicitly give the template parameter:
ProcessStrings<vector>(str_vec.begin(), str_vec.end()); // OK
ProcessStrings<set>(so_set.begin(), so_set.end()); // Error
Can anyone improve on this?
|
2,922,439 | 2,922,454 | How to interpret binary data as an integer? | The codebase at work contains some code that looks roughly like this:
#define DATA_LENGTH 64
u_int32 SmartKey::SerialNumber()
{
unsigned char data[DATA_LENGTH];
// ... initialized data buffer
return *(u_int32*)data;
}
This code works correctly, but GCC gives the following warning:
warning: dereferencing pointer ‘serialNumber’ does break strict-aliasing rules
Can someone explain this warning? Is this code potentially dangerous? How can it be improved?
Update
With thanks to James McNellis' answer I came up with the following utility function:
template<class T, class Data>
T BinaryCast(const Data & inData)
{
T ret;
std::copy(&inData[0], &inData[0] + sizeof(ret), reinterpret_cast<char*>(&ret));
return ret;
}
u_int32 SmartKey::SerialNumber()
{
unsigned char data[DATA_LENGTH];
// ... initialized data buffer
return BinaryCast<u_int32>(data);
}
Feel free to suggest improvements!
| The warning is because you are violating the strict aliasing rule.
One way to do it correctly would be to copy the bytes from the data buffer into a u_int32 object and return that object:
unsigned char data[DATA_LENGTH];
// ... initialized data buffer
u_int32 i;
assert(sizeof (i) <= DATA_LENGTH);
std::copy(&data[0], &data[0] + sizeof (i), reinterpret_cast<char*>(&i));
return i;
This solution works because in C++ it is permitted to access any type of object as an array of char.
(std::copy() is in <algorithm>)
|
2,922,590 | 2,922,676 | Application settings methods? c++ | I am thinking about adding configurable settings to an application, and I think the easiest ways are an external file or win registry (its a win only app).
Which way would be better?
I was wondering, an user with not enough permissions may not be able to create/write the config file. And in the case of the registry, would todays antivirus allow me to add/edit/remove keys? Or they only monitor certain keys?
Also, if someone knows a class/lib to manage config settings (in pure win32) in vc++ please post it.
| As far as I know:
an user with not enough permissions may not be able to create/write the config file
You should be able to make files inside user's "home directory" or "application data" directory, regardless of permissions. Normally those directories should be writeable.
would todays antivirus allow me to add/edit/remove keys?
Haven't ever seen my antivirus interfere with registry manipulation. You probably will be fine as long as you aren't doing anything suspicious in registry.
Which way would be better?
It is matter of taste. I think that text file is better - allows easier migration of settings. Just don't leave junk behind after uninstall.
Also, if someone knows a class/lib to manage config settings in vc++
QSettings in Qt 4. But using entire Qt for just saving settings is definitely an overkill. You could also check configuration languages like JSON, use lua for settings (less overkill than using Qt 4) or get any XML library. Also, working with registry directly or writing configuration files using iostreams or stdio shouldn't be hard. And you can always write your own configuration library - if you feel like it.
|
2,922,942 | 2,922,955 | Is it possible to have a function pointer to a template function in c++? | I want to know if it's possible to create a template function and then create a function pointer that points to that template function. Is this possible?
I'm using VS2008.
The following code gets this compile time error:
"cannot convert from 'overloaded-function' to 'int (__cdecl *)(int &,int &)' None of the functions with this name in scope match the target type"
template<typename T>
T tfunc(const T &x, const T &y){
return (x < y ? x : y);
}
int (*tfunc_ptr)(int &, int &) = &tfunc<int>;
| Your arguments are wrong. tfunc takes is arguments by const references so your function pointer must do the same;
int (*tfunc_ptr)(const int &, const int &) = &tfunc<int>;
|
2,923,018 | 2,923,060 | Stack STL with 2 params | Im implementing a B-tree in C++,I have a stack which saves pairs . my problem is, how i put in this stack because push only accept 1 argument. thanks
| #include <utility>
// ...
stack<pair<string,string> > s;
s.push(make_pair("roses", "red"));
|
2,923,147 | 2,923,164 | Shared objects (.so) static linking and opening other shared object, is the static library code shared between them? | I have one shared object (a.so) which has statically linked (s.so). b.so also has a static link of s.so.
a.so does a dlopen on b.so , will "s.so" code be shared between the two?
The .so are built on gcc 4.1 on RedHat linux.
The s.so is compiled against a.so and b.so with -Bstatic and --no-whole-archive option.
| Static library code (s.a) is never shared between binaries.
|
2,923,272 | 2,923,290 | How to convert vector to array | How do I convert a std::vector<double> to a double array[]?
| There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
|
2,923,287 | 2,923,355 | What is the process of creating an interpreted language? | I want to create a very simple experimental programming language. What are some resources can i check out to get an overview of the process of creating an interpreted language. I will be using c++ to build and compile the interpreter.
| You need to implement both a parser and an interpreter.
There is a great free text book called "Programming Languages: Application and Interpretation" that uses scheme to build increasingly more complex interpreters. It also serves as a great introduction to programming language features.
Check it out here: http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/
If Scheme isn't your cup of tea it may be worth looking into.
|
2,923,303 | 2,923,501 | OpenGL Shader Compile Error | I'm having a bit of a problem with my code for compiling shaders, namely they both register as failed compiles and no log is received.
This is the shader compiling code:
/* Make the shader */
Uint size;
GLchar* file;
loadFileRaw(filePath, file, &size);
const char * pFile = file;
const GLint pSize = size;
newCashe.shader = glCreateShader(shaderType);
glShaderSource(newCashe.shader, 1, &pFile, &pSize);
glCompileShader(newCashe.shader);
GLint shaderCompiled;
glGetShaderiv(newCashe.shader, GL_COMPILE_STATUS, &shaderCompiled);
if(shaderCompiled == GL_FALSE)
{
ReportFiler->makeReport("ShaderCasher.cpp", "loadShader()", "Shader did not compile", "The shader " + filePath + " failed to compile, reporting the error - " + OpenGLServices::getShaderLog(newCashe.shader));
}
And these are the support functions:
bool loadFileRaw(string fileName, char* data, Uint* size)
{
if (fileName != "")
{
FILE *file = fopen(fileName.c_str(), "rt");
if (file != NULL)
{
fseek(file, 0, SEEK_END);
*size = ftell(file);
rewind(file);
if (*size > 0)
{
data = (char*)malloc(sizeof(char) * (*size + 1));
*size = fread(data, sizeof(char), *size, file);
data[*size] = '\0';
}
fclose(file);
}
}
return data;
}
string OpenGLServices::getShaderLog(GLuint obj)
{
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 0)
{
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
string log = infoLog;
free(infoLog);
return log;
}
return "<Blank Log>";
}
and the shaders I'm loading:
void main(void)
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
void main(void)
{
gl_Position = ftransform();
}
In short I get
From: ShaderCasher.cpp, In: loadShader(), Subject: Shader did not compile
Message: The shader Data/Shaders/Standard/standard.vs failed to compile, reporting the error - <Blank Log>
for every shader I compile.
I've tried replacing the file reading with just a hard coded string but I get the same error so there must be something wrong with how I'm compiling them. I have run and compiled example programs with shaders, so I doubt my drivers are the issue, but in any case I'm on a Nvidia 8600m GT.
Can anyone help?
| In loadFileRaw, you pass char *data by value. Then you assign to it:
data = (char*)malloc(sizeof(char) * (*size + 1));
so your call
loadFileRaw(filePath, file, &size);
does not change the value of file! To change file, pass it in by pointer:
loadFileRaw(filePath, &file, &size);
and then change your function to
bool loadFileRaw(string fileName, char** data, Uint* size) { ... }
and in it,
*data = (char*)malloc(sizeof(char) * (*size + 1));
etc. (for the remaining references to data).
That said, since you're using C++, look into using std::vector<char> or std::string for your memory management. To get you started,
{
std::vector<char> data;
data.resize(100); // now it has 100 entries, initialized to zero
silly_C_function_that_takes_a_char_pointer_and_a_size(&data[0], 100); // OK
} // presto, memory freed
Also, you can look into using std::ifstream for reading files, instead of using FILE *.
|
2,923,461 | 8,012,205 | How to Determine the Size of MSADO Command Parameters | I am new to MS ADO and trying to understand how to set the size on command parameters as created by the
command.CreateParameter (Name, Type, Direction, Size, Value)
The documentation says the following:
Size Optional. A Long value that
specifies the maximum length for the
parameter value in characters or
bytes.
...
If you specify a variable-length data
type in the Type argument, you must
either pass a Size argument or set the
Size property of the Parameter object
before appending it to the Parameters
collection; otherwise, an error
occurs.
1.) What should one pass for fixed-size parameters? Is it a "don't care"?
I was a bit confused by the example found here, in which they set size to 3 for an adInteger parameter with Value set to a variant of type VT_I2
pPrmByRoyalty->Type = adInteger;
pPrmByRoyalty->Size = 3;
pPrmByRoyalty->Direction = adParamInput;
pPrmByRoyalty->Value = vtroyal;
VT_I2 implies two bytes. A tagVARIANT struct is 16 bytes. How did they land on three? I see that the enum value for adInteger happens to be three, but I suspect that is just a coincidence.
So it's a bit confusing what to pass for fixed-size parameters. The team I'm working with has always passed sizeof(int) for adInteger, and it seems to work. Is that correct?
Now, for "variable-length" parameters: we are instructed by the documentation to pass "the maximum length .. in characters or bytes".
2.) For adVarChar, is it sufficient to pass the max width as defined in the database?
3.) What about the Wide types (e.g. adVarWChar)? Is it characters or bytes?
4.) How about adVariant, which could contain fixed- or variable-length data?
5.) Do arrays ever come into play here? (we don't pass them as parameters, just curious)
Any references or personal insights are welcome.
| 1) size is optional for fixed length parameters, so you can pass vtMissing (comutil.h). BTW, my size (connecting to SQL Server) for adInteger is 4 and type is VT_I4, VT_I2 is size 2 and adSmallInt.
2) That should work, I guess. Remind to take the max width of the parameter as defined in the database, not any table column you compare it with. The size might be used for allocation, so you must assure that the size is big enough so that any value that might be filled in fits in.
3) Probably characters.
Regarding 4 and 5 I don't know in which scenario one would want to pass an adVariant or array to the database engine.
|
2,923,843 | 2,923,900 | Can I use boost library for crossplatform application executing? | Is there any WinAPI WinExec analog in boost (c++) libraries? I need to run executable from my program, and pass parameters to it. Should I use any other cross-platform libraries for this, or handle myself what OS my program is compiled for?
| You might want to take a look at this question regarding popen() on win32: popen
|
2,923,882 | 2,929,797 | Floor function returning EXC_BAD_ACCESS | The cod that I am using contains these snippets of code. I am calling ThetaG_JD with the argument 2455343.50000 which is just a sample Julian date. Every time I run the program, I receive a EXC_BAD_ACCESS on the indicated line. When using gdb and printing out the intermediary values and passing them through the floor function, I get no error, but when Frac() is used it always returns an error.
double Frac(double arg)
{
/* Returns fractional part of double argument */
return arg - floor(arg);
}
double ThetaG_JD(double jd)
{
/* Reference: The 1992 Astronomical Almanac, page B6. */
double UT=0, TU=0, GMST=0;
//THIS LINE
UT=Frac(jd+0.5);
// THAT ONE ^^
jd=jd-UT;
TU=(jd-2451545.0)/36525;
GMST=24110.54841+TU*(8640184.812866+TU*(0.093104-TU*6.2E-6));
GMST=Modulus(GMST+secday*omega_E*UT,secday);
return (twopi*GMST/secday);
}
| The EXC_BAD_ACCESS is somewhat puzzling to me, but this sounds suspiciously like a floating point exception. It's been a while, but as I recall on x87 hardware, you could generate overflow/underflow/NaN and the processor wouldn't let you know with an exception until the next FP operation which could be in a totally different part of the code. You could try something like jd += 0.5 instead of the call for Frac and see if it still dies.
Also the x87 status register will be able to show you if there's an error state and you should be able to see that within gbd.
|
2,924,037 | 2,924,106 | Separate "include" and "src" folders for application-level code? | This questions concerns mostly Unix/Linux style C++ development. I see that many C++ libraries store their header files in a "include" folder and source files in an "src" folder. For the sake of conformance I adopted this in my own code. But it is not clear to me whether this should be done for application code as well. I've seen a few cases where a flat directory structure is used for that. What would be the recommended approach?
| I also separate them, but not strictly on the extension, but on the access of the file.
Suppose you have a module that manages customer information and uses 2 classes to do this: Customer, CustomerValidityChecker.
Also suppose that other parts in your application only need to know about the Customer class, and that the CustomerValidityChecker is only used by the Customer class to perform some checking.
Based on these assumptions I store the files like this:
Public folder (or include folder):
customer.h
Private folder (or source folder):
customer.cpp
customervaliditychecker.h
customervaliditychecker.cpp
That way, it becomes immediately clear for callers of your module which parts are accessible (public) and which parts aren't.
|
2,924,058 | 2,924,154 | Confused about std::runtime_error vs. std::logic_error | I recently saw that the boost program_options library throws a logic_error if the command-line input was un-parsable. That challenged my assumptions about logic_error vs. runtime_error.
I assumed that logic errors (logic_error and its derived classes) were problems that resulted from internal failures to adhere to program invariants, often in the form of illegal arguments to internal API's. In that sense they are largely equivalent to ASSERT's, but meant to be used in released code (unlike ASSERT's which are not usually compiled into released code.) They are useful in situations where it is infeasible to integrate separate software components in debug/test builds or the consequences of a failure are such that it is important to give runtime feedback about the invalid invariant condition to the user.
Similarly, I thought that runtime_errors resulted exclusively from runtime conditions outside of the control of the programmer: I/O errors, invalid user input, etc.
However, program_options is obviously heavily (primarily?) used as a means of parsing end-user input, so under my mental model it certainly should throw a runtime_error in the case of bad input.
Where am I going wrong? Do you agree with the boost model of exception typing?
| In this case, I think (at least for the most part) you're right and it's wrong. The standard describes logic_error as:
The class logic_error defines the type of objects thrown as exceptions to report errors presumably detectable before the program executes, such as violations of logical preconditions or class invariants.
A command line argument that can't be parsed doesn't seem to fit that very well.
By contrast, it describes runtime_error as:
The class runtime_error defines the type of objects thrown as exceptions to report errors presumably detectable only when the program executes.
That seems to be a better fit.
|
2,924,134 | 2,924,159 | Copy constructor bug | I'm writing a simple nD-vector class, but am encountering a strange bug. I've stripped out the class to the bare minimum that still reproduces the bug:
#include <iostream>
using namespace std;
template<unsigned int size> class nvector
{
public:
nvector() {data_ = new double[size];}
~nvector() {delete[] data_;}
template<unsigned int size2>
nvector(const nvector<size2> &other)
{
data_ = new double[size];
int i=0;
for(; i<size && i < size2; i++)
data_[i] = other[i];
for(; i<size; i++)
data_[i] = 0;
}
double &operator[](int i) {return data_[i];}
const double&operator[](int i) const {return data_[i];}
private:
const nvector<size> &operator=(const nvector<size> &other); //Intentionally unimplemented for now
double *data_;
};
int main()
{
nvector<2> vector2d;
vector2d[0] = 1;
vector2d[1] = 2;
nvector<3> vector3d(vector2d);
for(int i=0; i<3; i++)
cout << vector3d[i] << " ";
cout << endl; //Prints 1 2 0
nvector<3> other3d(vector3d);
for(int i=0; i<3; i++)
cout << other3d[i] << " ";
cout << endl; //Prints 1 2 0
} //Segfault???
On the surface this seems to work fine, and both tests print out the correct values. However, at the end of main the program crashes with a segfault, which I've traced to nvector's destructor.
At first I thought the (incorrect) default assignment operator was somehow being called, which is why I added the (currently) unimplemented explicit assignment operator to rule this possibility out.
So my copy constructor must be buggy, but I'm having one of those days where I'm staring at extremely simple code and just can't see it. Do you guys have any ideas?
| Templated implementation of conversion-constructor is never considered as a candidate function for a copy-constructor. Your templated copy-constructor is never called. Instead, the compiler uses an implicitly generated "default" copy-constructor implementation, which performs shallow copying with obvious consequences.
In other words, the templated constructor you have implemented above will never be used as a copy-constructor, only as a conversion-constructor. You have to implement your copy-constructor explicitly as a non-template function.
|
2,924,238 | 2,924,289 | how to open a file in user's home folder | i'd like to put a kind of lock file in the user's home directory on linux(from c++) but fopen'ing ~/.fluudit doesn't seem to work.
fopen("~/.fluudit","w"); //fails
| You can use the environment variable HOME and if that's not present, you can use the password database:
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
|
2,924,240 | 2,924,274 | C++ - How could I do some operation on bmp file? | I am interesting to do some transformation, like change one color to another, count all used colors, and resize image. I DO NOT want to use any exist library, I would like write myslelf all code.
Summing up: How could I open BMP file and change it?
| I would start with reading some documentation. Maybe go to Wikipedia for an overview.
|
2,924,409 | 2,924,832 | Manually bring up tooltip? (WinAPI) | I've been reading about how tooltips work and it seems like I need to register each tool to the window. My issue is, I have a custom color wheel and I want it to show the tooltip for the RGB, HSV etc of that color which means I won't be registering multiple tools. From the looks of it, the tooltip works with a string resource and needs each tool to be registered, but I would like to manually call the tooltip and have it show mu custom string containing information regarding the color the mouse is under. Thanks
| No, a string resource is not needed, you can also set TOOLINFO.lpszText to a pointer to a regular string. Consider your usage, you probably want to use TTM_TRACKACTIVATE and TTM_TRACKPOSITION.
Beware that this isn't really appropriate use of tool tips. You'll fight the timeout. Once it trips, you can't get the tip back.
|
2,924,419 | 2,924,887 | Wierdness debugging Visual Studio C++ 2008 | I have a legacy C++ app, that in its most incarnation we've been building with makefiles and VS2003's command-line tool. I'm trying to get it to build using VS2008 and MsBuild. The build is working OK, but I'm getting errors where I'd never seen errors, before, and stepping through in VS2008's debugger only confuses me.
The app links a number of static libraries, which fall into two categories: those that are part of the same application suite, and those that are shared between a number of application suites.
Originally, I had a .csproj file for each static library, and two .sln files, one for the application suite (including the suite-specific libraries) and one for the non-suite-specific shared libraries. The shared libraries were included in the link, their projects were not included in the application suite .sln.
The application instantiates an object from a class that is defined in one of the shared libraries. The class has a member object of a class that wraps a linked list. The constructor of the linked list class sets its "head" pointer to null.
When I run the app, and try to add an element to the linked list, I get an error - the head pointer contains the value 0xCCCCCCCC. So I step through with the debugger. And see weirdness.
When the current line in the debugger is in a source file belonging to the static library, the head pointer contains 0x00000000. When I step into the constructor, I can see the pointer being set to that value, and when I'm stepped into any other method of the class, I can see that the head pointer still contains 0x00000000. But when I step out into methods that are defined in the application suite .sln, it contains 0xCCCCCCCC. It's not like it's being overwritten. It changes back and forth depending upon which source file I am currently debugging.
So I included the shared library's project in the application suite .sln, and now I see the head pointer containing 0xCCCCCCCC all the time. It looks like the constructor of the linked list class is not being called.
So now, I'm entirely confused. Anyone have any ideas?
| This is a common mishap when you mix and match code that was built with different versions of the CRT header files. Lots of changes between 2003 and 2008. STL iterator debugging for example. The RTC feature (Run-Time Error Checks) would be another, that's the source of the 0xcccccccc value you see. It means "uninitialized variable". You see this because the memory layout of the struct or class is not the same.
You'll have to rebuild those libraries and make sure they are built with the same compiler settings. Also be sure not to mix debug and release build versions.
|
2,924,673 | 2,924,705 | Template function in define | I have some template function and I want to call it using define in C++:
#define CONFIG(key, type, def) getValue<type>(key, def);
Of course, it won't work. Could I make something like this?
| It works fine:
template<typename T>
T getValue( int, int ) { return T(); }
#define CONFIG(key, type, def) getValue<type>(key, def);
int main()
{
CONFIG(1, int, 2);
return 0;
}
|
2,924,901 | 2,924,976 | How do i use 'auto' in C++ (C++0x)? | What do i have to do to this code to make it compile, it's braking around this line:
auto val = what.getObject();
#include<iostream>
using namespace std;
class CUP{
public:
void whatsHappening(){}
};
class MUG{
public:
void whatsHappening(){}
};
class CupThrower{
public:
CUP cp;
CUP getObject(){ return cp;}
};
class MugThrower{
public:
MUG mg;
MUG getObject(){return mg;}
};
template <typename T> void whatsHappening(T what){
auto val = what.getObject(); //DOES NOT COMPILE
val.whatsHappening();
}
int main(){
CupThrower ct;
MugThrower mt;
whatsHappening(ct);
whatsHappening(mt);
return 0;
}
i am using VS2008 to compile.
| Auto isn't supported in VS2008. Use VS2010 and later versions, or another compiler supporting this feature.
|
2,925,106 | 2,925,199 | How does c++ (c++0x) handle implicitly typed variables? | I am trying to learn how to use implicitly typed variables in c++.
Should i be using 'auto' from C++0x? If so how?
Can some one provide me with a simple example or a good tutorial on this?
Thank you.
| auto x = f();
The type of x will be whatever f() returns.
|
2,925,129 | 2,925,252 | Initialized Variables lose Values after Function Call | Question says it all, really. I'm not sure what the problem is. I'm fairly new to classes; my practical experience with them being close to nill, but I have read a fair amount about them.
I have created a class ECard with the following constructor
ECard::ECard( int bankNum, int PIN )
{
m_BankNum = new int;
m_PIN = new int;
m_Barred = new bool;
m_Amount = new double;
*m_BankNum = bankNum;
*m_PIN = PIN;
*m_Barred = false;
*m_Amount = 100.0;
}
and I initialize with EC card( 12345, 54321 )
I also have a member function display(), which simply prints out all the member variables BankNum, PIN, Barred, and Amount.
When I call this function card.display() in my main function, the output is perfectly what I expected.
However, when it enters my loop:
/* Fine values! */
card.display();
while( true )
{
/* Introductory screen giving user options to choose from */
mainScreen( card );
/* Make a choice... */
choice = readInput();
/* Garbage! */
card.display();
/* Pass it to the switch, watch out for invalid input! doChoice is a bool */
if( !doChoice( choice, card ) )
{
cout << "Bad input- repeat!" << endl;
}
/* TODO: Option to terminate loop. */
}
and I try to print the variables in my doChoice() function, I get garbage. All my variables have messed up settings. My Banknumber is something, PIN is a really large negative number( not the MIN ), Barred is suddenly set to true, and there is 0 money in my account even though Barred and Amount were never explicitely set by me anywhere outside the constructor.
/* Outsourced switch that handles the user input from MAIN */
bool doChoice( int choice, ECard card )
{
int inputPIN;
int inputAmount;
/* Garbage! */
card.display();
switch( choice )
{
case 1:
/* Case 1: Charge card with money. Needs PIN and amount */
cout << "PIN Eingeben: ";
inputPIN = readInput();
cout << "\nBetrag Eingeben: ";
inputAmount = readInput();
karte.aufladen( inputAmount, inputPIN );
return true;
I'm sorry if some of the member functions and the outputs are still in German. It shouldn't be important anyway( I like to write all my homework in English anyway since I'll probably be programming for international companies, but my teacher is really picky and lowers my grade if I program outside of his expectations )
The variables are already messed up before it even enters the switch, so that part should just be rhetoric. I can see a problem only with the passing of the card object, though I don't know why that would be a problem. I don't know how to fix it, do I just send each member instead? Create a pointer to the object and send that? I mean, I passed the card object around before and the other function didn't give me garbage. Only this one.
On a final note, if there suddenly is an error in syntax, then that is because I quickly translated all my functions and members into English, and I may have missed a capitalization somewhere or whatnot. Please disregard those, the syntax is correct and the program runs, it just displays garbage values.
| Don't dynamically allocate variables unless necessary
In the Java language, instances of variables are defined using the new operator. This is not necessary in C++.
Change your class declaration to:
struct ECard
{
ECard(unsigned int bankNum,
unsigned int newPIN)
: m_bankNum(bankNum),
m_pin(newPIN),
m_barred(false),
m_amount(100.0)
{
;
}
unsigned int m_bankNum; // Can bank numbers be negative???
unsigned int m_pin;
bool m_barred;
double m_amount;
};
Pointers
If you really need to dynamically allocate memory for the members, use smart pointers. Smart pointers will automagically deallocate memory memory when needed. I suggest using the Boost library ones.
If you can't use smart pointers, remember to deallocate the memory in the destructor:
ECard::
~ECard()
{
delete m_p_bankNum;
delete m_p_pin;
delete m_p_barred;
delete m_p_amount;
}
If you don't use pointers in your class or structure, you avoid the hassles of dynamic memory allocation and deallocation, especially for copying and destroying (who owns the memory?).
|
2,925,132 | 2,925,197 | Why is execution-time method resolution faster than compile-time resolution? | At school, we about virtual functions in C++, and how they are resolved (or found, or matched, I don't know what the terminology is -- we're not studying in English) at execution time instead of compile time. The teacher also told us that compile-time resolution is much faster than execution-time (and it would make sense for it to be so). However, a quick experiment would suggest otherwise. I've built this small program:
#include <iostream>
#include <limits.h>
using namespace std;
class A {
public:
void f() {
// do nothing
}
};
class B: public A {
public:
void f() {
// do nothing
}
};
int main() {
unsigned int i;
A *a = new B;
for (i=0; i < UINT_MAX; i++) a->f();
return 0;
}
I compiled the program above and named it normal. Then, I modified A to look like this:
class A {
public:
virtual void f() {
// do nothing
}
};
Compiled and named it virtual. Here are my results:
[felix@the-machine C]$ time ./normal
real 0m25.834s
user 0m25.742s
sys 0m0.000s
[felix@the-machine C]$ time ./virtual
real 0m24.630s
user 0m24.472s
sys 0m0.003s
[felix@the-machine C]$ time ./normal
real 0m25.860s
user 0m25.735s
sys 0m0.007s
[felix@the-machine C]$ time ./virtual
real 0m24.514s
user 0m24.475s
sys 0m0.000s
[felix@the-machine C]$ time ./normal
real 0m26.022s
user 0m25.795s
sys 0m0.013s
[felix@the-machine C]$ time ./virtual
real 0m24.503s
user 0m24.468s
sys 0m0.000s
There seems to be a steady ~1 second difference in favor of the virtual version. Why is this?
Relevant or not: dual-core pentium @ 2.80Ghz, no extra applications running between two tests. Archlinux with gcc 4.5.0. Compiling normally, like:
$ g++ test.cpp -o normal
Also, -Wall doesn't spit out any warnings, either.
Edit: I have separated my program into A.cpp, B.cpp and main.cpp. Also, I made the f() (both A::f() and B::f()) function actually do something (x = 0 - x where x is a public int member of A, initialized with 1 in A::A()). Compiled this into six versions, here are my final results:
[felix@the-machine poo]$ time ./normal-unoptimized
real 0m31.172s
user 0m30.621s
sys 0m0.033s
[felix@the-machine poo]$ time ./normal-O2
real 0m2.417s
user 0m2.363s
sys 0m0.007s
[felix@the-machine poo]$ time ./normal-O3
real 0m2.495s
user 0m2.447s
sys 0m0.000s
[felix@the-machine poo]$ time ./virtual-unoptimized
real 0m32.386s
user 0m32.111s
sys 0m0.010s
[felix@the-machine poo]$ time ./virtual-O2
real 0m26.875s
user 0m26.668s
sys 0m0.003s
[felix@the-machine poo]$ time ./virtual-O3
real 0m26.905s
user 0m26.645s
sys 0m0.017s
Unoptimized is still 1 second faster when virtual, which I find a bit peculiar. But this was a nice experiment and would like to thank all of you for your answers!
| Profiling unoptimised code is pretty much meaningless. Use -O2 to produce a meaningful result. Using -O3 may result in even faster code, but it may not generate a realistic outcome unless you compile A::f and B::f separately to main (i.e., in separate compilation units).
Based on the feedback, perhaps even -O2 is too aggressive. The 2 ms result is because the compiler optimised the loop away entirely. Direct calls aren't that fast; in fact, it ought to be very difficult to observe any appreciable difference. Move the implementations of f into a separate compilation unit to get real numbers. Define the classes in a .h, but define A::f and B::f in their own .cc file.
|
2,925,167 | 2,933,707 | Qt: How can I access the actual widgets on a page in WebKit? | Is there a way to access the widgets generated by INPUT and SELECT on a page in WebKit, using Qt?
On a related note, does WebKit provide these widgets, or does it delegate back to Qt to generate them?
| Everything inside in QWebView does not use the conventional Qt widget system. It's only HTML, rendered by WebKit. But you can access to html by using the evalJS function. Example of code:
QString Widget::evalJS(const QString &js)
{
QWebFrame *frame = ui->webView->page()->mainFrame();
return frame->evaluateJavaScript(js).toString();
}
evalJS(QString("document.forms[\"f\"].text.value = \"%1\";").arg(fromText));
evalJS(QString("document.forms[\"f\"].langSelect.value = \"%1\";").arg(langText));
evalJS(QString("translate()"));
QString from = evalJS("document.forms[\"f\"].text.value");
QString translation = evalJS("document.forms[\"f\"].translation.value");
ui->textEditTo->setText(translation);
|
2,925,268 | 2,925,294 | TinyXML and fetching values | I'm trying to load data from xml-file with TinyXML (c++).
int height = rootElem->attrib<int>("height", 480);
rootElem is a root element of loaded xml-file. I want to load height value from it (integer). But I have a wrapper function for this stuff:
template<typename T>
T getValue(const string &key, const string &defaultValue = "")
{
return mRootElement->attrib<T>(key, defaultValue);
}
It works with string:
std::string temp = getValue<std::string>("width");
And it fails during fetching:
int temp = getValue<int>("width");
>no matching function for call to ‘TiXmlElement::attrib(const std::string&, const std::string&)’
UPD: The new version of code:
template<typename T>
T getValue(const string &key, const T &defaultValue = T())
{
return mRootElement->attrib<T>(key, defaultValue);
}
| The reason is you are calling the int version of TiXmlElement::attrib, but you are giving it a defualtValue of type const std::string &, however, the function expects a defaultValue of type int.
|
2,925,279 | 3,066,267 | IWebBrowser2: how to force links to open in new window? | The MSDN documentation on WebBrowser Customization explains how to prevent new windows from being opened and how to cancel navigation. In my case, my application is hosting an IWebBrowser2 but I don't want the user to navigate to new pages within my app. Instead, I'd like to open all links in a new IE window. The desired behavior is: user clicks a link, and a new window opens with that URL.
A similar question was asked and answered here and rather than pollute that answered post, it was suggested I open a new discussion.
The members on the related post suggested I should be able to do this by trapping DISPID_BEFORENAVIGATE2, setting the cancel flag, and writing code to open a new window, but I've found out that the browser control gets lots of BeforeNavigate2 events that seem to be initiated by scripts on the main page. For example, amazon.com fires BeforeNavigate2 events like crazy, and they are not a result of link invocation.
Replies appreciated!
| What I ended up doing was using IHTMLDocument directly rather than IWebBrowser. IWebBrowser is a superset of IHTMLDocument, and the navigation model implemented by IWebBrowser isn't customizable to the degree I wanted.
I actually got MS Developer Support involved and this approach was their recommendation. They say this is what Outlook uses for HTML-based email, which is the user experience I wanted to emulate. They also confirmed that there's no reliable way to filter the OnBeforeNavigate events that result from user action from those that result from script activity.
Hope this helps anybody facing the same issues. It wasn't too hard to port the code to use IHTMLDocument. If you end up doing this, you may also find yourself looking for a way to figure out when the document is done loading. To do that, hook HTMLDocumentEvents instead of DWebBrowserEvents, and look for the DISPID_HTMLDOCUMENTEVENTS_ONREADYSTATECHANGE event. It doesn't tell you what the ready state is; you need to call IHTMLDocument::get_readyState and parse the resulting string. Goofy, but there you go.
|
2,925,352 | 2,925,373 | C++ STL: Trouble with iterators | I'm having a beginner problem:
bool _isPalindrome(const string& str)
{
return _isPalindrome(str.begin(), str.end()); // won't compile
}
bool _isPalindrome(string::iterator begin, string::iterator end)
{
return begin == end || *begin == *end && _isPalindrome(++begin, --end);
}
What am I doing wrong here? Why doesn't str.begin() get type checked to be a string::iterator?
Update: Better version:
bool BrittlePalindrome::_isPalindrome(string::const_iterator begin, string::const_iterator end)
{
return begin >= end || *begin == *(end - 1) && _isPalindrome(++begin, --end);
}
| Assuming that you have a declaration of the second function before the first function, the main issue is that you are passing the strings by const reference.
This means that the only overloads of begin() and end() that you have access to are the const versions which return std::string::const_iterator and not std::string::iterator.
The convention for iterators is that the end iterator points one beyond the end of a range and is not dereferencable - certainly if you pass str.end() as the end parameter. This means that *begin == *end is not valid, you need to decrement end once first. You are also going to have an issue with ranges with odd numbers of elements. By doing ++begin and --end with no further checking your iterators may cross over in the recursion rather than triggering the begin == end condition.
Also note that for maximum portability, global identifiers shouldn't start with an underscore.
|
2,925,601 | 2,925,621 | Can I use #undef this way? | I want to get some settings I store in the registry, and if they differ from a #define I want to redefine it, could I do it this way?:
#define DEFINED_X "testSetting"
void LoadConfig()
{
regConfigX = some value previusly stored in the registry;
if(regConfigX!=DEFINED_X)
{
#undef DEFINED_X
#define DEFINED_X regConfigX
}
}
I tought #define was used only when compiling, would this code work when running the compiled exe?
| No, use a static variable to store the value of DEFINED_X.
|
2,925,614 | 2,925,697 | C++ STL: Trouble with string iterators | I'm making a simple command line Hangman game.
void Hangman::printStatus()
{
cout << "Lives remaining: " << livesRemaining << endl;
cout << getFormattedAnswer() << endl;
}
string Hangman::getFormattedAnswer()
{
return getFormattedAnswerFrom(correctAnswer.begin(), correctAnswer.end());
}
string Hangman::getFormattedAnswerFrom(string::const_iterator begin, string::const_iterator end)
{
return begin == end? "" : displayChar(*begin) + getFormattedAnswerFrom(++begin, end);
}
char Hangman::displayChar(const char c)
{
return c;
}
(Eventually, I'll change this so displayChar() displays a - or a character if the user has guessed it, but for simplicity now I'm just returning everything.)
When I build and run this from VS 2010, I get a popup box:
Debug Assertion Failed!
xstring Line: 78
Expression: string iterator not
dereferenceable
What am I doing wrong?
| The problem is in the evaluation of:
displayChar(*begin) + getFormattedAnswerFrom(++begin, end)
In executing this statement, it is evident that your compiler is first incrementing begin, returning the "next" begin for use as the first argument to getFormattedAnswerFrom, and then dereferencing begin for the argument to displayChar.
When begin is one behind end, then begin != end so displayChar(*begin) + getFormattedAnswerFrom(++begin, end) will run. Your compiler increments begin, so now begin == end, and the dereference of begin is invalid.
See also: Order of evaluation in C++ function parameters
|
2,925,726 | 4,163,102 | Win32 DLL importing issues (DllMain) | I have a native DLL that is a plug-in to a different application (one that I have essentially zero control of). Everything works just great until I link with an additional .lib file (links my DLL to another DLL named ABQSMABasCoreUtils.dll). This file contains some additional API from the parent application that I would like to utilize. I haven't even written any code to use any of the functions exported but just linking in this new DLL is causing problems. Specifically, I get the following error when I attempt to run the program:
The application failed to initialize properly (0xc0000025). Click on OK to terminate the application.
I believe I have read somewhere that this is typically due to a DllMain function returning FALSE. Also, the following message is written to the standard output:
ERROR: Memory allocation attempted before component initialization
I am almost 100% sure this error message is coming from the application and is not some type of Windows error.
Looking into this a little more (aka flailing around and flipping every switch I know of) I linked with /MAP turned on and found this in the resulting .map file:
0001:000af220 ??3@YAXPEAX@Z 00000001800b0220 f ABQSMABasCoreUtils_import:ABQSMABasCoreUtils.dll
0001:000af226 ??2@YAPEAX_K@Z 00000001800b0226 f ABQSMABasCoreUtils_import:ABQSMABasCoreUtils.dll
0001:000af22c ??_U@YAPEAX_K@Z 00000001800b022c f ABQSMABasCoreUtils_import:ABQSMABasCoreUtils.dll
0001:000af232 ??_V@YAXPEAX@Z 00000001800b0232 f ABQSMABasCoreUtils_import:ABQSMABasCoreUtils.dll
If I undecorate those names using "undname" they give the following (same order):
void __cdecl operator delete(void * __ptr64)
void * __ptr64 __cdecl operator new(unsigned __int64)
void * __ptr64 __cdecl operator new[](unsigned __int64)
void __cdecl operator delete[](void * __ptr64)
I am not sure I understand how anything from ABQSMABasCoreUtils.dll can exist within this .map file or why my DLL is even attempting to load ABQSMABasCoreUtils.dll if I don't have any code that references this DLL. Can anyone help me put this information together and find out why this isn't working? For what it's worth I have confirmed via "dumpbin" that the parent application imports ABQSMABasCoreUtils.dll, so it is being loaded no matter what. I have also tried delay loading this DLL in my DLL but that did not change the results.
EDIT
I have double checked and all files involved are 64 bit.
| I just had exactly the same problem. This is an issue with the Abaqus API rather than with the loading of DLLS.
I think it is because the Abaqus API overrides the new and delete functions (as you seem to have noticed). If you call new or delete in your program before initializing the Abaqus API, such as by calling odb_initializeAPI(); then you get the
ERROR: Memory allocation attempted before component initialization
error message and the program crashes.
In my program, calling odb_initializeAPI(); before the first new resolved the problem.
|
2,925,881 | 2,925,962 | how a thread can signal when it's finished? | #include <iostream>
#include <boost/thread.hpp>
using std::endl; using std::cout;
using namespace boost;
mutex running_mutex;
struct dostuff
{
volatile bool running;
dostuff() : running(true) {}
void operator()(int x)
{
cout << "dostuff beginning " << x << endl;
this_thread::sleep(posix_time::seconds(2));
cout << "dostuff is done doing stuff" << endl;
mutex::scoped_lock running_lock(running_mutex);
running = false;
}
};
bool is_running(dostuff& doer)
{
mutex::scoped_lock running_lock(running_mutex);
return doer.running;
}
int main()
{
cout << "Begin.." << endl;
dostuff doer;
thread t(doer, 4);
if (is_running(doer)) cout << "Cool, it's running.\n";
this_thread::sleep(posix_time::seconds(3));
if (!is_running(doer)) cout << "Cool, it's done now.\n";
else cout << "still running? why\n"; // This happens! :(
return 0;
}
Why is the output of the above program:
Begin..
Cool, it's running.
dostuff beginning 4
dostuff is done doing stuff
still running? why
How can dostuff correctly flag when it is done? I do not want to sit around waiting for it, I just want to be notified when it's done.
| The problem in this example is that there are two instances of dostuff, so the version being set to false in operator() is different then the one in main.
From the thread management documentation:
A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor. The object is then copied into internal storage, and invoked on the newly-created thread of execution. If the object must not (or cannot) be copied, then boost::ref can be used to pass in a reference to the function object. In this case, the user of Boost.Thread must ensure that the referred-to object outlives the newly-created thread of execution.
If you don't want to copy the object, use boost::ref:
thread t(boost::ref(doer), 4);
|
2,926,034 | 2,926,112 | Include pdbs in installer? | Is there any reason to not include pdb files in an installer? I have C++ logging functionality that walks the stack, and reports line numbers and file names. It would be great if my customers could send me logs with this information. However, they would need the pdb files. Is there any downside (other than installer package size) to deploying them?
| Two possible downsides:
The PDB file might make it easier for someone to reverse-engineer your application.
As a result of the previous, someone might come to expect to be able to call undocumented functions in your DLLs.
If those don't bother you, I can't see any downside. Note though that you don't really need this. As John Seigel says, you should be able to reconstruct the stack trace from a crash dump.
|
2,926,037 | 2,926,052 | Creating a "mountable" File System, where to start? | A friend and I are thinking about creating a simple file system for learning purposes. We're going to write it in C/C++, and try to get it to a mountable state from within linux. We've both been coding or over 16 years (32 combined), so I suppose its just a matter of finding some documentation, and a ton of learning.
My question is, where could I find out more information? (Documentation for creating a file system, requirements of mounting a file system in linux, etc)
Where do we start?
Edit: I should also mention, this would not be a boot-able file system, just a file system used for storage, though I am not too sure if that matters or not.
| I don't have much experience with this, but FUSE ("Filesystem in Userspace") seems to be the way to go - see http://fuse.sourceforge.net, http://en.wikipedia.org/wiki/Filesystem_in_Userspace
|
2,926,066 | 2,926,085 | In C or C++, is there a way to extend a class without inheritance? | Is there a way to implement functionality like Class Categories (of Objective-C) or Extension Methods (of C# 3.0) in C and/or C++?
| With regard to C#'s extension methods: Not directly. C++ has less need for these things because C++ supports free functions. I've never used Objective-C so I can't comment there.
|
2,926,138 | 2,926,163 | Enums, Constructor overloads with similar conversions | Why does VisualC++ (2008) get confused 'C2666: 2 overloads have similar conversions' when I specify an enum as the second parameter, but not when I define a bool type?
Shouldn't type matching already rule out the second constructor because it is of a 'basic_string' type?
#include <string>
using namespace std;
enum EMyEnum { mbOne, mbTwo };
class test {
public:
#if 1 // 0 = COMPILE_OK, 1 = COMPILE_FAIL
test(basic_string<char> myString, EMyEnum myBool2) { }
test(bool myBool, bool myBool2) { }
#else
test(basic_string<char> myString, bool myBool2) { }
test(bool myBool, bool myBool2) { }
#endif
};
void testme() {
test("test", mbOne);
}
I can work around this by specifying a reference 'ie. basic_string &myString' but not if it is 'const basic_string &myString'.
Also calling explicitly via "test((basic_string)"test", mbOne);" also works.
I suspect this has something to do with every expression/type being resolved to a bool via an inherent '!=0'.
Curious for comments all the same :)
| The reason for the ambiguity is that one candidate function is better than another candidate function only if none of its parameters are a worse match than the parameters of the other.
The problem is that the string literal, which has a type of const char[5] is convertible to both std::string (via a converting constructor) and to a bool (since an array can decay to a pointer, and any pointer is implicitly convertible to bool). The conversion to bool is preferred because it is a standard conversion and standard conversions are preferred to user-defined conversions.
So, consider the "broken" overloads:
test(basic_string<char> myString, EMyEnum myBool2) { } // (1)
test(bool myBool, bool myBool2) { } // (2)
The first argument is a const char[5] and prefers (2) (per the description above). The second argument is an EMyEnum and prefers (1), which is an exact match; a conversion would be required to match (2) (an enumeration can be implicitly converted to a bool).
Now consider the second case:
test(basic_string<char> myString, bool myBool2) { } // (3)
test(bool myBool, bool myBool2) { } // (4)
The first argument still prefers (4), but now the second argument can match both (3) and (4) equally. So, the compiler can select (4) and there is no ambiguity.
There would be no ambiguity if you eliminated the required conversion for the first argument, e.g.,
test(basic_string<char>("test"), mbOne);
because both arguments would match (1) exactly.
|
2,926,319 | 2,926,345 | When does a const return type interfere with template instantiation? | From Herb Sutter's GotW #6
Return-by-value should normally be const for non-builtin return types. ...
Note: Lakos (pg. 618) argues against returning const value,
and notes that it is redundant for builtins anyway
(for example, returning "const int"), which he notes may
interfere with template instantiation.
While Sutter seems to disagree on whether to return a const value or non-const value when returning an object of a non-built type by value with Lakos, he generally agrees that returning a const value of a built-in type (e.g const int) is not a good idea.
While I understand why that is useless because the return value cannot be modified as it is an rvalue, I cannot find an example of how that might interfere with template instantiation.
Please give me an example of how having a const qualifier for a return type might interfere with template instantiation.
| Here's a simple example involving function pointers:
const int f_const(int) { return 42; }
int f(int) { return 42; }
template <typename T>
void g(T(*)(T))
{
return;
}
int main()
{
g(&f_const); // doesn't work: function has type "const int (*)(int)"
g(&f); // works: function has type "int (*)(int)"
}
Note that Visual C++ 2010 incorrectly accepts both. Comeau 4.3.10 and g++ 4.1.2 correctly do not accept the g(&f_const) call.
|
2,926,413 | 2,926,423 | Win32 select/poll/eof/ANYTHING? | Using the standard Win32 file I/O API's (CreateFile/ReadFile/etc), I'm trying to wait for a file to become readable, or for an exception to occur on the file. If Windows had any decent POSIX support, I could just do:
select(file_count, files_waiting_for_read, NULL, files_waiting_for_excpt, NULL, NULL);
And select will return when there's anything interesting on some of the files. Windows doesn't support select or poll. Fine. I figured I could take the file and do something like:
while(eof(file_descriptor))
{
Sleep(100);
}
The above loop would exit when more data is available to be read. But nope, Windows doesn't have an equivalent of eof() either! I could possibly call ReadFile() on the file, and determine if it's at the eof that way. But, then I'd have to handle the reading at that point in time -- I'm hoping to simply be able to figure out that a file is readable, without actually reading it.
What are my options?
| Windows has a completely different architecture for asynchronous I/O. You will need to use overlapped I/O with or without the related I/O completion ports.
Note that the standard Winsock interface does have a POSIX-like select() function, but that only works with network sockets.
|
2,926,454 | 3,457,224 | Embeddable unit testing framework for mixed Windows app | I want to test portions of a very complex app which includes both a major native Windows component and a substantial WPF GUI. Due to complexities I can't detail, it is impossible to run the native portion independently nor can I isolate the areas I want to test (spare me the lectures, we're talking a huge legacy code base and we do have refactoring plans).
I'm looking for a unit test kit I can invoke on the native side but must be able to run with the app launched with the managed portion initialised. That seems to rule out the run executable feature of the cfix Windows unit test kit. I really like their philosophy, like WinUnit, of using DLL compilation as a way to add the reflective capabilities missing in C++ and gain a more NUnit-like experience.
Ideally, I want something like WinUnit running within the application code and generating an HTML report.
I'm trying to introduce more TDD and having things as lean as possible is important.
| The answer is C++/CLI.
You can use managed code test frameworks such as mbUnit, NUnit and xUnit.Net with C++/CLI code and they work fine. The contents of the tests then call native functions from the native libraries.
There are two minor gotchas:
There's a bug in xUnit.Net that prevents their InlineData attribute being repeated in C++/CLI, as discussed in this question.
You sometimes have to be careful about the working directory of the test runner or to explicitly copy native DLLs as the shadow copy approach some use will only get managed dependencies.
|
2,926,640 | 2,931,360 | Why is T() = T() allowed? | I believe the expression T() creates an rvalue (by the Standard). However, the following code compiles (at least on gcc4.0):
class T {};
int main()
{
T() = T();
}
I know technically this is possible because member functions can be invoked on temporaries and the above is just invoking the operator= on the rvalue temporary created from the first T().
But conceptually this is like assigning a new value to an rvalue. Is there a good reason why this is allowed?
Edit: The reason I find this odd is it's strictly forbidden on built-in types yet allowed on user-defined types. For example, int(2) = int(3) won't compile because that is an "invalid lvalue in assignment".
So I guess the real question is, was this somewhat inconsistent behavior built into the language for a reason? Or is it there for some historical reason? (E.g it would be conceptually more sound to allow only const member functions to be invoked on rvalue expressions, but that cannot be done because that might break some existing code.)
| This is why several classes in the Standard library can be implemented. Consider for example std::bitset<>::operator[]
// bit reference:
class reference {
friend class bitset;
reference();
public:
˜reference();
reference& operator=(bool x); // for b[i] = x;
reference& operator=(const reference&); // for b[i] = b[j];
bool operator˜() const; // flips the bit
operator bool() const; // for x = b[i];
reference& flip(); // for b[i].flip();
};
reference operator[](size_t pos); // for b[i];
If you do bits[i] = true you exactly assign some value to an rvalue of class type. The proxy that's returned by operator[] can access the bits which are space efficiently packed into integers.
|
2,926,878 | 2,926,917 | Determine if a string contains only alphanumeric characters (or a space) | I am writing a function that determines whether a string contains only alphanumeric characters and spaces. I am effectively testing whether it matches the regular expression ^[[:alnum:] ]+$ but without using regular expressions. This is what I have so far:
#include <algorithm>
static inline bool is_not_alnum_space(char c)
{
return !(isalpha(c) || isdigit(c) || (c == ' '));
}
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(), is_not_alnum_space) == str.end();
}
Is there a better solution, or a “more C++” way to do this?
| Looks good to me, but you can use isalnum(c) instead of isalpha and isdigit.
|
2,927,036 | 2,927,155 | Does operator precedence in C++ differ for pointers and iterators? | The code below demonstrates this difference:
#include <iostream>
#include <string>
int main()
{
char s[] = "ABCD";
std::string str(s);
char *p = s;
while(*p) {
*p++ = tolower(*p); // <-- incr after assignment
}
std::cout << s << std::endl;
std::string::iterator it = str.begin(), end = str.end();
while(it != end) {
*it++ = tolower(*it); // <-- incr before assignment ?
}
std::cout << str << std::endl;
return 0;
}
it produces output:
abcd
bcd
if we separate assignment operation and increment operator:
while(it != end) {
*it = tolower(*it); // <-- incr before assignment ?
it++;
}
the output will be as expected.
What's wrong with the original code?
$ g++ --version
g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
Copyright (C) 2004 Free Software Foundation, Inc.
| The problem is that the order of evaluation of arguments of operator= is unspecified. This is according to C++ Standard 5.2.2/8. Consider the following:
*it++ = tolower(*it);
is equal to
operator=( *it++, tolower(*it) );
Now *it++ could be computed before tolower(*it) and vice versa.
|
2,927,109 | 2,927,182 | Strange overloading rules in C++ | I'm trying to compile this code with GCC 4.5.0:
#include <algorithm>
#include <vector>
template <typename T> void sort(T, T) {}
int main()
{
std::vector<int> v;
sort(v.begin(), v.end());
}
But it doesn't seem to work:
$ g++ -c nm.cpp
nm.cpp: In function ‘int main()’:
nm.cpp:9:28: error: call of overloaded ‘sort(std::vector<int>::iterator, std::vector<int>::iterator)’ is ambiguous
nm.cpp:4:28: note: candidates are: void sort(T, T) [with T = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]
/usr/lib/gcc/i686-pc-linux-gnu/4.5.0/../../../../include/c++/4.5.0/bits/stl_algo.h:5199:69: note: void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]
Comeau compiles this code without errors.
(4.3.10.1 Beta2, strict C++03, no C++0x)
Is this valid C++?
Why is GCC even considering std::sort as a valid overload?
I did some experiments, and I think I know why Comeau might compile this (but I don't know this for a fact):
namespace foo {
typedef int* iterator_a;
class iterator_b {};
template <typename T> void bar(T) {}
}
template <typename T> void bar(T) {}
int main()
{
bar(foo::iterator_a()); // this compiles
bar(foo::iterator_b()); // this doesn't
}
My guess is that the first call resolves to bar(int*) so there's no ADL and no ambiguity, while the second call resolves to bar(foo::iterator_b) and pulls in foo::bar (but I'm not really sure).
So GCC probably uses something like iterator_b while Comeau uses iterator_a.
| You can explicitly specify your sort function by fully qualifying the name as ::sort.
The ambiguous overload is due to argument dependent lookup. The C++ standard doesn't specify how std::vector<*>::iterator should be implemented. The gcc library writers have chosen to use a template (__gnu_cxx::__normal_iterator) with a template type argument of std::vector, which brings namespace std into the list of associated namespaces.
Is this valid C++?
Yes, but the behaviour of both compilers is also compliant with the C++ standard. ADL presents a huge headache from this perspective and the full consequences weren't understood until after standardization.
|
2,927,120 | 2,928,623 | Profiler for IAR EW for ARM | I am trying to get the profiler plug-in for IAR Embedded Workbench for ARM to work. I have set everything in the documentation but when I fire up C-Spy and start the plug-in I get errors. I tried to different emulators and each gave a different error:
Segger SAM-ICE JTAG Emulator - The following appears in the debug log:
Thu May 27 12:43:04 2010: Profiler: No cycle counter could be found. Profiler will only count function calls.
Thu May 27 12:43:04 2010: Failed to set breakpoint at 0x001411F2
Thu May 27 12:43:04 2010: Profiler: Could not set enough breakpoints.
J-Link Pro Emulator - A pop-up window appears with the following:
No More Breakpoints Available
Available breakpoints: 2048
It appears that the emulators do not support the plug-in. Has anyone successfully used this plug-in? If so with which emulator?
Does anyone know of a alternative method or solution that I could use (i.e. in code)? It would preferably meet the following conditions:
Be as memory efficient as possible because I have very little RAM in the application left.
Be able to play with an RTOS nicely.
| I think there's a better way. Use the GDB Server and use this technique.
|
2,927,136 | 2,927,717 | Developing a sector based partition copying program? | I want to develop a program that copies a partition's 'data' only, to another partition. And I want to do it such that the program starts from the first sector of source partition and checks if a sector is used.
If it is used
copy it to the destination parition.
Else
don't copy.
In other words it's like copying only the contents of a partition to another, sector-by-sector.
Question:
Is there a way to check if a particular sector on harddisk is used or not?
The programming language I am using is C++ and the underlying filesystem in NTFS.
Thanks a lot.
| Your question is fundamentally flawed. NTS can store data and metadata in the same cluster. Both are handled as file attributes.
I'm also wondering what the point is. Without the metadata, raw data is useless. You can't even tell where one file ends and another begins.
|
2,927,165 | 2,927,322 | Confused about definition of a 'median' when constructing a kd-Tree | Im trying to build a kd-tree for searching through a set of points, but am getting confused about the use of 'median' in the wikipedia article. For ease of use, the wikipedia article states the pseudo-code of kd-tree construction as:
function kdtree (list of points pointList, int depth)
{
if pointList is empty
return nil;
else
{
// Select axis based on depth so that axis cycles through all valid values
var int axis := depth mod k;
// Sort point list and choose median as pivot element
select median by axis from pointList;
// Create node and construct subtrees
var tree_node node;
node.location := median;
node.leftChild := kdtree(points in pointList before median, depth+1);
node.rightChild := kdtree(points in pointList after median, depth+1);
return node;
}
}
I'm getting confused about the "select median..." line, simply because I'm not quite sure what is the 'right' way to apply a median here.
As far as I know, the median of an odd-sized (sorted) list of numbers is the middle element (aka, for a list of 5 things, element number 3, or index 2 in a standard zero-based array), and the median of an even-sized array is the sum of the two 'middle' elements divided by two (aka, for a list of 6 things, the median is the sum of elements 3 and 4 - or 2 and 3, if zero-indexed - divided by 2.).
However, surely that definition does not work here as we are working with a distinct set of points? How then does one choose the correct median for an even-sized list of numbers, especially for a length 2 list?
I appreciate any and all help, thanks!
-Stephen
| It appears to me that you understand the meaning of median, but you are confused with something else. What do you mean be distinct set of points?
The code presented by Wikipedia is a recursive function. You have a set of points, so you create a root node and choose a median of the set. Then you call the function recursively - for the left subtree you pass in a parameter with all the points smaller than the split-value (the median) of the original list, for the right subtree you pass in the equal and larger ones. Then for each subtree a node is created where the same thing happens. It goes like this:
First step (root node):
Original set: 1 2 3 4 5 6 7 8 9 10
Split value (median): 5.5
Second step - left subtree:
Set: 1 2 3 4 5
Split value (median): 3
Second step - right subtree:
Set: 6 7 8 9 10
Split value (median): 8
Third step - left subtree of left subtree:
Set: 1 2
Split value (median): 1.5
Third step - right subtree of left subtree:
Set: 3 4 5
Split value (median): 4
Etc.
So the median is chosen for each node in the tree based on the set of numbers (points, data) which go into that subtree. Hope this helps.
|
2,927,250 | 2,927,407 | How to write a flexible modular program with good interaction possibilities between modules? | I went through answers on similar topics here on SO but could't find a satisfying answer. Since i know this is a rather large topic, i will try to be more specific.
I want to write a program which processes files. The processing is nontrivial, so the best way is to split different phases into standalone modules which then would be used as necessary (since sometimes i will be only interested in the output of module A, sometimes i would need output of five other modules, etc). The thing is, that i need the modules to cooperate, because the output of one might be the input of another. And i need it to be FAST. Moreover i want to avoid doing certain processing more than once (if module A creates some data which then need to be processed by module B and C, i don't want to run module A twice to create the input for modules B,C ).
The information the modules need to share would mostly be blocks of binary data and/or offsets into the processed files. The task of the main program would be quite simple - just parse arguments, run required modules (and perhaps give some output, or should this be the task of the modules?).
I don't need the modules to be loaded at runtime. It's perfectly fine to have libs with a .h file and recompile the program every time there is a new module or some module is updated. The idea of modules is here mainly because of code readability, maintaining and to be able to have more people working on different modules without the need to have some predefined interface or whatever (on the other hand, some "guidelines" on how to write the modules would be probably required, i know that). We can assume that the file processing is a read-only operation, the original file is not changed.
Could someone point me in a good direction on how to do this in C++ ? Any advice is wellcome (links, tutorials, pdf books...).
| This looks very similar to a plugin architecture. I recommend to start with a (informal) data flow chart to identify:
how these blocks process data
what data needs to be transferred
what results come back from one block to another (data/error codes/ exceptions)
With these Information you can start to build generic interfaces, which allow to bind to other interfaces at runtime. Then I would add a factory function to each module to request the real processing object out of it. I don't recommend to get the processing objects direct out of the module interface, but to return a factory object, where the processing objects ca be retrieved. These processing objects then are used to build the entire processing chain.
A oversimplified outline would look like this:
struct Processor
{
void doSomething(Data);
};
struct Module
{
string name();
Processor* getProcessor(WhichDoIWant);
deleteprocessor(Processor*);
};
Out of my mind these patterns are likely to appear:
factory function: to get objects from modules
composite && decorator: forming the processing chain
|
2,927,444 | 2,927,492 | sending data packet just before closing socket | Before disconnect the client, the server wants to send some info to the client - why do I(server) disconnect you(client).
If I send packet to the info and close the client socket immediately, closesocket() returns -1 and if I use linger option to work closesocket() successfully, the info cannot be sent completely.
How can I complete this and is it possible to know socket buffer is empty(means my packet sent all)?
thx.
| try to call shutdown() on socket first.
http://msdn.microsoft.com/en-us/library/ms740481%28VS.85%29.aspx
http://www.opengroup.org/onlinepubs/000095399/functions/shutdown.html
|
2,927,448 | 2,927,527 | Sleep Function Error In C | I have a file of data Dump, in with different timestamped data available, I get the time from timestamp and sleep my c thread for that time. But the problem is that The actual time difference is 10 second and the data which I receive at the receiving end is almost 14, 15 second delay. I am using window OS. Kindly guide me.
Sorry for my week English.
| If I understand well:
you have a thread that send data (through network ? what is the source of data ?)
you slow down sending rythm using sleep
the received data (at the other end of network) can be delayed much more (15 s instead of 10s)
If the above describe what you are doing, your design has several flaws:
sleep is very imprecise, it will wait at least n seconds, but it may be more (especially if your system is loaded by other running apps).
networks introduce a buffering delay, you have no guarantee that your data will be send immediately on the wire (usually it is not).
the trip itself introduce some delay (latency), if your protocol wait for ACK from the receiving end you should take that into account.
you should also consider time necessary to read/build/retrieve data to send and really send it over the wire. Depending of what you are doing it can be negligible or take several seconds...
If you give some more details it will be easier to diagnostic the source of the problem. sleep as you believe (it is indeed a really poor timer) or some other part of your system.
If your dump is large, I will bet that the additional time comes from reading data and sending it over the wire. You should mesure time consumed in the sending process (reading time before and after finishing sending).
If this is indeed the source of the additional time, you just have to remove that time from the next time to wait.
Example: Sending the previous block of data took 4s, the next block is 10s later, but as you allready consumed 4s, you just wait for 6s.
sleep is still a quite imprecise timer and obviously the above mechanism won't work if sending time is larger than delay between sendings, but you get the idea.
Correction sleep is not so bad in windows environment as it is in unixes. Accuracy of windows sleep is millisecond, accuracy of unix sleep is second. If you do not need high precision timing (and if network is involved high precision timing is out of reach anyway) sleep should be ok.
|
2,927,914 | 2,928,313 | Generation of .tlb Files in Windows 7 Pro 32-bit | I have a C++ DLL that imports a .tlb file generated in a C# project. The C++ DLL is a wrapper DLL containing functions that call the corresponding C# functions.
When I call the C++ functions on the computer that I built the projects, all works well. But when I copy the DLL's and generated tlb's to another computer with the same exact version of Windows and installed programs andI call the C++ functions, it breaks with a COM error. However, after recompiling the projects on the new computer, everything works again.
I already checked the "Work on All Computers" for both projects but this keeps happening. What else do I need to do for the DLL's to work on all computers?
| The HRESULT you get would be crucial to diagnose this. Forced to guess: did you run Regasm.exe on that machine? Required to make the necessary registry entries so COM can find the server. It is automatic when you build in the IDE.
|
2,928,036 | 2,928,139 | Makefile issue with compiling a C++ program | I recently got MySQL compiled and working on Cygwin, and got a simple test example from online to verify that it worked. The test example compiled and ran successfully.
However, when incorporating MySQL in a hobby project of mine it isn't compiling which I believe is due to how the Makefile is setup, I have no experience with Makefiles and after reading tutorials about them, I have a better grasp but still can't get it working correctly.
When I try and compile my hobby project I recieve errors such as:
Obj/Database.o:Database.cpp:(.text+0x492): undefined reference to `_mysql_insert_id'
Obj/Database.o:Database.cpp:(.text+0x4c1): undefined reference to `_mysql_affected_rows'
collect2: ld returned 1 exit status
make[1]: *** [build] Error 1
make: *** [all] Error 2
Here is my Makefile, it worked with compiling and building the source before I attempted to put in MySQL support into the project. The LIBMYSQL paths are correct, verified by 'mysql_config'.
COMPILER = g++
WARNING1 = -Wall -Werror -Wformat-security -Winline -Wshadow -Wpointer-arith
WARNING2 = -Wcast-align -Wcast-qual -Wredundant-decls
LIBMYSQL = -I/usr/local/include/mysql -L/usr/local/lib/mysql -lmysqlclient
DEBUGGER = -g3
OPTIMISE = -O
C_FLAGS = $(OPTIMISE) $(DEBUGGER) $(WARNING1) $(WARNING2) -export-dynamic $(LIBMYSQL)
L_FLAGS = -lz -lm -lpthread -lcrypt $(LIBMYSQL)
OBJ_DIR = Obj/
SRC_DIR = Source/
MUD_EXE = project
MUD_DIR = TestP/
LOG_DIR = $(MUD_DIR)Files/Logs/
ECHOCMD = echo -e
L_GREEN = \e[1;32m
L_WHITE = \e[1;37m
L_BLUE = \e[1;34m
L_RED = \e[1;31m
L_NRM = \e[0;00m
DATE = `date +%d-%m-%Y`
FILES = $(wildcard $(SRC_DIR)*.cpp)
C_FILES = $(sort $(FILES))
O_FILES = $(patsubst $(SRC_DIR)%.cpp, $(OBJ_DIR)%.o, $(C_FILES))
all:
@$(ECHOCMD) " Compiling $(L_RED)$(MUD_EXE)$(L_NRM).";
@$(MAKE) -s build
build: $(O_FILES)
@rm -f $(MUD_EXE)
$(COMPILER) -o $(MUD_EXE) $(L_FLAGS) $(O_FILES)
@echo " Finished Compiling $(MUD_EXE).";
@chmod g+w $(MUD_EXE)
@chmod a+x $(MUD_EXE)
@chmod g+w $(O_FILES)
$(OBJ_DIR)%.o: $(SRC_DIR)%.cpp
@echo " Compiling $@";
$(COMPILER) -c $(C_FLAGS) $< -o $@
.cpp.o:
$(COMPILER) -c $(C_FLAGS) $<
clean:
@echo " Complete compile on $(MUD_EXE).";
@rm -f $(OBJ_DIR)*.o $(MUD_EXE)
@$(MAKE) -s build
I like the functionality of the Makefile, instead of spitting out all the arguments etc, it just spits out the "Compiling [Filename]" etc.
If I add -c to the L_FLAGS then it compiles (I think) but instead spits out stuff like:
g++: Obj/Database.o: linker input file unused because linking not done
After a full day of trying and research on google, I'm no closer to solving my problem, so I come to you guys to see if you can explain to me why all this is happening and if possible, steps to solve.
Regards,
Steve
| Try changing
$(COMPILER) -o $(MUD_EXE) $(L_FLAGS) $(O_FILES)
to
$(COMPILER) -o $(MUD_EXE) $(O_FILES) $(L_FLAGS)
The linker searches and processes libraries and object files in the order they are specified. Thus when you mention the libraries before the object files, the functions used in the object files may not be loaded from the libraries.
|
2,928,158 | 2,928,768 | How can I load scripts, styles and images from a non-URL source? | I am integrating WebKit (via Qt) into an application. Instead of having WebKit retrieve scripts, CSS files and images via URLs, I want my application to provide them (e.g. retrieved from a database).
For example, a "regular" web page may contain this tag:
<IMG src="photos/album1/123456.jpg">
Instead of WebKit fetching this image from a server or the file system, I would prefer some kind of callback that allows my application to provide this image.
How can I accomplish this?
| Maybe this is a bit overkill, but maybe it could work for you.
Simply have your application act as a HTTP server. Then you could have paths like this:
<IMG src="http://localhost:73617/photos/album1/123456.jpg">
Where 73617 is a random port, you can have your application listen on another port. Then, when your app retrieves the request for the image, it fetches it from wherever you want it to. It still involves a a server but at least you have complete control on where you get your resources from.
So, WebKit sees the url in the image, sends a request, your App gets the request, reads the resource, returns the resource. So basically you are still getting it from your App.
Hope this helps.
|
2,928,409 | 2,928,761 | boost::filesystem::path(std::wstring) throw exception | this code:
boost::filesystem::is_directory("/usr/include");
work fine.
both this code:
boost::filesystem::is_directory(L"/usr/include");
throw an exception:
terminate called after throwing an
instance of 'std::runtime_error'
what():
locale::facet::_S_create_c_locale name
not valid
OS - Linux Mint
boost-1.43
gcc-4.6.0
|
Don't use wide strings on Linux. You don't need them..
What happens that it tries to convert wide string to normal one and for this
creates a locale and probably this locale is not configured in your system.
Bring output of commands:
locale
locale -a
GCC-4.6 wasn't released yet ;-), check if this works with ordinary compiler. Probably libstdc++ wasn't build well.
|
2,928,713 | 2,930,443 | Out of Process COM Server - function calls and threads | When you have an out of process COM Server and you call a function from a Client inside this server from Thread X inside the client, then how this function get executed in the COM Server?
In the thread its currently executing on, or on its main thread?
| Normal COM apartment threading rules are observed. If the object was created by the client in an STA apartment then your client thread need to use a marshaled interface pointer or it gets RPC_E_WRONG_THREAD. The actual method call will execute on the server in its STA thread, it needs to pump a message loop for that to work. Execution is serialized, no locking should be needed.
If it lives in the MTA apartment then the method call will execute on an arbitrary RPC worker thread. And you'll need to take the usual threading precautions.
|
2,928,715 | 2,928,779 | Function should return reference or object? | Let's discuss these two functions:
complex& operator+=(const T& val);
complex operator+(const T& val);
Where "complex" is a name of a class that implements for example complex variable.
So first operator returnes reference in order to be possible to write a+=b+=c ( which is equivalent to b=b+c; a=a+b;).
Second operator returnes and objec(NOT A REFERENCE), be we still able to write a=b+c+d.
Who could explain me this nuance? What is the difference between returning reference or object?
| In 1, a+=b, the += operator modifies a. Therefore it can return a reference to itself, because a itself is the correct result of the operation.
However, in 2. a new object is required because a+b returns something that is not a, so returning a reference to a wouldn't be correct.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.