question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,628,434 | 1,628,730 | null objects vs. empty objects | [ This is a result of Best Practice: Should functions return null or an empty object? but I'm trying to be very general. ]
In a lot of legacy (um...production) C++ code that I've seen, there is a tendency to write a lot of NULL (or similar) checks to test pointers. Many of these get added near the end of a release cycle when adding a NULL-check provides a quick fix to a crash caused by the pointer dereference--and there isn't a lot of time to investigate.
To combat this, I started to write code that took a (const) reference parameter instead of the (much) more common technique of passing a pointer. No pointer, no desire to check for NULL (ignoring the corner case of actually having a null reference).
In C#, the same C++ "problem" is present: the desire to check every unknown reference against null (ArgumentNullException) and to quickly fix NullReferenceExceptions by adding a null check.
It seems to me, one way to prevent this is to avoid null objects in the first place by using empty objects (String.Empty, EventArgs.Empty) instead. Another would be to throw an exception rather than return null.
I'm just starting to learn F#, but it appears there are far fewer null objects in that enviroment. So maybe you don't really have to have a lot of null references floating around?
Am I barking up the wrong tree here?
| I tend to be dubious of code with lots of NULLs, and try to refactor them away where possible with exceptions, empty collections, Java Optionals, and so on.
The "Introduce Null Object" pattern in Martin Fowler's Refactoring (page 260) may also be helpful. A Null Object responds to all the methods a real object would, but in a way that "does the right thing". So rather than always check an Order to see if order.getDiscountPolicy() is NULL, make sure the Order has a NullDiscountPolicy in these cases. This streamlines the control logic.
|
1,628,588 | 1,628,617 | Finding symbols for C++ source file | I have a project that is C++ WIN32 project. I found a problem that
some symbol can be recognized by the windbg but some don't. I don't
know why.
The characteristics are:
1) both are C++ method
2) both function are in one .cpp file
3) the two functions are very close in the source file and neither of
them are enclosed by a #ifdef
4) I have used dbh.exe to check the symbol, the symbol missing in the
windbg is also not in the pdb file.
I am guessing if the symbol missing may due to the inheritance of the
class?
Please suggest, thanks!
Bin
| If you don't use a function, as long as it is not a virtual function, it may be deadstripped by the linker. Unused global data objects may be deadstripped as well.
|
1,628,729 | 1,628,789 | Yet another unit testing / code coverage question. Is my approach sane? | This is yet another Unit Testing question. I'm trying to draw knowledge from a number of places regarding how to proceed, and I wanted to bounce my current understanding off of the collection of experts here.
assume a project for which all dependencies except opengl funkiness are statically linked (except the c run time)
My current understandings so far:
It is ok to make unit tests that only test the public interface of classes because ultimately the class is the unit that is most sane to test. Problems can be hunted down from there (inside the offending class), and a class that is too complicated to debug, requiring unit testing of its internal structures, is a good candidate for having it broken up.
This practice makes it possible to write unit tests in its own project, from a Visual studio perspective.
A code coverage tool, like CoverageMeter, is installed in the main project, and given its own build configuration, like test instead of debug. This will place the metrics inside the object code for the external "viewer" tool to get metrics.
At the same time, the main application is built as a library in the Test configuration, so that the external Unit Test project uses the object code to run its tests. At the same time further, the CoverageMeter code is included in the library that the Unit Test project uses for its run, making the coverage metrics measure how much code is being exercised in unit tests.
With a testing configuration made separate from release or debug, placeholder libraries can be used to break dependencies like opengl.
My questions really are:
Is this pie in the sky stuff?
Do I have my understandings right?
can I actually do the first sentence of 3, is that how I would get the Unit test code to run the object code build in the main app project, or is there another way?
Am I insane?
I am open to any criticism.
Thanks in advance for your time.
UPDATE: So it looks like I have the right idea of what to exercise in my unit tests, but I'm concerned about 3. Is my understanding of those components correct?
Thanks for your responses. Its good to get feedback! This will be my first big project, and I'm trying to understand all of the pieces involved. I appreciate the pointers!
Josh
| I test everything but private methods, since anything else can be called from outside the class, and it would be helpful to ensure that if someone else calls my function it won't cause problems for them.
If they are also testing calling my code then if they make an assumption that is wrong, we can know quickly that a recent change broke something.
Update: I would distribute any tests for public functions with the distribution and internally the rest of the tests. If people are going to write against my API then unit tests serve as a good source of documentation, to show what I expect to happen, and how I expect to treat invalid parameters.
|
1,628,768 | 1,629,074 | Why does an overridden function in the derived class hide other overloads of the base class? | Consider the code :
#include <stdio.h>
class Base {
public:
virtual void gogo(int a){
printf(" Base :: gogo (int) \n");
};
virtual void gogo(int* a){
printf(" Base :: gogo (int*) \n");
};
};
class Derived : public Base{
public:
virtual void gogo(int* a){
printf(" Derived :: gogo (int*) \n");
};
};
int main(){
Derived obj;
obj.gogo(7);
}
Got this error :
>g++ -pedantic -Os test.cpp -o test
test.cpp: In function `int main()':
test.cpp:31: error: no matching function for call to `Derived::gogo(int)'
test.cpp:21: note: candidates are: virtual void Derived::gogo(int*)
test.cpp:33:2: warning: no newline at end of file
>Exit code: 1
Here, the Derived class's function is eclipsing all functions of same name (not signature) in the base class. Somehow, this behaviour of C++ does not look OK. Not polymorphic.
| Judging by the wording of your question (you used the word "hide"), you already know what is going on here. The phenomenon is called "name hiding". For some reason, every time someone asks a question about why name hiding happens, people who respond either say that this called "name hiding" and explain how it works (which you probably already know), or explain how to override it (which you never asked about), but nobody seems to care to address the actual "why" question.
The decision, the rationale behind the name hiding, i.e. why it actually was designed into C++, is to avoid certain counter-intuitive, unforeseen and potentially dangerous behavior that might take place if the inherited set of overloaded functions were allowed to mix with the current set of overloads in the given class. You probably know that in C++ overload resolution works by choosing the best function from the set of candidates. This is done by matching the types of arguments to the types of parameters. The matching rules could be complicated at times, and often lead to results that might be perceived as illogical by an unprepared user. Adding new functions to a set of previously existing ones might result in a rather drastic shift in overload resolution results.
For example, let's say the base class B has a member function foo that takes a parameter of type void *, and all calls to foo(NULL) are resolved to B::foo(void *). Let's say there's no name hiding and this B::foo(void *) is visible in many different classes descending from B. However, let's say in some [indirect, remote] descendant D of class B a function foo(int) is defined. Now, without name hiding D has both foo(void *) and foo(int) visible and participating in overload resolution. Which function will the calls to foo(NULL) resolve to, if made through an object of type D? They will resolve to D::foo(int), since int is a better match for integral zero (i.e. NULL) than any pointer type. So, throughout the hierarchy calls to foo(NULL) resolve to one function, while in D (and under) they suddenly resolve to another.
Another example is given in The Design and Evolution of C++, page 77:
class Base {
int x;
public:
virtual void copy(Base* p) { x = p-> x; }
};
class Derived : public Base{
int xx;
public:
virtual void copy(Derived* p) { xx = p->xx; Base::copy(p); }
};
void f(Base a, Derived b)
{
a.copy(&b); // ok: copy Base part of b
b.copy(&a); // error: copy(Base*) is hidden by copy(Derived*)
}
Without this rule, b's state would be partially updated, leading to slicing.
This behavior was deemed undesirable when the language was designed. As a better approach, it was decided to follow the "name hiding" specification, meaning that each class starts with a "clean sheet" with respect to each method name it declares. In order to override this behavior, an explicit action is required from the user: originally a redeclaration of inherited method(s) (currently deprecated), now an explicit use of using-declaration.
As you correctly observed in your original post (I'm referring to the "Not polymorphic" remark), this behavior might be seen as a violation of IS-A relationship between the classes. This is true, but apparently back then it was decided that in the end name hiding would prove to be a lesser evil.
|
1,628,913 | 1,628,967 | Memory mapping physical disks and volumes | In Windows it's possible to open devices and volumes via CreateFile(). I've used this successfully before to ReadFile() from devices, but now I want to switch to memory-mapping. In the following code, I receive INVALID_HANDLE_VALUE for the value of b, and c is set to 87, ERROR_INVALID_PARAMETER.
HANDLE a = ::CreateFileA("\\\\.\\h:", GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY | FILE_FLAG_NO_BUFFERING, NULL);
HANDLE b = ::CreateFileMappingA(a, NULL, PAGE_READONLY, 0, 0, NULL);
DWORD c = ::GetLastError();
How can I get this to work?
| You can't. CreateFileMapping can only create a mapping to a file. Take a look at the difference in the documentation between the hFile parameter for ReadFile and for CreateFileMapping. For ReadFile it lists all the different types of handles it accepts (which includes devices), for CreateFileMapping it only lists files.
|
1,629,123 | 1,629,378 | To write a bootloader in C or C++? | I am writing a program, more specifically a bootloader, for an embedded system. I am going to use a C library to interact with some of the hardware components and I have the choice of writing it either in C or C++. Is there any reason I should choose one over the other? I do not need the object oriented features of C++ but it does have a stronger type system. Could it have other language features that would make the program more robust? I know some people avoid C++ because it can (but not always) generate large firmware images.
| This isn't a particularly straightforward question to answer. It depends on a number of factors including:
How you prefer to layout your code.
Whether there's a C++ compiler available for your target (and any other targets you may wish to use the bootloader on).
How critical the code size is for your application (we're talking about 10% extra maybe, not MB as suggested by another answer).
Personally, I really like classes as a way of laying out my code. Even when writing C code, I'll tend to keep everything in modular files with file-scope static functions "simulating" member functions and (a few) file-scope static variables to "simulate" member variables. Having said that, most of my existing embedded projects (all of which are relatively small scale, up to a maximum of 128kB flash including bootloader, but usually less) have tended to be written in C. Now that I have a C++ compiler though, I'm certainly considering moving to C++.
There are considerable benefits to C++ from simply using references, overloading and templates, even if you don't go as far as classes. Certainly, I'd stop short of using a lot of more advanced features, including the use of dynamic memory allocation (new). Then again, I'd avoid dynamic memory allocation (malloc etc) in embedded C as well if possible.
If you have a C++ compiler (even if it's only g++), it is worth running your code through it just for the additional type checking so that you can reduce the number of problems in your code. The C++ compiler can pick up on a few things that even static analysis tools won't spot.
For a good discussion on many invalid reasons people reject C++, see Dan Saks' article on Embedded.com.
|
1,629,172 | 2,170,880 | How do you get the icon, MIME type, and application associated with a file in the Linux Desktop? | Using C++ on the Linux desktop, what is the best way to get the icon, the document description and the application "associated" with an arbitrary file/file path?
I'd like to use the most "canonical" way to find icons, mime-type/file type descriptions and associated applications on both KDE and gnome and I'd like to avoid any "shelling out" to the command line and "low-level" routines as well as avoiding re-inventing the wheel myself (no parsing the mime-types file and such).
Edits and Notes:
Hey, I originally asked this question about the QT file info object and the answer that "there is no clear answer" seems to be correct as far as it goes. BUT this is such a screwed-up situation that I am opening the question looking for more information.
I don't care about QT in particular any more, I'm just looking for the most cannonical way to find the mime type via C++/c function calls on both KDE and gnome (especially Gnome, since that's where things confuse me most). I want to be able show icons and descriptions matching Nautilus in Gnome and Konquerer/whatever on KDE as well as opening files appropriately, etc.
I suppose it's OK that I get this separately for KDE and Gnome. The big question is what's the most common/best/cannonical way to get all this information for the Linux desktop? Gnome documentation is especially opaque. gnome-vsf has mime routines but it's deprecated and I can't find a mime routine for GIO/GFS, gnome-vsf's replacement. There's a vague implication that one should use the open desktop applications but which one to use is obscure. And where does libmagic and xdg fit in?
Pointers to an essay summarizing the issues gladly accepted. Again, I know the three line answer is "no such animal" but I'm looking for the long answer.
| Here is an example of using GLib/GIO to get the information you want.
#include <gio/gio.h>
#include <stdio.h>
int
main (int argc, char **argv)
{
g_thread_init (NULL);
g_type_init ();
if (argc < 2)
return -1;
GError *error;
GFile *file = g_file_new_for_path (argv[1]);
GFileInfo *file_info = g_file_query_info (file,
"standard::*",
0,
NULL,
&error);
const char *content_type = g_file_info_get_content_type (file_info);
char *desc = g_content_type_get_description (content_type);
GAppInfo *app_info = g_app_info_get_default_for_type (
content_type,
FALSE);
/* you'd have to use g_loadable_icon_load to get the actual icon */
GIcon *icon = g_file_info_get_icon (file_info);
printf ("File: %s\nDescription: %s\nDefault Application: %s\n",
argv[1],
desc,
g_app_info_get_executable (app_info));
return 0;
}
|
1,629,297 | 1,629,372 | Whitespace at end of file causing EOF check to fail in C++ | I am reading in data from a file that has three columns. For example the data will look something like:
3 START RED
4 END RED
To read in the data I am using the following check:
while (iFile.peek() != EOF) {
// read in column 1
// read in column 2
// read in column 3
}
My problem is that the loop usually does an extra loop. I am pretty sure this is because a lot of text editors seem to put a blank line after the last line of actual content.
I did a little bit of Googling and searched on SO and found some similar situations such as Reading from text file until EOF repeats last line however I couldn't quite seem to adapt the solution given to solve my problem. Any suggestions?
| Presuming iFile is an istream:
You should break out of the loop on any error, not only on EOF (which can be checked for with iFile.eof(), BTW), because this is an endless loop when any format failure sets the stream into a bad state other that EOF. It is usually necessary to break out of a reading loop in the middle of the loop, after everything was read (either successfully or not), and before it is entered.
To make sure there isn't anything interesting coming anymore, you could, after the loop, reset the stream state and then try to read whitespace only until your reach EOF:
while( !iFile.eof() )
{
iFile >> std::ws;
string line;
std::getline(iFile,line);
if(!line.empty()) error(...);
}
|
1,629,406 | 1,629,417 | C++ template specialization without default function | I have the following code that compiles and works well:
template<typename T>
T GetGlobal(const char *name);
template<>
int GetGlobal<int>(const char *name);
template<>
double GetGlobal<double>(const char *name);
However I want to remove the "default" function. That is, I want to make all calls to GetGlobal<t> where 't' is not an int or a double an error.
For example, GetGlobal<char>() should be a compile time error.
I tried to just delete the default function, but, as I imagined, I received a lot of errors.. So is there a way to "disable" it and allow calls only to the specialized versions of the function?
Thanks!
| To get a compile-time error implement it as:
template<typename T>
T GetGlobal(const char *name) { T::unimplemented_function; }
// `unimplemented_function` identifier should be undefined
If you use Boost you could make it more elegant:
template<typename T>
T GetGlobal(const char *name) { BOOST_STATIC_ASSERT(sizeof(T) == 0); }
C++ Standard guarantees that there is no such type which has sizeof equal to 0, so you'll get a compile-time error.
As sbi suggested in his comments the last could be reduced to:
template<typename T>
T GetGlobal(const char *name) { char X[!sizeof(T)]; }
I prefer the first solution, because it gives more clear error message (at least in Visual C++) than the others.
|
1,629,514 | 1,629,533 | Pointer to a Qt Slot | i want to build a pointer to a Qt Slot:
union {
void (*set_slot)(unsigned long value);
void (*refresh_slot)(void);
} the_slot;
The slot definition is:
void set_pwm(unsigned long new_pwm);
I try to do something like this:
the_slot.set_slot = set_pwm;
But the compiler says that the signature does not match:
error: argument of type void
(DriverBoard::)(long unsigned
int)' does not matchvoid (*)(long
unsigned int)'
hint: the slot is in class DriverBoard
Any idea where my error is?
And if someone knows - is it possible to do something like that with signals also?
Thanks!
Simon
| Slots and signals are identified by their names (when you do use SLOT(set_pwm(unsigned long)) in your code, you are constructing a string). You can simply store the name and the object and then call the slot using QMetaObject.
You can use pointers to member functions in C++ (see the C++ faq), but in this case I'd suggest to use Qt's meta object system.
|
1,629,685 | 4,280,418 | When and how to use GCC's stack protection feature? | I have enabled the -Wstack-protector warning when compiling the project I'm working on (a commercial multi-platform C++ game engine, compiling on Mac OS X 10.6 with GCC 4.2).
This flag warns about functions that will not be protected against stack smashing even though -fstack-protector is enabled.
GCC emits some warnings when building the project:
not protecting function: no buffer at least 8 bytes long
not protecting local variables: variable length buffer
For the first warning, I found that it is possible to adjust the minimum size a buffer must have when used in a function, for this function to be protected against stack smashing: --param ssp-buffer-size=X can be used, where X is 8 by default and can be as low as 1.
For the second warning, I can't suppress its occurrences unless I stop using -Wstack-protector.
When should -fstack-protector be used? (as in, for instance, all the time during dev, or just when tracking bugs down?)
When should -fstack-protector-all be used?
What is -Wstack-protector telling me? Is it suggesting that I decrease the buffer minimum size?
If so, are there any downsides to putting the size to 1?
It appears that -Wstack-protector is not the kind of flag you want enabled at all times if you want a warning-free build. Is this right?
| Stack-protection is a hardening strategy, not a debugging strategy. If your game is network-aware or otherwise has data coming from an uncontrolled source, turn it on. If it doesn't have data coming from somewhere uncontrolled, don't turn it on.
Here's how it plays out: If you have a bug and make a buffer change based on something an attacker can control, that attacker can overwrite the return address or similar portions of the stack to cause it to execute their code instead of your code. Stack protection will abort your program if it detects this happening. Your users won't be happy, but they won't be hacked either. This isn't the sort of hacking that is about cheating in the game, it's the sort of hacking that is about someone using a vulnerability in your code to create an exploit that potentially infects your user.
For debugging-oriented solutions, look at things like mudflap.
As to your specific questions:
Use stack protector if you get data from uncontrolled sources. The answer to this is probably yes. So use it. Even if you don't have data from uncontrolled sources, you probably will eventually or already do and don't realize it.
Stack protections for all buffers can be used if you want extra protection in exchange for some performance hit. From gcc4.4.2 manual:
-fstack-protector
Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call alloca, and functions with buffers larger than 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits.
-fstack-protector-all
Like -fstack-protector except that all functions are protected.
The warnings tell you what buffers the stack protection can't protect.
It is not necessarily suggesting you decrease your minimum buffer size, and at a size of 0/1, it is the same as stack-protector-all. It is only pointing it out to you so that you can, if you decide redesign the code so that buffer is protected.
No, those warnings don't represent issues, they just point out information to you. Don't use them regularly.
|
1,629,782 | 1,670,609 | Makefile generator for c++? | Do the following build systems: cmake, jam and bjam also generate makefiles like qmake does? What utility does MS visual c++ uses to generate make file?
| CMake does generate makefiles and projects files for several different build systems on different platforms. CMake is more generalised than qmake, which is specialised for Qt projects.
jam and bjam are replacements for make, i.e. different syntax. They do not generate build files.
You can generate makefiles (that nmake can use) from Visual Studio by saving them out once you have generated a solution.
|
1,629,829 | 1,630,740 | Ambiguous overload on template operators | I am working on two wrapper classes that define real and complex data types. Each class defines overloaded constructors, as well as the four arithmetic operators +,-,*,/ and five assignment operators =,+= etc. In order to avoid repeating code, I was thinking of using template functions when the left- and right-hand-side arguments of an operator are of a different data type:
// real.h
class Real {
public:
explicit Real(const double& argument) {...}
explicit Real(int argument) {...}
...
friend const operator*(const Real&; const Real&);
template <class T> friend const Real operator*(const Real&, const T&);
template <class T> friend const Real operator*(const T&, cont Real&);
// Here, T is meant to be a template parameter for double and int
// Repeat for all other arithmetic and assignment operators
};
// complex.h
class Complex {
public:
explicit Complex(const Real& realPart) {...}
explicit Complex(const Real& realPart, const Real& imaginaryPart) {...}
// Overload for double and int data types
...
friend const operator*(const Complex&, const Complex&);
template <class T> friend const Complex operator*(const Complex&, const T&);
template <class T> friend const Complex operator*(const T&, cont Complex&);
// Here, T is is a template parameter for Real, double and int
...
};
The problem here is that code like:
//main.cpp
void main() {
Complex ac(2.0, 3.0);
Real br(2.0);
Complex cc = ac * br;
}
returns the compiler (gcc) error ambiguous overload for 'operator*' in 'ac * br', as the compiler cannot tell the difference between:
template <class T> friend const Complex operator*(const Complex&, const T&) [with T = Real]
template <class T> friend const Real operator*(const T&, cont Real&) [with T = Complex]
Is there a way to specify that T cannot be a Complex in the template operator* definition in the class Real? Or do I have to do without templates and define each operator for every possible combination of argument data types? Or is there a way to redesign the code?
| Ah, the problem of operators...
Boost created a nice library so that by providing a minimum of logic all the other variations are automagically added for you!
Take a look at Boost.Operators !
Now for your problem, actually as you noticed, you will have to define both flavors of the operators (int and double) rather than using a generic template. If there is a lot of logic in these operators (which I doubt), you can always have them call a common (templated) method.
template <typename T>
Complex complex_mult_impl(T const& lhs, Complex const& rhs) { ... } // Note (1)
// return type is not 'Complex const', see (2)
Complex operator*(int lhs, Complex const& rhs)
{
return complex_mult_impl(lhs,rhs);
}
But if you use Boost.operators you only provide Complex::operator*=(int) and Complex::operator*=(double) and the stand-alone versions will be automatically deduced :)
(1) You might use pass by-value here, if all arguments are built-ins. You might also want to consider Boost.CallTraits, which automatically chooses between by-value and by-ref depending if the argument is built-in or not. It is handy for templates.
(2) When returning arguments by value, it is non-sensical to qualify them as const. The const keyword only means something for references and pointers, here nothing prevents the user to instantiate a 'simple' Complex... and you are fortunate it doesn't!
|
1,630,169 | 1,630,245 | How to create nested Lua tables using the C API | I want to create a table like
myTable = {
[0] = { ["a"] = 4, ["b"] = 2 },
[1] = { ["a"] = 13, ["b"] = 37 }
}
using the C API?
My current approach is
lua_createtable(L, 0, 2);
int c = lua_gettop(L);
lua_pushstring(L, "a");
lua_pushnumber(L, 4);
lua_settable(L, c);
lua_pushstring(L, "b");
lua_pushnumber(L, 2);
lua_settable(L, c);
to create the inner tables in a loop. Before, this loop, I use
lua_createtable(L, 2, 0);
int outertable = lua_gettop(L);
to create the outer table for 2 numeric slots.
But how can I save the inner tables to the outer table?
| Here's a full and minimal program demonstrating how to nest tables. Basically what you are missing is the lua_setfield function.
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main()
{
int res;
lua_State *L = lua_open();
luaL_openlibs(L);
lua_newtable(L); /* bottom table */
lua_newtable(L); /* upper table */
lua_pushinteger(L, 4);
lua_setfield(L, -2, "four"); /* T[four] = 4 */
lua_setfield(L, -2, "T"); /* name upper table field T of bottom table */
lua_setglobal(L, "t"); /* set bottom table as global variable t */
res = luaL_dostring(L, "print(t.T.four == 4)");
if(res)
{
printf("Error: %s\n", lua_tostring(L, -1));
}
return 0;
}
The program will simply print true.
If you need numeric indices, then you continue using lua_settable:
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main()
{
int res;
lua_State *L = lua_open();
luaL_openlibs(L);
lua_newtable(L); /* bottom table */
lua_newtable(L); /* upper table */
lua_pushinteger(L, 0);
lua_pushinteger(L, 4);
lua_settable(L, -3); /* uppertable[0] = 4; pops 0 and 4 */
lua_pushinteger(L, 0);
lua_insert(L, -2); /* swap uppertable and 0 */
lua_settable(L, -3); /* bottomtable[0] = uppertable */
lua_setglobal(L, "t"); /* set bottom table as global variable t */
res = luaL_dostring(L, "print(t[0][0] == 4)");
if(res)
{
printf("Error: %s\n", lua_tostring(L, -1));
}
return 0;
}
Rather than using absolute indices of 0 like I did, you might want to use lua_objlen to generate the index.
|
1,630,406 | 1,630,433 | C++ template specialization with <int&> not picking up an int | I have the following code:
template <typename T> LuaCall& operator>>(T) { BOOST_STATIC_ASSERT(sizeof(T) == 0); }
template <> LuaCall& operator>><int&>(int& val) { mResults.push_back(std::make_pair(LUA_RESULT_INTEGER, (void *)&val)); return *this; }
template <> LuaCall& operator>><float&>(float& val) { mResults.push_back(std::make_pair(LUA_RESULT_FLOAT, (void *)&val)); return *this; }
template <> LuaCall& operator>><double&>(double& val) { mResults.push_back(std::make_pair(LUA_RESULT_DOUBLE, (void *)&val)); return *this; }
template <> LuaCall& operator>><bool&>(bool& val) { mResults.push_back(std::make_pair(LUA_RESULT_BOOLEAN, (void *)&val)); return *this; }
template <> LuaCall& operator>><std::string&>(std::string& val) { mResults.push_back(std::make_pair(LUA_RESULT_STRING, (void *)&val)); return *this; }
template <> LuaCall& operator>><LuaNilStruct>(LuaNilStruct) { mResults.push_back(std::make_pair(LUA_RESULT_NIL, (void *)NULL)); return *this; }
And then:
int abc;
LuaCall(l, "test") % "test" % 5 % LuaNil % 2.333 >> abc;
I want it to work kinda like cin >> does, ie it needs to write to abc the return value of the lua function. So I need its address.. but it defaults on the default template. What am I doing wrong? There is surely a way to do this since cin does exactly that.
Thanks!
Note to whoever changed the %'s to >>: I changed it back since it's the way it is :D The code calls the Lua function test("test", 5, nil, 2.333) and saves its return value to abc. %'s are for the parameters of the functions, >>'s are for the return value(s).
template <typename T>
LuaCall& operator%(T val) {
mLua->Push(val);
++mArguments;
return *this;
}
| You'v written operator>> as a unary operator, but it's a binary operator. LeftHandSide >> RightHandSide.
The form std::cout <"Hello" << " world"; therefore is (operator<<(operator<<(std::cout, "Hello"), " world); - the first << returns std::cout for use as the left-hand side of the second <<.
The real problem is that in your code, lookup happens as follows:
Candiate functions are determined (only one candidate, the template)
T is deduced.
Determine which specialization (if any) to instantiate.
In step 2, T==int. In step 3, there are no specializations for T==int so the base template is chosen and instantiated. You might want to use an overload instead of a specialization. The overload would be a better match in step 1 so you don't even get to the point of template argument deduction
|
1,630,464 | 1,631,554 | Are there good examples of good C++ I/O usage | I am heavily involved in doing I/O in C++ (currently using it for printing headers, tables, some data alignments), and wonder about it proper/great usage in either open source projects or general examples/nippets
I use things such:
cout.setf(ios::right,ios::jyustified);
cout<<std::setw()
std::copy (vector.begin(), vector.end(), std::osteam_iterator<const Foo *>
std::cout,"\n"); //provided I have operator << in/for Foo
locale mylocale("");
cout.imbue( mylocale );
I don't like my current implementation, as I have a lot of forced (\t) and spaces to ensure correct indentation. Hence I want to see how I/O is used by top notch professionals.
| One thing that's extremely useful is the Boost IO state saver library. This provides (in particular) a clean way to deal with "sticky" flags.
I tend to agree with David Seiler though -- very few people will be happy with output that's pure text in a single font, etc., that you get by writing just text. HTML, however, is quite easy to generate. RAII, however, can work nicely with fixed-structure documents to ensure that you always generate properly nested tags.
|
1,630,484 | 1,630,545 | compiler error help (E2209 Unable to open include file) | I am using Borland C++ Builder 6. I have installed LMD Tool version 7, and ABC for Delphi 6 companion version (runtime pakage only).
When I compiled a software unit, I received the following error messages:
[C++ Error] iss_hmi_gui_cached.h(58): E2209 Unable to open include file 'abcbtn.hpp'
Full parser context
C++ Error] iss_hmi_gui_cached.h(59): E2209 Unable to open include file 'abcctl32.hpp'
Full parser context
[C++ Error] iss_hmi_gui_cached.h(61): E2209 Unable to open include file 'abcexctl.hpp'
and
[C++ Error] Lmdcontrol.hpp(24): E2209 Unable to open include file 'Uxtheme.hpp'
[C++ Error] Lmdcustomspeedbutton.hpp(22): E2209 Unable to open include file 'Uxtheme.hpp'
I have searched my PC, and I could not find Uxtheme.hpp anywhere.
Any help is appreciated.
Thanks in advance
David.
| UxTheme.h is part of the Windows SDK. The SDK comes with the newer versions of visual studio, but you can download it from microsoft. You will also have to tell the compiler where to find the SDK header and library files.
|
1,630,489 | 1,630,993 | Increasing memory usage in sqlite3? | I've written a console app which receives events via boost::interprocess memory and dumps the info into an sqlite3 database. While running the app I've noticed that, in the Windows task manager, the memory usage was cyclically increasing every... 30s-1min. This led me to believe that the problem lies within the main loop in which I execute my SQL. I've added some monitoring and apparently the sqlite3_memory_usage returns increasing results every couple loop iterations.
Can somebody tell me what am I doing wrong? Am I missing something I should de-allocate ?
Here are 2 strings I use to generate SQL
const std::string sql_insert =
"INSERT INTO EventsLog "
"(Sec, uSec, DeviceId, PmuId, EventId, Error, Msg) "
"VALUES (%ld, %ld, %ld, %d, %ld, %d, %Q)";
const std::string sql_create =
"CREATE TABLE IF NOT EXISTS EventsLog("
"Id INTEGER PRIMARY KEY AUTOINCREMENT, "
"Sec INTEGER NOT NULL, "
"uSec INTEGER NOT NULL, "
"DeviceId INTEGER NOT NULL, "
"PmuId INTEGER NOT NULL, "
"EventId INTEGER NOT NULL, "
"Error INTEGER NOT NULL, "
"Msg TEXT"
")";
In here, I generate the SQL INSERT command
std::string construct_sql_query
(const ELMessageData & data)
{
std::string query = "";
ptime jan1st1970 = ptime(date(1970,1,1));
ptime now = boost::posix_time::microsec_clock::universal_time();
time_duration delta = now - jan1st1970;
TimeVal time((uint32)delta.total_seconds(),
(uint32)now.time_of_day().fractional_seconds());
char * const sql = sqlite3_mprintf(sql_insert.c_str(),
time.tv_sec,
time.tv_usec,
data.getDeviceId(),
data.getPmuId(),
data.getEventId(),
(data.getIsError() ? 1 : 0),
data.getExMsg().c_str());
if(sql == NULL)
post_event(EvIOError("Failed to create the SQL command",
"StLoggingEvents::_construct_sql_query"));
query = std::string(sql);
sqlite3_free(sql);
return query;
} // construct_sql_query
Here's the main loop in which I execute the INSERT commands
while(true)
{
m_exchange_obj->wait(); // wait for the semaphore to be raised
const std::string sql = construct_sql_query
(m_exchange_obj->receive());
char ** err = NULL;
const int rc = sqlite3_exec(m_db_handle,
sql.c_str(),
NULL,
NULL,
err);
sqlite3_free(err);
if(rc != SQLITE_OK)
{
LERR_ << "Error while inserting into the database";
LERR_ << "Last SQL Query : ";
LERR_ << sql;
}
else
{
LDBG_ << "Event logged...";
LDBG_ << "Sqlite3 memory usage : "
<< sqlite3_memory_used();
}
}
| I second the suggestion of trying this under valgrind. You may also want to look at google's tcmalloc replacement... It can print pretty graphs showing you all your leaks... That said, I hope you get the answer for this... I plan on using SQLite in an upcoming project...
|
1,630,547 | 1,630,565 | Using the same header files as those in static library | If a header file (.h) included in the source file has also been included in a static library (.lib), what will happen?
| A typical library implementation will include its own header, so this is not a particularly special case.
If the header declares things like global static variables, you of course can't define them more than once. Typically a library will include definitions for the data it declares (or, better, not declare any static global data) so your code that uses the library shouldn't duplicate those.
|
1,630,709 | 1,631,080 | boost spirit 2.x: how to deal with keywords and identifiers? | good day.
i've been using boost spirit classic in the past and now i'm trying to stick to the newer one, boost spirit 2.x. could someone be so kind to point me in how to deal with keywords? say, i want to distinguish between "foo" and "int" where "foo" is identifier and "int" is just a keyword. i want to protect my grammar from incorrect parsing, say, "intfoo".
okay, i have
struct my_keywords : boost::spirit::qi::symbols<char, std::string> {
my_keywords() {
add
("void")
("string")
("float")
("int")
("bool")
//TODO: add others
;
}
} keywords_table_;
and the ident rule declared as:
boost::spirit::qi::rule<Iterator, std::string(), ascii::space_type> ident;
ident = raw[lexeme[((alpha | char_('_')) >> *(alnum | char_('_'))) - keywords_table_]];
and, say, some rule:
boost::spirit::qi::rule<Iterator, ident_decl_node(), ascii::space_type> ident_decl;
ident_decl = ("void" | "float" | "string" | "bool") >> ident;
how to write it correctly, stating that "void", "float", etc are keywords?
thanks in advance.
| Hmmm just declare your rule to be:
//the > operator say that your keyword MUST be followed by an ident
//instead of just may (if I understood spirit right the >> operator will
//make the parser consider other rules if it fail which might or not be
//what you want.
ident_decl = keyword_table_ > ident;
Expending on your exemple you should have something like this at the end:
struct my_keywords : boost::spirit::qi::symbols<char, int> {
my_keywords() {
add
("void", TYPE_VOID)
("string", TYPE_STRING)
("float", TYPE_FLOAT)
("int", TYPE_INT)
("bool", TYPE_BOOL)
//TODO: add others
;
}
} keywords_table_;
//...
class ident_decl_node
{
//this will enable fusion_adapt_struct to access your private members
template < typename, int>
friend struct boost::fusion::extension::struct_member;
//new version of spirit use:
//friend struct boost::fusion::extension::access::struct_member;
int type;
std::string ident;
};
BOOST_FUSION_ADAPT_STRUCT(
ident_decl_node,
(int, type)
(std::string, ident)
)
//...
struct MyErrorHandler
{
template <typename, typename, typename, typename>
struct result { typedef void type; };
template <typename Iterator>
void operator()(Iterator first, Iterator last, Iterator error_pos, std::string const& what) const
{
using boost::phoenix::construct;
std::string error_msg = "Error! Expecting ";
error_msg += what; // what failed?
error_msg += " here: \"";
error_msg += std::string(error_pos, last); // iterators to error-pos, end
error_msg += "\"";
//put a breakpoint here if you don't have std::cout for the console or change
//this line for something else.
std::cout << error_msg;
}
};
//...
using boost::spirit::qi::grammar;
using boost::spirit::ascii::space_type;
typedef std::vector<boost::variant<ident_decl_node, some_other_node> ScriptNodes;
template <typename Iterator>
struct NodeGrammar: public grammar<Iterator, ScriptNodes(), space_type>
{
using boost::spirit::arg_names; //edit1
NodeGrammar: NodeGrammar::base_type(start)
{
//I had problem if I didn't add the eps rule (which do nothing) so you might
//want to leave it
start %= ident_decl | some_other_node_decl >> eps;
ident_decl %= keyword_table > ident;
//I'm not sure if the %= operator will work correctly on this, you might have to do
//the push_back manually but I think it should work
ident %= raw[lexeme[((alpha | char_('_')) >> *(alnum | char_('_'))) - keywords_table_]];
on_error<fail>(start, error_handler(_1, _2, _3, _4)); //edit1
}
my_keywords keyword_table_;
boost::spirit::qi::rule<Iterator, ScriptNodes(), ascii::space_type> start;
boost::spirit::qi::rule<Iterator, ident_decl_node(), ascii::space_type> ident_decl;
boost::spirit::qi::rule<Iterator, some_other_node(), ascii::space_type> ident_decl;
boost::spirit::qi::rule<Iterator, std::string(), ascii::space_type> ident;
boost::phoenix::function<MyErrorHandler> error_handler; //edit1
};
Also I don't know which version you use but I used the one in boost 1.40 and it seems there is a bug
when using operator %= followed by only one argument (the parser would not parse correctly this rule). Ex:
ident_decl %= ident;
do this instead
ident_decl %= ident > eps;
which should be equivalent.
Hope this helped.
|
1,630,860 | 1,630,921 | Read numbers and Convert them into doubles? | Okay, so i have a fairly annoying problem, one of the applications we use hdp, dumps HDF values to a text file.
So basically we have a text file consisting of this:
-8684 -8683 -8681 -8680 -8678 -8676 -8674 -8672 -8670 -8668 -8666
-8664 -8662 -8660 -8657 -8655 -8653 -8650 <trim... 62,000 more rows>
Each of these represent a double:
E.g.:
-8684 = -86.84
We know the values will be between 180 -> -180. But we also have to process around 65,000 rows of this. So time is kinda important.
Whats the best way to deal with this? (i can't use Boost or any of the other libraries, due to internal standards)
| As you wish, as an answer instead... :)
Can't you just use standard iostream?
double val; cin >> &val; val/=100;
rinse, repeat 62000*11 times
|
1,630,877 | 1,631,106 | C++ template recursion - how to solve? | Im stuck again with templates.
say, i want to implement a guicell - system. each guicell can contain a number of child-guicells. so far, so tree-structure. in std-c++ i would go for sthg. like:
template <typename T>
class tree
{
public:
void add (T *o) { _m_children.push_back (o); }
void remove (T *o) { ... };
list<T*> _m_children;
};
class _cell : public tree<_cell>
{
public:
_cell () { x = 0; y =0; }
long x,y;
};
But now i want to go further, and make the cells referencable if the coder wishes so. so i basically implement a refTree - class for that purpose that also takes just pointers (_cell*) as input.
template <typename T>
class refTree
{
public:
void add (T *o) { _ref<T> r = o; _m_children.push_back (r); }
void remove (T *o) { ... }
list<_ref<T> > _m_children;
};
Also this is still working fine. using
class _cell : public refTree<_cell>
{
:
};
no changes to the user-code, but all added _cell* are now referenced before they are added to the tree.
Good, but now i want to be able to chose on _cell - level which tree-template implementation to use. So this means i have to make the _cell - class a template class that takes a template class as parameter (the chosen tree template).
template <template <typename> class __TyTree = tree>
class Cell : public __TyTree <Cell> // cannot work - no question, Cell expects input
{
};
And here we got the recursive problem - ofcourse the compiler can't resolve that, because Cell is awaiting a tree - parameter which is expecting a simple-type parameter (which should be a Cell ofc. is awaiting a tree - parameter which is expecting a simple.... ).
You get the picture - what is a proper solution to that kind of problem ?
| There is no recursion. Template argument for Cell is __TyTree, not __TyTree<Cell>.
template <template <typename> class __TyTree = tree>
class Cell : public __TyTree <Cell<__TyTree> >
{
};
int main()
{
Cell mycell0; // error
Cell<> mycell1; // ok. tree is used
Cell<tree> mycell2;
Cell<refTree> mycell3;
}
P.S. You should not use two leading underscores in __TyTree because it is reserved for implementation purposes by C++ Standard.
|
1,631,065 | 1,631,155 | Is libssl version 0.9.8e compatible with 0.9.7a? | I'm using a third party static library in my C++ project that has a dependency on libssl version 0.9.7a. Due to various reasons, the libssl version that my project used is 0.9.8e.
Everything was working fine, until the third party made a recent change to their static library. I wasn't able to successfully compile my application when it included this new version of the static library. The old version compiles fine.
I'm not very familiar with these library dependencies and their backwards compatibility. We were told that we must use the version suggested by the third party. I just want to know if that is really the reason. IMO, I guess it should be backwards compatible, shouldn't it?
Any direction with troubleshooting this issue is very much appreciated.
The following is the compilation error that I'm getting:
cc1plus: note: obsolete option -I- used, please use -iquote instead
In file included from /usr/include/openssl/e_os2.h:56,
from /usr/include/openssl/ssl.h:173,
from MyClass.cpp:28:
/usr/include/openssl/opensslconf.h:13:30: error: opensslconf-i386.h: No such file or directory
/usr/include/openssl/bn.h:288: error: expected ';' before '*' token
/usr/include/openssl/bn.h:304: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:407: error: 'BN_ULONG' was not declared in this scope
/usr/include/openssl/bn.h:450: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:451: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:452: error: 'BN_ULONG' has not been declared
/usr/include/openssl/bn.h:453: error: 'BN_ULONG' has not been declared
/usr/include/openssl/bn.h:454: error: 'BN_ULONG' has not been declared
/usr/include/openssl/bn.h:455: error: 'BN_ULONG' has not been declared
/usr/include/openssl/bn.h:456: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:471: error: 'BN_ULONG' has not been declared
/usr/include/openssl/bn.h:764: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:765: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:766: error: variable or field 'bn_sqr_words' declared void
/usr/include/openssl/bn.h:766: error: 'BN_ULONG' was not declared in this scope
/usr/include/openssl/bn.h:766: error: 'rp' was not declared in this scope
/usr/include/openssl/bn.h:766: error: expected primary-expression before 'const'
/usr/include/openssl/bn.h:766: error: expected primary-expression before 'int'
/usr/include/openssl/bn.h:767: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:768: error: 'BN_ULONG' does not name a type
/usr/include/openssl/bn.h:769: error: 'BN_ULONG' does not name a type
/usr/include/openssl/ssl3.h:303: error: 'PQ_64BIT' does not name a type
/usr/include/openssl/pqueue.h:73: error: 'PQ_64BIT' does not name a type
/usr/include/openssl/pqueue.h:80: error: 'PQ_64BIT' was not declared in this scope
/usr/include/openssl/pqueue.h:80: error: expected primary-expression before 'void'
/usr/include/openssl/pqueue.h:89: error: 'PQ_64BIT' has not been declared
/usr/include/openssl/dtls1.h:92: error: 'PQ_64BIT' does not name a type
/usr/include/openssl/dtls1.h:94: error: 'PQ_64BIT' does not name a type
The error message says that there's no such file as opensslconf-i386.h, but it is indeed present.
Any idea what's going wrong?
Thanks for you time!
| The C pre-processor is not finding the opensslconf-i386.h file - so you need to find out why that is failing. You've got a warning from the compiler about using an obsolete option (and it recommends a fix) - do it.
OK - you say the file is present: where is it, and what are the permissions on it? How is it included by opensslconf.h? How is that line different from any other OpenSSL headers that are included. What are the '-I' options you are using other than the deprecated '-I-'?
At this stage, I'd say you've got either a faulty installation or an odd-ball command line.
And the question title is ... not obviously related to the question body.
At the operational level, yes, the two interwork for most purposes.
At the compilation level, yes, the two are basically compatible (that which worked in 0.9.7a should work with 0.9.8e).
At the internals and configuration level, there will be small differences; there may be extra ciphers or modes supported by the more recent version, for example.
|
1,631,128 | 1,631,174 | Objective c library with c interface | I have run into a problem... I'm trying to use QTKit in an application that we have at work. The only problem with that is the app is written in C++, not Obj-C. I have looked through Apple's documentation for answers, but I haven't found anything useful.
Basically what I'm looking to do is write a single controller class in Obj-C that has its methods exposed through a C interface to my app. I've written all that code already, but when I try and link it to even a sample C++ app, it finds the Obj-C symbols in the lib and complains about them being there. I thought about hiding the symbols using compiler flags, but I saw in Apple's docs that Obj-C isn't affected by that, since classes and messages are bound by the runtime and not the linker.
Has anyone successfully done this?
Thanks,
Robbie
| You can use QTKit from within your C++ application by using Objective-C++:
Rename the files that access QTKit from .cpp to .mm. This does not change anything in your existing code but you can then use Objective-C from within these files.
|
1,631,288 | 1,631,403 | Better way to determine length of a std::istream? | Is there a better way to determine the length of an std::istream than the following:
std::istream* pcStream = GetSomeStream();
pcStream->seekg(0, ios::end);
unsigned int uiLength = pcStream->tellg();
It just seems really wasteful to have to seek to the end of the stream and then seek back to the original position, especially if the stream might be to a file on some slow media like a CD or DVD.
| The "best" way is to avoid needing the length :)
Not all streams are seekable (For example, imagine an istream on a network socket)
The return type from tellg() is not necessarily numeric (the only requirement is that it can be passed back to seekg() to return to the same position)
Even if it is numeric, it is not necessarily a number of bytes. For example, it could be a "magic" value meaning "at the end"
For fstreams, issues like case and linefeed conversion can screw things up
|
1,631,338 | 1,631,455 | error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) | Please don't confuse with the title as it was already asked by someone but for a different context
The below code in Visual C++ Compiler (VS2008) does not get compiled, instead it throws this exception:
std::ifstream input (fileName);
while (input) {
string s;
input >> s;
std::cout << s << std::endl;
};
But this code compiles fine in cygwin g++. Any thoughts?
| Have you included all of the following headers?
<fstream>
<istream>
<iostream>
<string>
My guess is you forgot <string>.
On a side note: That should be std::cout and std::endl.
|
1,631,375 | 1,632,532 | Is there an OS function to translate a REFIID to a helpful name? | Short of writing a function manually that translates a few known REFIID to names, such as:
if (riid == IID_IUnknown) return "IUnknown";
if (riid == IID_IShellBrowser) return "IShellBrowser";
...
Is there a system call that would return a reasonable debugging string for well-known (or even all) REFIIDs?
| Thanks for the responses. Below is what I came up with based on your feedback - much appreciated!
CString ToString(const GUID & guid)
{
// could use StringFromIID() - but that requires managing an OLE string
CString str;
str.Format(_T("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"),
guid.Data1,
guid.Data2,
guid.Data3,
guid.Data4[0],
guid.Data4[1],
guid.Data4[2],
guid.Data4[3],
guid.Data4[4],
guid.Data4[5],
guid.Data4[6],
guid.Data4[7]);
return str;
}
CString GetNameOf(REFIID riid)
{
CString name(ToString(riid));
try
{
// attempt to lookup the interface name from the registry
RegistryKey::OpenKey(HKEY_CLASSES_ROOT, "Interface", KEY_READ).OpenSubKey("{"+name+"}", KEY_READ).GetDefaultValue(name);
}
catch (...)
{
// use simple string representation if no registry entry found
}
return name;
}
|
1,631,398 | 1,631,418 | c++ class with templates compilation error | I'm not an experienced C++ programmer and I'm having problems compiling. I've got a Heap class that uses a template:
template <class T>
class Heap
{
public:
Heap(const vector<T>& values);
private:
vector<T> d;
// etc.
};
And then in a separate implementation file:
template <class T>
Heap<T>::Heap(const vector<T>& values)
{
d = values;
for (unsigned int i = d.size()-1; i > 0; i--) Heapify(ParentIndex(i));
}
// ... more implementation code ...
And finally a main.cc file:
int main (int argc, char *argv[])
{
vector<int> in;
unsigned int i;
while (cin >> i) in.push_back(i);
Heap<int> h = Heap<int>(in);
return 0;
}
I get these compile errors:
g++ -Wall -I/opt/local/include -c -o main.o main.cc
g++ -Wall -I/opt/local/include -c -o heap.o heap.cc
g++ -Wall -o heap main.o heap.o
Undefined symbols:
"Heap<int>::Heap(std::vector<int, std::allocator<int> > const&)", referenced from:
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [heap] Error 1
Why does this not compile? I think the linker is saying it can't find the constructor, but I know it made the object file.
| Templates need to be defined 100% within the header file. If you have your Heap<T> implementation in a .cc / .cpp file that is the problem. Move all of the code to the header file and it should fix your issue.
|
1,631,425 | 1,631,482 | Actual total size of struct's members | I must write array of struct Data to hard disk:
struct Data {
char cmember;
/* padding bytes */
int imember;
};
AFAIK, most of compilers will add some padding bytes between cmember and imember members of Data, but I want save to file only actual data (without paddings).
I have next code for saving Datas array (in buffer instead of file for simplification):
bool saveData(Data* data, int dataLen, char* targetBuff, int buffLen)
{
int actualLen = sizeof(char) + sizeof(int); // this code force us to know internal
// representation of Data structure
int actualTotalLen = dataLen * actualLen;
if(actualTotalLen > buffLen) {
return false;
}
for(int i = 0; i < dataLen; i++) {
memcpy(targetBuff, &data[i].cmember, sizeof(char));
targetBuff += sizeof(char);
memcpy(targetBuff, &data[i].imember, sizeof(int));
targetBuff += sizeof(int);
}
return true;
}
As you can see, I calculate actual size of Data struct with the code: int actualLen = sizeof(char) + sizeof(int). Is there any alternative to this ? (something like int actualLen = actualSizeof(Data))
P.S. this is synthetic example, but I think you understand idea of my question...
| Just save each member of the struct one at a time. If you overload << to write a variable to a file, you can have
myfile << mystruct.member1 << mystruct.member2;
Then you could even overload << to take an entire struct, and do that inside the struct's operator<<, so in the end you have:
myfile << mystruct;
Resulting in save code that looks like:
myfile << count;
for (int i = 0; i < count; ++i)
myFile << data[i];
IMO all that fiddling about with memory addresses and memcpy is too much of a headache when you could do it this way. This general technique is called serialization - hit google for more, it's a well-developed area.
|
1,631,613 | 1,631,642 | Right click on Button | I see there are BN_CLICKED and BN_DBLCLK notification messages for a button control. but how would i catch a right click message for any button control?
| You can use WM_RBUTTONDOWN, WM_RBUTTONUP, and WM_RBUTTONDBLCLK.
|
1,631,755 | 1,706,634 | Access violation on run function from dll | I have DLL, interface on C++ for work with he. In bcb, msvc it works fine. I want to use Python-scripts to access function in this library.
Generate python-package using Swig.
File setup.py
import distutils
from distutils.core import setup, Extension
setup(name = "DCM",
version = "1.3.2",
ext_modules = [Extension("_dcm", ["dcm.i"], swig_opts=["-c++","-D__stdcall"])],
y_modules = ['dcm'])
file dcm.i
%module dcm
%include <windows.i>
%{
#include <windows.h>
#include "../interface/DcmInterface.h"
#include "../interface/DcmFactory.h"
#include "../interface/DcmEnumerations.h"
%}
%include "../interface/DcmEnumerations.h"
%include "../interface/DcmInterface.h"
%include "../interface/DcmFactory.h"
run these command (python is associated with extension .py)
setup build
setup install
using this DLL
import dcm
f = dcm.Factory() #ok
r = f.getRegistrationMessage() #ok
print "r.GetLength() ", r.GetLength() #ok
r.SetLength(0) #access violation
On last string I get access violation. And I have access violation on every function using input parameters.
DcmInterface.h (interface)
class IRegistrationMessage
{
public:
...
virtual int GetLength() const = 0;
virtual void SetLength(int value) = 0;
...
};
uRegistrationMessage.cpp (implementation in DLL)
class TRegistrationMessage : public IRegistrationMessage
{
public:
...
virtual int GetLength() const
{
return FLength;
}
virtual void SetLength(int Value)
{
FLength = Value;
FLengthExists = true;
}
...
};
Factory
DcmFactory.h (using DLL in client code)
class Factory
{
private:
GetRegistrationMessageFnc GetRegistration;
bool loadLibrary(const char *dllFileName = "dcmDLL.dll" )
{
...
hDLL = LoadLibrary(dllFileName);
if (!hDLL) return false;
...
GetRegistration = (GetRegistrationMessageFnc) GetProcAddress( hDLL, "getRegistration" );
...
}
public:
Factory(const char* dllFileName = "dcmDLL.dll")
{
loadLibrary(dllFileName);
}
IRegistrationMessage* getRegistrationMessage()
{
if(!GetRegistration) return 0;
return GetRegistration();
};
};
| I find bug.
If you using DLL, you must write calling conventions in an explicit form like this:
class IRegistrationMessage
{
public:
...
virtual int _cdecl GetLength() const = 0;
virtual void _cdecl SetLength(int value) = 0;
...
};
I append calling conventions and now all work fine.
|
1,631,940 | 1,631,985 | Looking for Multi-Platform Memory Leak detection programs | Ok I have a school assignment to basically pick 3 memory leak detecting programs and run them on a bunch of c++ programs that the teacher supplies us and see how they compare to each other. These 3 programs have to be multi-platform and this is where I'm stuck. I have only been able to find one called valgrind which works on both MAC OSX and Linux. Does anybody know of a few others? Almost everything I find seems to be for only one OS or I have to pay for it. I don't have to actually run them on each OS they just have to have a version that will run on another OS. Any help would be appreciated.
EDIT: Turns out I completely misunderstood my assignment and that I just have to have like say 1 for linux and 2 for windows. Basically I can't have all 3 for one OS. This makes things a heck of a lot easier.
| Since leak detection programs uses OS specific instrumentation code which injected to your code, there aren't many multi platform solutions, as each OS has it's own memory management features.
I used to work with bounds-checker, AQTime (more modern) but they both run on windows based software.
if your code is pure C++ than you can just port it to MS environment - and check it there.
|
1,632,145 | 1,632,175 | Use of min and max functions in C++ | From C++, are std::min and std::max preferable over fmin and fmax? For comparing two integers, do they provide basically the same functionality?
Do you tend to use one of these sets of functions or do you prefer to write your own (perhaps to improve efficiency, portability, flexibility, etc.)?
Notes:
The C++ Standard Template Library (STL) declares the min and max functions in the standard C++ algorithm header.
The C standard (C99) provides the fmin and fmax function in the standard C math.h header.
Thanks in advance!
| fmin and fmax are specifically for use with floating point numbers (hence the "f"). If you use it for ints, you may suffer performance or precision losses due to conversion, function call overhead, etc. depending on your compiler/platform.
std::min and std::max are template functions (defined in header <algorithm>) which work on any type with a less-than (<) operator, so they can operate on any data type that allows such a comparison. You can also provide your own comparison function if you don't want it to work off <.
This is safer since you have to explicitly convert arguments to match when they have different types. The compiler won't let you accidentally convert a 64-bit int into a 64-bit float, for example. This reason alone should make the templates your default choice. (Credit to Matthieu M & bk1e)
Even when used with floats the template may win in performance. A compiler always has the option of inlining calls to template functions since the source code is part of the compilation unit. Sometimes it's impossible to inline a call to a library function, on the other hand (shared libraries, absence of link-time optimization, etc.).
|
1,632,484 | 1,632,506 | When do I have to use initializer lists for initializing C++ class members? | let's say I have
std::map< std::string, std::string > m_someMap as a private member variable of class A
Two questions: (and the only reason I'm asking is because I came across code like that)
What's the purpose of this line:
A::A() : m_someMap()
Now I know that this is intialization, but do you have to do this like that?
I'm confused.
What's the default value of std::map< std::string, std::string > m_someMap, also C# defines that int, double, etc. is always initialized to defualt 0 and objects are to null (at least in most cases)
So what's the rule in C++?? are object initialized by defualt to null and primitives to garbage?
Of course I'm taking about instance variables.
EDIT:
also, since most people pointed out that this is a style choice and not necessary, what about:
A::A() : m_someMap(), m_someint(0), m_somebool(false)
| m_somemap
You don't have to.
What you get if you omit it: An empty std::map< std::string, std::string >, i.e., a valid instance of that map which has no elements in it.
m_somebool
You have to initialize it to true or false if you want it to have a known value. Booleans are "plain old data types" and they do not have the concept of a constructor. Moreover, the C++ language does not specify default values for non-explicitly-initialized booleans.
What you get if you omit it: a boolean member with an unspecified value. You must not do this and later use its value. Because of that, it is a strongly recommended policy that you initialize all values of this type.
m_someint
You have to initialize it to some integer value if you want it to have a known value. Integers are "plain old data types" and they do not have the concept of a constructor. Moreover, the C++ language does not specify default values for non-explicitly-initialized integers.
What you get if you omit it: an int member with an unspecified value. You must not do this and later use its value. Because of that, it is a strongly recommended policy that you initialize all values of this type.
|
1,632,563 | 1,632,602 | STL algorithms and const_iterators | Today I wrote a small predicate to find matching symbols in a container.
But I'm faced to a problem: I want to use this predicate in a std::find_if call inside a const-method of a class, searching in a container that is a member of this class.
But I just noticed that neither std::find nor std::find_if are able to operate on const_iterators !
I checked on some C++ references and it seems there is no version of std::find or std::find_if that accept/return const_iterators. I just can't understand why, since from what I've seen, there is no way that these algorithms could modify the object referenced by the iterator.
Here is how is documented std::find in the SGI implementation:
Returns the first iterator i in the
range [first, last) such that *i ==
value. Returns last if no such
iterator exists.
| std::find and std::find_if can definitely operate on *::const_iterator for a given container. Are you by chance looking at the signatures of those functions, and misunderstanding them?
template <class InputIterator, class Type>
InputIterator find(InputIterator first, InputIterator last, const Type& val);
Note that InputIterator here is just a name of a template type parameter, and any const_iterator will satisfy the requirements for it.
Or, perhaps, you're confusing const_iterator (i.e. an iterator referencing a const value) with a const iterator (i.e. an iterator which is itself const)?
|
1,632,600 | 1,632,755 | memory layout C++ objects | I am basically wondering how C++ lays out the object in memory. So, I hear that dynamic casts simply adjust the object's pointer in memory with an offset; and reinterpret kind of allows us to do anything with this pointer. I don't really understand this. Details would be appreciated!
| Each class lays out its data members in the order of declaration.
The compiler is allowed to place padding between members to make access efficient (but it is not allowed to re-order).
How dynamic_cast<> works is a compiler implementation detail and not defined by the standard. It will all depend on the ABI used by the compiler.
reinterpret_cast<> works by just changing the type of the object. The only thing that you can guarantee that works is that casting a pointer to a void* and back to the same the pointer to class will give you the same pointer.
|
1,632,645 | 1,632,686 | Does std::sort change the relative order of equal elements? | Does the standard guarantee that order of equal elements will not change (eh, forgot the term for that) by using std::sort or do I need to consider an alternative solution to achieve this goal?
| std::sort is not guaranteed to be stable (the term you were trying to think of). As you'd guess, std::stable_sort is guaranteed to be stable. std::stable_sort also provides a guarantee on worst-case complexity, which std::sort does not. std::sort is typically faster on average though.
|
1,632,695 | 1,632,848 | how to solve this problem with a cast of iterator? | The compiler (VC8) error is:
error C2680: 'std::_Tree<_Traits>::iterator' : invalid target type for dynamic_cast
the source code to simulate the error :
[EDIT]source fixed now
#include <map>
#include <string>
struct tag_data
{
int in;
int on;
std::string sn;
};
class myclass
{
private:
typedef std::map<std::string, tag_data> TypeData;
TypeData MapStorage;
typedef std::map<unsigned long, TypeData::iterator > TypeToThreadIterMapStorage;
TypeToThreadIterMapStorage ThreadIterMapStorage;
public:
bool find( std::string& k)
{
TypeData::const_iterator theData ;
theData = MapStorage.find(k);
//ThreadIterMapStorage [ 0 ] = MapStorage.begin();// this is ok
ThreadIterMapStorage [ 1 ] = dynamic_cast<TypeData::iterator>(theData); // the error occurs here
return theData != MapStorage.end();
}
virtual ~myclass(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
myclass mc;
return 0;
}
| What makes you think that TypeData::iterator and TypeData::const_iterator are even related?
Why not change the type of 'theData' to an iterator?
TypeData::iterator theData = MapStorage.find(k);
|
1,632,715 | 1,632,775 | Jailing user to GUI program in linux | I have a project to create a program, which prevents the user from escaping a GUI program. The program is designed for students to take exams in. The program contains a web browser page.
I have looked around and asked in different places how I should do this, and I have been recommended Qt. I am now having second thoughts about it...
I am using ubuntu 9.04 64 bits.
What do you think is the best solution for jailing users in GUI programs?
| First of all, see this answer.
The best way to prevent users from using anything else is to use full-screen mode and not to start a window manager at all. So just start X and then your app and nothing else.
[EDIT] Some things you must take care of:
Disable the switching to the text console (usually Ctrl-Alt-F1..F10)
Killing the X server (Ctrl-Alt-Backspace)
Magic Keys (Alt-SysRq-...)
As you see, this can become arbitrarily complex. Therefore, I suggest to close some of the holes and let the hackers waste their time on the other ones. If they want to spend their time hacking the computer instead on the test, that's OK.
|
1,632,802 | 1,632,832 | Maintain reference to any object type in C++? | I'm trying to teach myself C++, and one of the traditional "new language" exercises I've always used is to implement some data structure, like a binary tree or a linked list. In Java, this was relatively simple: I could define some class Node that maintained an instance variable Object data, so that someone could store any kind of object in every node of the list or tree. (Later I worked on modifying this using generics; that's not what this question is about.)
I can't find a similar, idiomatic C++ way of storing "any type of object." In C I'd use a void pointer; the same thing works for C++, obviously, but then I run into problems when I construct an instance of std::string and try to store it into the list/tree (something about an invalid cast from std::string& to void*). Is there such a way? Does C++ have an equivalent to Java's Object (or Objective-C's NSObject)?
Bonus question: If it doesn't, and I need to keep using void pointers, what's the "right" way to store a std::string into a void*? I stumbled upon static_cast<char*>(str.c_str()), but that seems kind of verbose for what I'm trying to do. Is there a better way?
| C++ does not have a base object that all objects inherit from, unlike Java. The usual approach for what you want to do would be to use templates. All the containers in the standard C++ library use this approach.
Unlike Java, C++ does not rely on polymorphism/inheritance to implement generic containers. In Java, all objects inherit from Object, and so any class can be inserted into a container that takes an Object. C++ templates, however, are compile time constructs that instruct the compiler to actually generate a different class for each type you use. So, for example, if you have:
template <typename T>
class MyContainer { ... };
You can then create a MyContainer that takes std::string objects, and another MyContainer that takes ints.
MyContainer<std::string> stringContainer;
stringContainer.insert("Blah");
MyContainer<int> intContainer;
intContainer.insert(3342);
|
1,633,774 | 1,673,426 | IHTMLDocument2->documentElement->outerHTML is too slow recreating HTML from DOM, is there a faster way? | I've got an IE BHO plugin that sends out via a COM call the HTML of a page that was loaded in the window.
// Note all error handling removed for readability :)
STDMETHODIMP CPlugin::get_HTML(long lMaxSize, BSTR *pbstrHTML)
{
CComPtr<IDispatch> pDispatch;
MSHTML::IHTMLDocument2Ptr pDocument2 = NULL;
MSHTML::IHTMLDocument3Ptr pDocument3 = NULL;
hr = m_spWebBrowser->get_Document(&pDispatch);
hr = pDispatch->QueryInterface(IID_IHTMLDocument3, (void**)&pDocument3);
MSHTML::IHTMLElementPtr pRoot = pDocument3->documentElement;
wstring strHTML = pRoot->outerHTML;
CComBSTR bstrHTML = strOutput.c_str();
bstrHTML.CopyTo(pbstrHTML);
}
However when it encounters a very large page (e.g. "http://sitemap.zillow.com/uncompressed/ForSale_Hood_MedPri_1.xml"), it takes 3 minutes to create the HTML from the DOM.
Is there a way to access the raw HTML/XML?
When you do a 'view page source' in IE, it pops up almost immediately, so internally IE must be using some API that can do what I want.
Thanks,
Shane.
| It seems that in old versions of MSHTML, outerHTML had a O(n^2) performance. However, in newer versions (IE8) this problem is gone. If you have a choice, use IE8 or later.
Otherwise, using IPersistStream::Save is an option. But CreateStreamOnHGlobal won't help you since its implementation is also O(n^2). You'll have to use a custom IStream for that.
Included is an IStream implementation which was made for this purpose and supports quick writes:
#include <atlbase.h>
#include <atlcom.h>
#include <vector>
// an implementation of a write-only IStream.
// needed because the CreateStreamOnHGlobal implementation doesn't handle
// resizes well (N writes seem to take O(N^2) time)
class MyStream :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<MyStream>,
public IStreamImpl
{
public:
std::vector<char> buf;
BEGIN_COM_MAP(MyStream)
COM_INTERFACE_ENTRY(IStream)
END_COM_MAP()
STDMETHOD(Write) (const void * pv, ULONG cb, ULONG *pcbWritten);
};
/*
Usage:
CComPtr<IStream> stream;
hr = MyStream::CreateInstance(&stream);
// streamObj will be valid as long as IStream smart pointer lives
MyStream *streamObj = (MyStream*)stream.p;
*/
STDMETHODIMP MyStream::Write(const void * pv, ULONG cb, ULONG *pcbWritten)
{
buf.insert(buf.end(), (char*)pv, (char*)pv+cb);
return S_OK;
}
|
1,633,779 | 1,636,551 | Moving development from Windows to Linux | I'm a longtime Visual Studio(from versions 6 to 2008) user that really like the editor and especially the debugger. Now I'm thinking of giving Linux a go, is there a IDE with similar, or better, capabilities out there?
I'm also interested in recommendations for GUI libraries, c++ or c#.
| I moved from windows to linux 9 or so years ago after spending my initial career using Visual Studio.
The move was relatively easy as the build environment was first and foremost based on Makefiles. Up to this point I used scripts to create a visual studio project for the project each time there were changes.
At that time, the others in my team were using emacs. The learning curve is pretty steep when you come from something like VS, but IMHO it has been well worth the time I invested in it.
What sold me on emacs was the integration with gdb. Emacs has a mode specifically for gdb. Once this mode is started you can enable 'gdb-many-windows'. This gives you a view very similar to that of any debuger environment. Also, one of the first things that I did after moving was to setup the VS key shortcuts. So even after all this time, I have the following in my .emacs file:
(global-set-key [f7] 'compile) ;; asks for a command to run eg: make
(global-set-key [f4] 'next-error) ;; show the next error
(global-set-key [S-f4] 'previous-error) ;; show the previous error
(global-set-key [f5] 'gdb) ;; start the debugger
(add-hook 'gud-mode-hook ;; allows changes to debugger mode
'(lambda ()
(define-key (current-local-map)
[f10]
'gud-next) ;; F10 does step over
(define-key (current-local-map)
[f11]
'gud-step) ;; F11 does step into
(define-key (current-local-map)
[\S-f11]
'gud-finish) ;; Shift+F11 finish function
(define-key (current-local-map)
[f5]
'gud-cont) ;; F5 does continue.
(gdb-many-windows t))) ;; Set's up a debugger type view
If you haven't used emacs before, then the first thing you need to know is that you type: Ctrl+X Ctrl+C to exit emacs.
If you do decide to give it a go, after loading it up use Ctrl-H then 't'. This starts the emacs tutorial which will give you the basics.
Of course, if you get stuck, then just review or ask a SO question tagged with emacs. This has become a really could source of information for emacs use. I only found out about gdb-many-windows this April from this question!
|
1,633,959 | 1,633,972 | C++ Sound Processing | I'm looking for a library that could be used to manipulate audio files. Essentially what I would like to do is:
Load an MP3/WAV file
Get a 15 second clip of the file
Overlay another MP3/WAV file ontop of it
Render as a new MP3/WAV file
| You can use any common MP3 codec API to decode the stream, work with it, and save it again. For instance you could use libLAME for this part.
As for mixing, you could either do it yourself (e.g., naively, add two samples and divide by two -- which might not sound too good), or find a proper library for it.
You might also be interested in a related Stack Overflow question at best c audio library linux
|
1,633,979 | 1,634,023 | Concept Checking change in C++? | I'm porting over some code from one project to another within my company and I encountered a generic "sets_intersect" function that won't compile:
template<typename _InputIter1, typename _InputIter2, typename _Compare>
bool sets_intersect(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_Compare __comp)
{
// Standard library concept requirements
// These statements confuse automatic indentation tools.
// concept requirements
__glibcpp_function_requires(_InputIteratorConcept<_InputIter1>)
__glibcpp_function_requires(_InputIteratorConcept<_InputIter2>)
__glibcpp_function_requires(_SameTypeConcept<
typename iterator_traits<_InputIter1>::value_type,
typename iterator_traits<_InputIter2>::value_type>)
__glibcpp_function_requires(_OutputIteratorConcept<_OutputIter,
typename iterator_traits<_InputIter1>::value_type>)
__glibcpp_function_requires(_BinaryPredicateConcept<_Compare,
typename iterator_traits<_InputIter1>::value_type,
typename iterator_traits<_InputIter2>::value_type>)
while (__first1 != __last1 && __first2 != __last2)
if (__comp(*__first1, *__first2))
++__first1;
else if (__comp(*__first2, *__first1))
++__first2;
else {
return true;
}
return false;
}
I'm new to this concept of "concepts" (sorry for the pun), so I did some poking around in the c++ standard library and some googling and I can see that these __glibcpp_function_requires macros were changed to __glibcxx_function_requires. So that fixed my compiler error; however, since this is new to me, I'm curious about what this code is doing for me and I'm having trouble finding any documentation or decyphering the code in the library.
I'm assuming that the point of these macros is that when the compiler expands the templated function these will run some type checking at compile-time to see if the container being used is compatible with this algorithm. In other words, I'm assuming the first call is checking that _InputIter1 conforms to the _InputIteratorConcept. Am I just confused or am I on the right track? Also, why were the names of these macros changed in the c++ standard library?
| You are correct, the first call is checking that _InputIter1 implements "input iterator" concept.
These macros are internal GLIBC implementation details (starting with an underscore or a double underscore), therefore GLIBC implementers are allowed to change them at will. They are not supposed to be used by user's code.
Since "concepts" are no longer the part of C++0x draft, in order to have portable concept checking, you should use some third-party library, like Boost Concept Check Library.
|
1,634,177 | 1,634,191 | default arguments in constructor | Can I use default arguments in a constructor like this maybe
Soldier(int entyID, int hlth = 100, int exp = 10, string nme) : entityID(entyID = globalID++), health(hlth), experience(exp), name(nme = SelectRandomName(exp))
{ }
I want for example exp = 10 by default but be able to override this value if I supply it in the constructor otherwise it should use the default.
How can I do this, I know my approach does not work....
If I supply any value in the initialization list no matter whatever I supply in constructor gets overwritten ofcourse on the other hand whenever I supply a value in constructor then why do I need a default value in the first place as every time I am supplying a value for object initiation...?
Should I use different overloaded constructors or do you people have any other ideas....?
| Default arguments can only be supplied to a continuous range of parameters that extends to the end of the parameter list. Simply speaking, you can supply default arguments to 1, 2, 3, ... N last parameters of a function. You cannot supply default arguments to parameters in the middle of the parameter list, as you are trying to do above. Either rearrange your parameters (put hlth and exp at the end) or supply a default argument for nme as well.
Additionally, you constructor initializer list doesn't seem to make any sense. What was the point of passing entyID and nme from outside, if you override their values anyway in the constructor initializer list?
|
1,634,231 | 1,634,331 | C# Hashtable vs c++ hash_map | I'm comparing the following code in C++ and C# and C# (Mono 2.4) seems to be faster. Is there anything wrong with the C++ code?
#include <map>
#include <string>
#include <iostream>
#include <ext/hash_map>
#include <boost/any.hpp>
int main()
{
//std::map<long, long> m;
// hash_map is a little bit faster
__gnu_cxx::hash_map<long, long> m;
for( long i = 0; i < 1000000; ++i )
{
m[i] = i;
}
}
And C#
using System;
using System.Collections;
public int Main()
{
Hashtable m = new Hashtable();
for( long i = 0; i < 1000000; ++i )
{
m[i] = i;
}
}
C# code is actually twice as fast on the same machine.
$ time ./a.out
real 0m1.028s
user 0m0.986s
sys 0m0.041s
$ time mono test.exe
real 0m0.603s
user 0m0.732s
sys 0m0.090s
| You need to compile the C++ code with compiler optimizations turned on for a fair comparison. Otherwise, you are comparing apples to debug builds — the compiler will not even try to emit fast code.
In GCC this would be the -O3 flag, to start with.
|
1,634,290 | 2,085,006 | C/C++ Resources To Develop Using MetroWerks C/C++ | My friend have real Macintosh IIci, that uses Mac System 7.5.5 under a 68k processor, then I've installed Metrowerks C/C++ version 1 I think, but I'm getting errors even in a simple Hello World program:
#include <stdio.h>
int main(void)
{
printf("Hello, World!");
return 0;
}
I'm getting this error:
·· Link Error : LinkError:hello.c: 'printf' referenced from 'main' is undefined.
All help will be an advance. Thanks.
| You need to add the runtime libraries to the project. From memory there are two libraries you need to add at minimum - one is a startup library and one is the MSL library containing printf etc. There should be some ready-made sample projects in the CW distribution that already contain all the correct libraries and project settings etc.
|
1,634,435 | 1,767,354 | How to check if computer exists or not? | I wrote a little program, which is working like a ping command(i use ICMPSendEcho2), but it gives back a return value, not only a text message. Now I have only one question. How can I programmatically check if a hostname exist or not? I mean if i want to ping computerA, and i don't even have a computerA then it should say what the originally ping says : "Ping request couldn't find host...". This means that there is no computer with that name. But if i ping computerB(when it's turned off) with my ping then it says Host not found. So my question is how can i decide that a computer doesn't exists, or it's only turned off?
Thanks in advance!
kampi
| It's much easier, than i thought! I only have to call the DNSQuery function, and if this will fail with error 9003 (which means DNS name doesn't exists) than i have what i wanted :)
Thanks for help for anyone!
kampi
|
1,634,443 | 1,634,597 | #include header style | I have a question regarding "best-practice" when including headers.
Obviously include guards protect us from having multiple includes in a header or source file, so my question is whether you find it beneficial to #include all of the needed headers in a header or source file, even if one of the headers included already contains one of the other includes. The reasoning for this would be so that the reader could see everything needed for the file, rather than hunting through other headers.
Ex: Assume include guards are used:
// Header titled foo.h
#include "blah.h"
//....
.
// Header titled bar.h that needs blah.h and foo.h
#include "foo.h"
#include "blah.h" // Unnecessary, but tells reader that bar needs blah
Also, if a header is not needed in the header file, but is needed in it's related source file, do you put it in the header or the source?
| In your example, yes, bar.h should #include blah.h. That way if someone modifies foo so that it doesn't need blah, the change won't break bar.
If blah.h is needed in foo.c but not in foo.h, then it should not be #included in foo.h. Many other files may #include foo.h, and more files may #include them. If you #include blah.h in foo.h, then you make all those files needlessly dependent on blah.h. Needless dependencies cause lots of headaches:
If you modify blah.h, all those files must be recompiled.
If you want to isolate one of them (say, to carry it over to another project or build a unit test around it) you have to take blah.h along.
If there's a bug in one of them, you can't rule out blah.h as the cause until you check.
If you are foolish enough to have something like a macro in blah.h... well, never mind, in that case there's no hope for you.
|
1,634,773 | 1,634,845 | Freeing memory allocated in a different DLL | I have an EXE file using a DLL file which is using another DLL file. This situation has arisen:
In DLL file 1:
class abc
{
static bool FindSubFolders(const std::string & sFolderToCheck,
std::vector< std::string > & vecSubFoldersFound);
}
In DLL file 2:
void aFunction()
{
std::vector<std::string> folders;
std::string sLocation;
...
abc::FindSubFolders(sLocation, folders)
}
In release mode, everything works fine. But in debug mode, I come up with an assertion failure in the destructor of one of the std::strings in the folders vector (when folders goes out of scope at the end of aFunction):
dbgheap.c : line 1274
/*
* If this ASSERT fails, a bad pointer has been passed in. It may be
* totally bogus, or it may have been allocated from another heap.
* The pointer MUST come from the 'local' heap.
*/
_ASSERTE(_CrtIsValidHeapPointer(pUserData));
I assume this is because the memory has been allocated on DLL file 1's heap, but is being freed in DLL file 2.
The comment in dbgheap.c seems pretty insistent that this is a problem.
Why is this such a problem, when it seems to work fine if I just ignore it? Is there a non-assertion-failing way of doing this?
| As sean has already said, the release build simply ignores that delete statement, so the best you can hope for is a memory leak.
If you have control over how both DLL files are compiled, make sure to use the Multi-threaded Debug DLL (/MDd) or Multi-threaded DLL (/MD) settings for the runtime library. That way, both DLL files will use the same runtime system and share the same heap.
The downside is that you need to install the runtime system together with your application (Microsoft offers an installer for that). It will work fine on your development machine since Visual Studio installs that runtime system too, but on a freshly installed machine it will report missing DLL files.
|
1,634,804 | 1,634,819 | C++, Accept lowercase and uppercase letters in a variable | I want to allow the user to use lowercase or uppercase letters giving the value to the char type variable... Any help??
| Err, do you mean something like (where getAChar() is whatever method you're using to get the character):
int ch = getAChar();
while (!isalpha (ch))
ch = getAChar();
Alternatively, if you want to check that a user enters only alphas. You can get a string with:
cin >> myString;
Checking for alphas is as simple as:
char *cstr = myString.c_str();
for (int i = 0; i < myString.length(); i++)
if (!isalpha (*cstr++))
return false;
return true;
|
1,634,813 | 1,634,882 | A Good Way to Store C++ CLI Arguments? (W/O using libraries) | So, I'm writting a CLI application in C++ which will accept a bunch of arguments.
The syntax is pretty typical, -tag arg1 arg2 -tag2 arg1 ...
Right now, I take the char** argv and parse them into an
std::map< std::string, std::list<**std::string** > > >
The key is the tag, and the list holds each token behind that tag but before the next one. I don't want to store my args as just std::strings; but I need to make it more interactive.
By interactive, I mean when a user types './myprog -help' a list of all available commands comes up with descriptions.
Currently, my class to facilitate this is:
class Argument
{
public:
Argument(std::string flag, std::string desc);
std::string getFlag();
std::string getDesc();
std:;list<std::string> > getArgs();
void setArgs(std::list<std::string> > args);
bool validSyntax()=0;
std::string getSyntaxErrorDesc()=0;
};
The std::map structure is in a class ProgramCommands which goes about handling the these Arguments.
Now that the problem description is over, my 4 questions are:
How do I give the rest of the program access to the data in ProgramCommands?
I Don't want to make a singleton, at all; and I'd prefer to not have to pass ProgramCommands as an arg to almost every function in the program.
Do you have better ideas about storing how I'm doing this?
How best can I add arguments to the program, without hardcoding them into the ProgramCommands, or main?
std::string only allows for 1 line descriptions, does anyone have an elegant solution to this besides using a list of strings or boost?
EDIT
I don't really want to use libraries because this is a school project (sniffing & interpreting packets). I could, if I wanted to, but I'd rather not.
| Your choices on storing the command line arguments are either: Make them a global or pass them around to the functions that need them. Which way is best depends on the sorts of options you have.
If MANY places in your program need the options (for instance a 'verbose' option), then I'd just make the structure a global and get on with my life. It doesn't need to be a singleton (you'll still only have one of them, but that's OK).
If you only need the options at startup time (i.e. # of threads to start initially or port # to connect on), then you can keep the parsing local to 'main' and just pass the parameters needed to the appropriate functions.
I tend to just parse options with the venerable getopt library (yes, that's a leftover from C - and it works just fine) and I stuff the option info (flags, values) into a global structure or a series of global variables. I give usage instructions by having a function 'print_usage' that just prints out the basic usage info as a single block of text. I find it works, it's quick, it's simple, and it gets the job done.
|
1,634,856 | 1,634,898 | fixing memory leaks when you're returning the leaked memory? | How do you fix a memory leak where you're returning from the function the leak itself?
For example, I make a char* returnMe = new char[24324]; returnMe is what ends up getting returned from the function. How do you account for this memory leak? How do you destroy it once it's been returned? I have some memory management rules in place that throw runtime errors on memory leaks to stop this, so I can't really ignore it.
Orrr am I a fool and this isn't a leak, implying that the leak is elsewhere?
| It's not a leak if you return it (well, it's not your leak).
You need to think in terms of resource ownership. If you return an allocated buffer from your function, the caller of the function is now responsible for it. The API should make it clear that it needs to be freed when they're finished with it.
Whether they free it themselves or pass it to another of your functions to have it freed (encapsulation in case more needs to be done than just freeing the memory) is another issue for the API.
|
1,634,860 | 1,635,455 | Self Organizing Map (SOM) Implementation | I'm looking for a C, C++ or Java based SOM implementation with licensing applicable for commercial use (non-zero cost is okay).
So far I'm aware that there exists SOM_PAK (from Kohonen), but the licensing forbids commercial use.
Is anyone aware of alternative implementations?
| How about this, it's BSD licensed.
http://knnl.sourceforge.net/
|
1,634,934 | 1,636,197 | Would C# benefit from distinctions between kinds of enumerators, like C++ iterators? | I have been thinking about the IEnumerator.Reset() method. I read in the MSDN documentation that it only there for COM interop. As a C++ programmer it looks to me like a IEnumerator which supports Reset is what I would call a forward iterator, while an IEnumerator which does not support Reset is really an input iterator.
So part one of my question is, is this understanding correct?
The second part of my question is, would it be of any benefit in C# if there was a distinction made between input iterators and forward iterators (or "enumerators" if you prefer)? Would it not help eliminate some confusion among programmers, like the one found in this SO question about cloning iterators?
EDIT: Clarification on forward and input iterators. An input iterator only guarantees that you can enumerate the members of a collection (or from a generator function or an input stream) only once. This is exactly how IEnumerator works in C#. Whether or not you can enumerate a second time, is determined by whether or not Reset is supported. A forward iterator, does not have this restriction. You can enumerate over the members as often as you want.
Some C# programmers don't underestand why an IEnumerator cannot be reliably used in a multipass algorithm. Consider the following case:
void PrintContents(IEnumerator<int> xs)
{
while (iter.MoveNext())
Console.WriteLine(iter.Current);
iter.Reset();
while (iter.MoveNext())
Console.WriteLine(iter.Current);
}
If we call PrintContents in this context, no problem:
List<int> ys = new List<int>() { 1, 2, 3 }
PrintContents(ys.GetEnumerator());
However look at the following:
IEnumerable<int> GenerateInts() {
System.Random rnd = new System.Random();
for (int i=0; i < 10; ++i)
yield return Rnd.Next();
}
PrintContents(GenerateInts());
If the IEnumerator supported Reset, in other words supported multi-pass algorithms, then each time you iterated over the collection it would be different. This would be undesirable, because it would be surprising behavior. This example is a bit faked, but it does occur in the real world (e.g. reading from file streams).
| Interesting question. My take is that of course C# would benefit. However, it wouldn't be easy to add.
The distinction exists in C++ because of its much more flexible type system. In C#, you don't have a robust generic way to clone objects, which is necessary to represent forward iterators (to support multi-pass iteration). And of course, for this to be really useful, you'd also need to support bidirectional and random-access iterators/enumerators. And to get them all working smoothly, you really need some form of duck-typing, like C++ templates have.
Ultimately, the scopes of the two concepts are different.
In C++, iterators are supposed to represent everything you need to know about a range of values. Given a pair of iterators, I don't need the original container. I can sort, I can search, I can manipulate and copy elements as much as I like. The original container is out of the picture.
In C#, enumerators are not meant to do quite as much. Ultimately, they're just designed to let you run through the sequence in a linear manner.
As for Reset(), it is widely accepted that it was a mistake to add it in the first place. If it had worked, and been implemented correctly, then yes, you could say your enumerator was analogous to forward iterators, but in general, it's best to ignore it as a mistake. And then all enumerators are similar only to input iterators.
Unfortunately.
|
1,635,000 | 1,635,064 | Is it possible to wrap boost sockets with Pimpl? | in a project we want to wrap the Boost Asio socket in a way, that the using class or the wrapping .h does not have to include the boost headers.
We usually use pointers and forward declarations for wrapped classes.
Foward declaration:
namespace boost
{
namespace asio
{
namespace ip
{
class udp;
}
}
}
And then declaring the socket:
scoped_ptr<boost::asio::ip::udp::socket> socket_;
scoped_ptr<boost::asio::ip::udp::endpoint> receiveEp_;
(If you don't know scoped_ptr, ignore it, the problem is equal with a standard * pointer.)
But this gives a compiler error:
error C2027: use of undefined type 'boost::asio::ip::udp'
I understand this is because udp is actually not a namespace, but a class itself. We only want to use the inner class though, any ideas?
| With inner types your only option is wrapping everything. Hide scoped pointers themselves inside a forward declared class. Users would see only your API and pass around your own objects instead of boost objects.
In your example though scoped_ptr look like private member declarations, you can get away with simple:
// header
class SomeClass
{
public:
SomeClass();
// stuff
private:
scoped_ptr<class pimpl_bla> _m;
};
// source
class pimpl_bla
{
public:
scoped_ptr<boost::asio::ip::udp::socket> socket_;
};
SomeClass::SomeClass()
:_m(new pimpl_bla)
{
}
|
1,635,130 | 1,635,140 | error when I call strcmp Invalid conversion from 'int' to 'const char*' | I'm using strcmp to compare character arrays in c++, but I get the following error for every occurrence of strcmp: error: invalid conversion from 'int' to 'const char*' followed by: error: initializing argument 2 of 'int strcmp(const char*, const char*)'
I've include string, string.h, and stdio.h and here is my code, thanks to all who reply.
Also, is there a better way to check the buffer other than a bunch of if statements?
int main(int argc, char* argv[])
{
unsigned count = 0;
bool terminate = false;
char buffer[128];
do {
// Print prompt and get input
count++;
print_prompt(count);
cin.getline(buffer, 128);
// check if input was greater than 128, then check for built-in commands
// and finally execute command
if (cin.fail()) {
cerr << "Error: Commands must be no more than 128 characters!" << endl;
}
else if ( strcmp(buffer, 'hist') == 0 ) {
print_Hist();
}
else if ( strcmp(buffer, 'curPid') == 0 ) {
// get curPid
}
else if ( strncmp(buffer, 'cd ', 3) == 0 ) {
// change directory
}
else if ( strcmp(buffer, 'quit') == 0 ) {
terminate = true;
}
else {
//run external command
}
} while(!terminate);
return 0;
}
| Your comparison string are incorrect. They should be of the form "hist", not 'hist'.
In C++, 'hist' is simply a character literal (as stated in section 2.14.3 of the C++0x draft (n2914) standard), my emphasis on the last paragraph:
A character literal is one or more characters enclosed in single quotes, as in ’x’, optionally preceded by one of the letters u, U, or L, as in u’y’, U’z’, or L’x’, respectively.
A character literal that does not begin with u, U, or L is an ordinary character literal, also referred to as a narrow-character literal.
An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set.
An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.
As to there being a better way, it depends on what you mean by better :-)
One possibility is to set up a functon table which is basically an array of structs, each containing a word and a function pointer.
Then you simply extract the word from your string and do a lookup in that array, calling the function if you find a match. The following C program shows how to use function tables. As to whether that's a better solution, I'll leave it up to you (it's a moderately advanced technique) - you may be better off sticking with what you understand.
#include <stdio.h>
typedef struct { // This type has the word and function pointer
char *word; // to call for that word. Major limitation is
void (*fn)(void); // that all functions must have the same
} tCmd; // signature.
// These are the utility functions and the function table itself.
void hello (void) { printf ("Hi there\n"); }
void goodbye (void) { printf ("Bye for now\n"); }
tCmd cmd[] = {{"hello",&hello},{"goodbye",&goodbye}};
// Demo program, showing how it's done.
int main (int argc, char *argv[]) {
int i, j;
// Process each argument.
for (i = 1; i < argc; i++) {
//Check against each word in function table.
for (j = 0; j < sizeof(cmd)/sizeof(*cmd); j++) {
// If found, execute function and break from inner loop.
if (strcmp (argv[i],cmd[j].word) == 0) {
(cmd[j].fn)();
break;
}
}
// Check to make sure we broke out of loop, otherwise not a avlid word.
if (j == sizeof(cmd)/sizeof(*cmd)) {
printf ("Bad word: '%s'\n", argv[i]);
}
}
return 0;
}
When run with:
pax> ./qq.exe hello goodbye hello hello goodbye hello bork
you get the output:
Hi there
Bye for now
Hi there
Hi there
Bye for now
Hi there
Bad word: 'bork'
|
1,635,583 | 1,635,600 | Is C++ completely object oriented language? | I read about small talk being completely object oriented.. is C++ also completely object oriented? if no.. then why so??
| No, it isn't. You can write a valid, well-coded, excellently-styled C++ program without using an object even once.
C++ supports object-oriented programming, but OO is not intrinsic to the language. In fact, the main function isn't a member of an object.
In smalltalk or Java, you can't tie your shoes (or write "Hello, world") without at least one class.
(Of course, one can argue about Java being a completely object-oriented language too, because its primitives (say, int) are not objects.)
|
1,635,609 | 1,635,643 | Set Visual Studio (conditional) breakpoint on local variable value | I'm trying to debug a method which among other things, adds items to a list which is local to the method.
However, every so often the list size gets set to zero "midstream". I would like to set the debugger to break when the list size becomes zero, but I don't know how to, and would appreciate any pointers on how to do this.
Thanks.
| Why not use conditional breakpoints?
http://blogs.msdn.com/saraford/archive/2008/06/17/did-you-know-you-can-set-conditional-breakpoints-239.aspx
|
1,635,664 | 1,635,741 | C++ STL:map search by iterator to another map | I'm trying to jump through some hoops to organize data in a special way. I'm including a simplified piece of code that demonstrates my pain.
I can't use boost.
I'm using the latest version of g++ in cygwin.
#include <iostream>
#include <map>
using namespace std;
int main () {
map< int,int > genmap;
map< int,int >::iterator genmapit;
map< map<int,int>::iterator,int > itermap;
// insert something into genmap
genmap.insert (make_pair(1,500) );
// find and return iterator.
genmapit=genmap.find(1);
// insert the iterator/int into itermap. Dies on each of the following 3 versions of this line.
//itermap[genmapit] = 600; // crash
//itermap.insert ( pair< map<int,int>::iterator,int >(genmapit,600) ); // crash
itermap.insert ( make_pair(genmapit,600) ); // crash
return 0;
}
So as you can see, I have 1 simple map, an iterator to that map and another map that has the first argument as an iterator to the first map.
It's clear from this:
Why can't I put an iterator in map?
That I can have an iterator as the second argument. However, the way shown above provides this:
$ make
g++ -c -o main.o main.cpp
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h: In member fun
ction `bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp =
std::_Rb_tree_iterator<std::pair<const int, int> >]':
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_tree.h:871: instantiate
d from `std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _All
oc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::i
nsert_unique(const _Val&) [with _Key = std::_Rb_tree_iterator<std::pair<const in
t, int> >, _Val = std::pair<const std::_Rb_tree_iterator<std::pair<const int, in
t> >, int>, _KeyOfValue = std::_Select1st<std::pair<const std::_Rb_tree_iterator
<std::pair<const int, int> >, int> >, _Compare = std::less<std::_Rb_tree_iterato
r<std::pair<const int, int> > >, _Alloc = std::allocator<std::pair<const std::_R
b_tree_iterator<std::pair<const int, int> >, int> >]'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_map.h:360: instantiated
from `std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_
Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator, bool> std::
map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [wit
h _Key = std::_Rb_tree_iterator<std::pair<const int, int> >, _Tp = int, _Compare
= std::less<std::_Rb_tree_iterator<std::pair<const int, int> > >, _Alloc = std:
:allocator<std::pair<const std::_Rb_tree_iterator<std::pair<const int, int> >, i
nt> >]'
main.cpp:23: instantiated from here
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h:227: error: no
match for 'operator<' in '__x < __y'
make: *** [main.o] Error 1
"instantiated from here" tells me nothing and a web search gives me no info on this.
Does STL:map simply not allow for this? I can recode my app to work around this but it will be very inefficient and I would like to get this working. Is there another kind of pointer I can make for a map element I could use?
Thanks for your time.
| You can't do this because std::map iterators are not random access iterators so aren't comparable with <.
Instead, you could use pointers to the value_type in the first map as a map key.
|
1,635,869 | 1,635,884 | Using free inside the destructor of an object freed with delete | I have an object that I'm freeing with delete, and it has a char* that's being freed with free in its destructor. The reason I'm using free is because I used strdup and malloc in creating the char pointers. The reason I'm using malloc is because I used strdup to begin with in most code paths. Would this scenario cause memory corruption?
| No, if you match calls properly i.e. free() for memory allocated with malloc() and delete for memory allocated with new, it will work fine.
|
1,635,897 | 1,635,928 | C++ object and C style cast question | I have the following code compiled by gcc:
#include <iostream>
using namespace std;
class Buffer {
public:
operator char *() { cout << "operator const * called" << endl; return buff; }
private:
char buff[1024];
};
int main(int, char**) {
Buffer b;
(char *)b; // Buffer::operator char * is called here
return 0;
}
What I see is that Buffer::operator char * is called on line:
(char *)b;
Why C style cast calls Buffer::operator char * is called here?
I though that
static_cast<char *>(b);
should be used in order to invoke explicitly Buffer::operator char *.
| If you had done (char *)(&b) it would have been C style cast and operator char* will not be called. Here you are trying to cast an object into char*. Since there is no automatic conversion compiler looks for operator char* provided by you. If you had not provided it, you'll get a compiler error saying that Buffer can not be converted into char*
|
1,636,191 | 2,493,224 | How can including GDB debugging symbols 'break packages'? | When I am building packages on Gentoo. I get this warning that '-ggdb3' flag can 'break packages.
I have yet to find an instance of when that is true. Although I once found some code which broke under different optimisation settings, that's different from including debugging symbols.
Could some provide an example of code which would compile without debugging symbols and not compile (or go wrong in some other way at runtime) with them?
| In the "old days" I built an entire Linux from Scratch system leaving debugging on for every single binary. Sure, the install was significantly larger, memory usage was less than ideal, but I never had any problems at all, either in compilation or subsequent execution.
It is hard to prove a negative, and one can't through anecdote, but a year of running this as a second desktop/toy server would lead me to conclude that it is really not a problem.
I think the flag you are getting is the standard warning that a package will give in Gentoo if you set USE flags with which it was not tested, or with which it is not really meant to be installed. As long as you know what the flag is---and in this case, you seem to---and you are not placing it in any "mission critical" setting (i.e., you will get blamed if something goes wrong) seems safe to ignore those warnings.
|
1,636,286 | 1,636,428 | debug vs. release dll size | Why in cpp a dll in debug mode is X10 bigger than release while in .Net they are almost the same size?
| To Debug a C++ program alot of extra information has to be kept in the DLL so the debugger can find out about the code at run-time. C++ has no run-time requirement to be able to inspect the code unlike C# which allows for extensive run-time inspection also known as reflection. This information is there in C# whether using debug or release mode.
Additionally C++ is usually compiled directly to machine code in release mode the objective of the compiler is to optimized the code as much as possible, eg. remove any and all extraneous information and code. In C# the compiler compiles to a pseudo code which is just in time compiled as required. This code keeps much of what is required for debugging regardless if it is release or debug that you are building. So much so that it is possible to write a de-compiler to give you the code back from a run-time assembly.
|
1,636,314 | 1,648,095 | Stay in directory with popen | I want to make some C++ program and I'm using function popen here to send commands to command line in Unix. It works fine, but when I call cd directory, the directory doesn't change. I thing that it's same when I try to run cd directory in some script, after finishing script directory path change back. So, scripts I must run like . ./script.sh not ./sript.sh, but how to do that with popen function? I have tried to add ". " before first argument of popen, but running ". ls" makes error.
Code:
cout << "@ Command from " << session->target().full() << ": " << message.body() << endl;
//cout << "Prisla zprava" << endl;
//m_session->send( "Hello World", "No Subject" );
//system( message.body().c_str() );
//if ( message.body() == "" )
FILE* outp;
char buffer[100];
string outps = "";
outp = popen( message.body().c_str(), "r" );
while ( !feof(outp) )
{
fgets( buffer, 100, outp );
outps = outps + buffer;
}
pclose(outp);
cout << "& Output from command: " << outps << endl;
m_session->send( outps.c_str(), "Output" );
In message.body(); is string which I want to run (I'm receiving this from XMPP). When the string is for example "ls", it returns string with list of files in actual directory. But when the message is "cd directory", nothing happens, like trying to change directory in scripts.
| Typically, the way the popen() command executes the command is via the shell. So, it opens a pipe, and forks. The child does some plumbing (connecting the pipe to the standard input or standard output - depending on the flag) and then executes
execl("/bin/sh", "/bin/sh", "-c", "what you said", (char *)0);
So, how it all behaves is going to depend on your key environment variables - notably PATH.
If you want to execute a script in the current directory, then one of these options:
outp = popen("./script.sh", "r");
outp = popen("sh -x ./script.sh", "r");
outp = popen("sh -c './script.sh arg1 arg2'", "r");
If you want to execute the 'ls' command:
outp = popen("/bin/ls /the/directory", "r");
And if you want to change directory before running something:
outp = popen("cd /somewhere/else; ./script", "r");
And so on...
If you want to change the directory of the program that is using popen(), then you need to use the 'chdir()' system call (or possibly fchdir()). If you think you might want to get back to where you started, use:
int fd = open(".", O_RDONLY);
chdir("/some/where/else");
...do stuff in new directory
fchdir(fd);
(Clearly, you need some error checking in that lot.)
|
1,636,447 | 1,636,560 | Load an extern C-library into an existing C++-Project (f.e. ffmpeg/libavcodec - step by step) | I really have big problems with importing an extern C-Library to my existing C++-Project. I want to import libavcodec from the FFmpeg-Project, so I downloaded the latest source-code-release.
What do I have to do now? Do I have to compile FFmpeg first or can I import it just like that? A really simple step-by-step manual would be awesome!
(I found tutorials how to use libavcodec when it's imported, so this is not necessary... I didn't found some to import it)
| To include a source code library into your existing project you have a number of options:
Compile to a static library
Compile to a dynamic library
Compile to object files
So, yes, you do need to compile their source code, and you need to change your toolchain to include the results into your program.
|
1,636,578 | 1,636,591 | iterator validity ,after erase() call in std::set | Do erase call in std::set invalidate iterator ? As i have done below 5th from last line..?
if yes what is better way to erase all elements from set
class classA
{
public:
classA(){};
~classA(){};
};
struct structB
{
};
typedef std::set <classA*, structB> SETTYPE;
typedef std::map <int, SETTYPE>MAPTYPE;
int __cdecl wmain (int argc, wchar_t* pArgs[])
{
MAPTYPE mapObj;
/*
...
.. Some Operation Here
...
*/
for (MAPTYPE::iterator itr1=mapObj.begin(); itr1!=mapObj.end(); itr1++)
{
SETTYPE li=(*itr1).second;
for (SETTYPE::iterator itr2=li.begin();itr2!=li.end();itr2++)
{
classA *lt=(classA*)(*itr2);
li.erase(itr2);
delete lt; // Does it invalidate Iterator ?
}
}
}
| Since you are just apparently deleting every element of the set, you could just do:
for (SETTYPE::iterator itr2=li.begin();itr2!=li.end();itr2++)
{
classA *lt=(classA*)(*itr2);
delete lt;
}
li.clear(); // clear the elements
|
1,636,600 | 1,636,777 | How to learn C++ for the purposes of debugging | Some background: My job involves maintaining a large multi-threaded multi-process C++ / C# application, and so I'm often tasked with understanding access violations, memory leaks, heap curruption issues and the like.
I quite enjoy this, and I've amassed quite a good understanding of various low level concepts, but the trouble is that I don't program in C++, and aside for the purposes of maintenance I don't really intend to.
What I mean by that is that if I ever need to develop something then at the company I work at the best choice is C# (more developers, other apps also in C# means better interops), so its not that I don't program in C++, it's just that whenever I do program in C++ it will be purely for the purpose of learning C++, and so I want to get the most out of it.
My view is that "Teach yourself C++" books and the like aren't very suitable as they focus too much on getting things done - there are usually many ways of doing things and so they tend to pick one method, so when I'm presented with some code that does things a different way I'm stuffed (e.g. a book teaches MFC, I then get presented with some ATL code and the book hasn't even taught me what ATL and MFC are, let alone how to recognise that what I'm looking at is different!)
I'm really looking for teach yourself C++, with the emphasis on understanding other peoples code.
| IMHO C++ in particular is a language that you cannot learn by reading a "teach yourself" book, you really need to have several sources and one of these is actually to look at other people's code.
I would recommend reading Effective C++ and More Effective C++ by Scott Meyers to learn some of the pitfalls when programming in C++, it is a good way to learn especially when you are looking at people's code. Another site than can help is gotw as well, some excellent information is there as well.
|
1,636,753 | 1,636,764 | Silly compile error using lists / iterators (C++) | The following does not compile, and I cannot for the life of me see why!
#include <list>
using namespace std;
list<char> myList;
list<int>::iterator it;
it = myList.begin();
The error:
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::list<_Ty>::_Iterator<_Secure_validation>' (or there is no acceptable conversion)
| This happens because list<char> and list<int> are two different classes.
So their iterators are different types too.
If you look at std::list class code you will see something like:
typedef _Iterator<_SECURE_VALIDATION_DEFAULT> iterator;
or
typedef _Iterator<bla_bla_bla> iterator;
That means new type is defined by each distinct class list. In other words each list defines its own iterator type.
Change your code to this:
list<char>::iterator it;
|
1,636,760 | 1,636,780 | Dynamic Memory Reallocation using realloc | I am learning C++. I am trying to learn this dynamic memory allocation. In the below code I am trying to allocate memory using malloc and realloc.
int main (void) {
char *g = (char*) malloc (sizeof(char) * 2);
g = "ab";
g = (char*) realloc (g, sizeof(char) * 200);
strcpy (g, "cdefg");
cout << g << endl;
return 0;
}
I get segmentation fault error when I execute this code.
I've seen other SO threads recommending to use either vector or new instead of using above approach. Since, I am trying to learn this approach, so these answers does not applies to my question.
I've encountered a scenario where this approach will be well fitted, for example, If I am reading a raw text file using ifstream.read function and reading, let's say 1024bytes of it. Now, If I want to make sure I am not reading a word which is broken due to 1024bytes size I have to read further from that position using ifstream.get to reach until a space character is found. In this scenario, I need to adjust the buffer (which is of 1024) slightly more. My intention is to use realloc here to assign some more memory to it.
Please feel free to correct me if I am wrong anywhere.
| There are many problems with your code. First of all, you should not use malloc and friends if you are programming in C++.
char *g = (char*) malloc (sizeof(char) * 2);
g = "ab";
Ooops. You just lost the 2 bytes of memory returned by the malloc call because now g points to the possibly read only location where "ab" is stored.
g = (char*) realloc (g, sizeof(char) * 200);
realloc can only be called on a pointer returned by an earlier malloc.
Even if you had passed a valid pointer to realloc, realloc may return NULL if the re-allocation fails. In that case, the memory previously allocated remains allocated but you would overwrite the only variable pointing to that memory making it impossible to free the earlier allocation. See Having dynamically allocated an array, can I change its size? in the C FAQ list.
Also, note that "ab" requires three bytes of storage, not two. Finally, sizeof(char) is always and everywhere 1, so there is no need to use sizeof(char) in your malloc calls.
A correct C version of your program would look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
char *tmp;
char *g = malloc(3);
if ( !g ) {
return EXIT_FAILURE;
}
strcpy(g, "ab");
tmp = realloc (g, 200);
if ( !tmp ) {
return EXIT_FAILURE;
}
g = tmp;
strcpy (g, "cdefg");
puts(g);
return 0;
}
In the C++ version, you would use string rather than plan old C style character arrays.
See my answer to another question for an example of how to reallocate a buffer to read complete lines for the second part of your question.
However, note that code is also C and I am sure there are better ways of doing what you want in C++. I just do not know enough of the C++ standard library to give you a correct solution in C++.
|
1,636,950 | 1,636,972 | Detect system architecture (x86/x64) while running | Is it possible to detect the system/processor architecture while the program is running (under windows and under linux) in c++?
| On Windows, you may use __cpuid. On Linux, you can open("/proc/cpuinfo") and look through it.
Here is an example on Windows, based on the example in the MSDN page:
#include <intrin.h>
bool cpuSupports64()
{
int CPUInfo[4];
__cpuid(CPUInfo, 0);
return (CPUInfo[3] & 0x20000000) || false;
}
|
1,636,987 | 1,637,058 | Compiling GTK+ Application with G++ compiler | I am writing an application in C++ with using GTK+ (not gtkmm) so I need to compile using g++ compiler. Is it possible to compile GTK+ applications with the g++ compiler? Are GTK+ and libraries compatible with g++ compiler?
I am trying to embed GTK+ functions call in a class like follows:
#include <gtk/gtk.h>
class LoginWindow
{
public:
LoginWindow();
void on_window_destroy( GtkObject *object, gpointer user_data);
private:
GtkBuilder *builder;
GtkWidget *window;
};
LoginWindow::LoginWindow()
{
builder = gtk_builder_new ();
gtk_builder_add_from_file (builder, "login_window.glade", NULL);
window = GTK_WIDGET (gtk_builder_get_object (builder, "login_window"));
gtk_builder_connect_signals (builder, NULL);
g_signal_connect( GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(on_window_destroy), NULL );
g_object_unref (G_OBJECT (builder));
gtk_widget_show (window);
}
void LoginWindow::on_window_destroy (GtkObject *object, gpointer user_data)
{
gtk_main_quit ();
}
int main (int argc, char *argv[])
{
gtk_init (&argc, &argv);
LoginWindow loginWindow;
gtk_main ();
return 0;
}
Am I doing it right? I am getting compile error on line:
g_signal_connect( GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(on_window_destroy), NULL );
login_window.cpp: In constructor "LoginWindow::LoginWindow()":
login_window.cpp:27: error: invalid use of member (did you forget the "&" ?)
What is the right way of doing it?
| Gtk+ is a C-based library, so you can't give it class-member-functions as callbacks. Either define C-style functions as callbacks i.e.
extern "C"
void on_window_destroy( GtkObject *object, gpointer user_data)
{
// do yer stuff.. keep in mind, there's no this-pointer here, it's not
// associated with an object
}
outside of any class declarations. When registering the signal, you might want to add the LoginWindow-object itself as user_data and simply cast it when entering the method and
forward the call, like so
extern "C"
void on_window_destroy( GtkObject *object, gpointer user_data)
{
static_cast<LoginWindow*>(user_data)->on_window_destroy();
}
If you want to do it c++ style though, have a look at gtkmm, which is the c++ wrapper for Gtk+, and it'll give you a lot more OOP for your buck. It's a little more messy to work with signals/callbacks in gtkmm, but it's type safe and will save you a lot of headaches in the end.
|
1,637,332 | 1,637,367 | static const vs #define | Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?
What are advantages/disadvantages for each method?
| Personally, I loathe the preprocessor, so I'd always go with const.
The main advantage to a #define is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.
Advantages of "const"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.
I don't know exactly what you are getting at with the "static" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static. For example
namespace {
unsigned const seconds_per_minute = 60;
};
int main (int argc; char *argv[]) {
...
}
|
1,637,587 | 1,639,047 | C++ libcurl console progress bar | I would like a progress bar to appear in the console window while a file is being downloaded. My code is this: Download file using libcurl in C/C++.
How to have a progress bar in libcurl?
| Your meter.
#include <math.h>
int progress_func(void* ptr, double TotalToDownload, double NowDownloaded,
double TotalToUpload, double NowUploaded)
{
// ensure that the file to be downloaded is not empty
// because that would cause a division by zero error later on
if (TotalToDownload <= 0.0)) {
return 0;
}
// how wide you want the progress meter to be
int totaldotz=40;
double fractiondownloaded = NowDownloaded / TotalToDownload;
// part of the progressmeter that's already "full"
int dotz = (int) round(fractiondownloaded * totaldotz);
// create the "meter"
int ii=0;
printf("%3.0f%% [",fractiondownloaded*100);
// part that's full already
for ( ; ii < dotz;ii++) {
printf("=");
}
// remaining part (spaces)
for ( ; ii < totaldotz;ii++) {
printf(" ");
}
// and back to line begin - do not forget the fflush to avoid output buffering problems!
printf("]\r");
fflush(stdout);
// if you don't return 0, the transfer will be aborted - see the documentation
return 0;
}
|
1,637,671 | 3,117,177 | Standard notifications or alert styles in Symbian (Qt/S60)? | I'm building a an application using Qt on the Symbian/S60 platform and I was wondering if there was a standard notification window that I could use to pass messages to users. Using other platforms as examples, I'm looking for something equivalent to Javascript's alert() method or Cocoa's NSRunAlert* methods.
If there is not a native Symbian/S60 equivalent, is there something in the Qt space that I should be looking at? QMessageBox didn't seem to work as I might expect.
| You can use RNotifier class from any Symbian code (and from Qt too). This class can show notifications even from window-less programs, like Symbian servers. It is simple to use:
RNotifier notifier;
User::LeaveIfError(notifier.Connect());
TInt buttonVal;
TRequestStatus lStatus;
notifier.Notify(_L("First line of notification"), _L("Second line of notification"), _L("Left button text"), _L("Right button text"), buttonVal, lStatus);
User::WaitForRequest(lStatus);
notifier.Close();
After User::WaitForRequest(lStatus) completes you can inspect value of buttonVal to know which button was pressed. It is set to: 0, if the left button is selected; 1, if the right button is selected.
Hope this helps.
|
1,637,938 | 1,638,470 | Finding the end of a zlib compressed stream | I'm working on an NMDC client (p2p, DC++ and friends) with Qt. The protocol itself is pretty straightforward:
$command parameters|
Except for compression:
"ZPipe works by sending a command $ZOn| to the client. After $ZOn a ZLib compressed stream containing commands will follow. This stream will end with an EOF that ZLib defines. (there is no $ZOff in the compressed stream!)"
Here's the relevant code:
QTcpSocket *conn;
bool compressed;
QByteArray zbuffer;
QByteArray buffer;
// ...
void NMDCConnection::on_conn_readyRead() {
// this gets called whenever we get new data from the hub
if(compressed) { // gets set when we receive $ZOn
zbuffer.append(conn->readAll());
// Magic happens here
if( stream_is_complete ) {
buffer.append(uncompressed_stream);
buffer.append(remainder_of_data);
compressed = false;
}
} else {
buffer.append(conn->readAll());
};
parse(buffer);
}
So, how do I get the values for stream_is_complete, uncompressed_stream, and remainder_of_data? I can't look for the next '$' because the stream can contain it. I tried looking for something resembling an EOF in the zlib documentation, but there is no such thing, in fact, every stream ends with a seemingly random character.
I also played around with qUncompress(), but that wants a complete stream, nothing less, nothing more.
| Are you using zlib directly?
Totally untested...
z_stream zstrm;
QByteArray zout;
// when you see a $ZOn|, initialize the z_stream struct
parse() {
...
if (I see a $ZOn|) {
zstrm.next_in = Z_NULL;
zstrm.avail_in = 0;
zstrm.zalloc = Z_NULL;
zstrm.zfree = Z_NULL;
zstrm.opaque = 0;
inflateInit(&zstrm);
compressed = true;
}
}
void NMDCConnection::on_conn_readyRead() {
if (compressed) {
zbuffer.append(conn->readAll());
int rc;
do {
zstrm.next_in = zbuffer.data();
zstrm.avail_in = zbuffer.size();
zout.resize(zstrm.total_out + BLOCK_SIZE);
zstrm.next_out = zout.data() + zstrm.total_out;
zstrm.avail_out = BLOCK_SIZE;
rc = inflate(&zstrm, Z_SYNC_FLUSH);
zbuffer.remove(0, zstrm.next_in - zbuffer.data());
} while (rc == Z_OK && zstrm->avail_out == 0);
if (rc == Z_STREAM_END) {
zout.truncate(zstrm.total_out);
buffer.append(zout);
zout.clear();
buffer.append(zbuffer);
zbuffer.clear();
compress = false;
inflateEnd(&zstrm);
}
else if (rc != Z_OK) {
// ERROR! look at zstrm.msg
}
}
else // whatever
}
This incrementally decompresses (inflates) from qbuffer to qout, and stops when inflate says "no more".
Maybe it would be better to borrow from QuaZip instead.
|
1,638,073 | 1,638,426 | NOT sharing all classes with shared library | As ugly as win32 Microsoft compiler is by using the __declspec macro, it does have the advantage of being explicit about what you want to export or not.
Moving the same code onto a Linux gnu/gcc system now means all classes are exported!(?)
Is this really true?
Is there a way to NOT export a class within a shared library under gcc?
#ifndef WIN32
#define __IMPEXP__
#else
#undef __IMPEXP__
#ifdef __BUILDING_PULSETRACKER__
#define __IMPEXP__ __declspec(dllexport)
#else
#define __IMPEXP__ __declspec(dllimport)
#endif // __BUILDING_PULSETRACKER__
#endif // _WIN32
class __IMPEXP__ MyClass
{
...
}
| This is possible in GCC 4.0 and later. The GCC folks consider this visibility. There is a good article on the GCC wiki about the subject. Here is a snippet from that article:
#if defined _WIN32 || defined __CYGWIN__
#ifdef BUILDING_DLL
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__((dllexport))
#else
#define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
#endif
#else
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__((dllimport))
#else
#define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
#endif
#define DLL_LOCAL
#else
#if __GNUC__ >= 4
#define DLL_PUBLIC __attribute__ ((visibility("default")))
#define DLL_LOCAL __attribute__ ((visibility("hidden")))
#else
#define DLL_PUBLIC
#define DLL_LOCAL
#endif
#endif
extern "C" DLL_PUBLIC void function(int a);
class DLL_PUBLIC SomeClass
{
int c;
DLL_LOCAL void privateMethod(); // Only for use within this DSO
public:
Person(int _c) : c(_c) { }
static void foo(int a);
};
|
1,638,172 | 1,638,462 | Issues when moving code from one class into a new class? | I had some decryption code (using wincrypt.h) that lived within my FileReader.cpp class. I am trying to segregate the code and push this decryption method into a MyCrypt.cpp class. However, upon moving it I'm stuck with a bunch of errors that I wasn't facing before. For every wincrypt.h or windows.h specific command, I am recieving "identifier not found" or "undeclared identifier".
What gives!
More details..
Sample errors:
error C2065: 'HCRYPTPROV' : undeclared
identifier
error C3861: 'CryptDecrypt':
identifier not found
I am including windows.h and wincrypt.h, just as I was in FileReader.cpp.
#include "MyCrypt.h"
#include <windows.h>
#include <wincrypt.h>
MyCrypt.h is defined as:
#pragma once
class MyCrypt
{
public:
static char *DecryptMyFile(char *input, char *password, int size, int originalSize) ;
private:
static const DWORD KEY_LENGTH = 128;
}
If I rearrange my include files, I get the following errors instead:
error C2628: 'MyCrypt' followed by
'char' is illegal (did you forget a
';'?) error C2556: 'MyCrypt
*MyCrypt::DecryptMyFile(char *,char *,int,int)' : overloaded function differs only by return type from 'char
*MyCrypt::DecryptMyFile(char *,char *,int,int)
But nowhere in my code does it use this redefinition it speaks of..
| Check MyCrypt.h and make sure there's a ; after the closing brace. I've seen some fairly strange error messages when I've missed that. It's missing in the sample you posted.
|
1,638,237 | 1,638,648 | boost random number library, use same random number generator for different variate generators | It seems that one can use the following code to produce random numbers from a particular Normal distribution:
float mean = 0, variance = 1;
boost::mt19937 randgen(static_cast<unsigned int>(std::time(0)));
boost::normal_distribution<float> noise(mean, variance);
variate_generator<mt19937, normal_distribution<float> > nD(randgen, noise);
float random = nD();
This works fine, however, I would like to be able to draw numbers from several distributions, i.e. one would think something like:
float mean1 = 0, variance1 = 1, mean2 = 10, variance2 = 0.25;
boost::mt19937 randgen(static_cast<unsigned int>(std::time(0)));
boost::normal_distribution<float> noise1(mean1, variance1);
boost::normal_distribution<float> noise2(mean2, variance2);
variate_generator<mt19937, normal_distribution<float> > nD(randgen, noise1);
variate_generator<mt19937, normal_distribution<float> > nC(randgen, noise2);
float random1 = nD();
float random2 = nC();
However, the problem appears to be that nD() and nC() are generating similar sequences of numbers. I hypothesize this is because the constructor for variate_generator appears to make a copy of randgen, not use it explicitly. Thus, the same psuedo-random sequence is being generated and simply pushed through different transformations (due to the different parameters of the distributions).
Does anyone know if there is a way, in Boost, to create a single random number generator and use it for multiple distributions? Alternatively, does the design of the Boost random library intend users to create one random number generator per distribution? Obviously, I could write code to transform a sequence of uniform random numbers to a sequence from an arbitrary distribution, but I'm looking for something simple and already built-in to the library.
Thanks in advance for your help.
| Your hypothesis is correct. You want both variate_generator instances to use the same random number generator instance. So use a reference to mt19937 as your template parameter.
variate_generator<mt19937 &, normal_distribution<float> > nD(randgen, noise1);
variate_generator<mt19937 &, normal_distribution<float> > nC(randgen, noise2);
Obviously you'll have to ensure randgen does not go out of scope before nD and nC do.
|
1,638,306 | 1,638,324 | C++ - calling methods from outside the class | I have couple questions regarding some C++ rules.
Why am I able to call a function/method from outside the class in the namespace when I include the return type? (look at the namespace test2::testclass2 in the code below) i.e. this works:
bool b = testclass1::foo<int>(2);
whereas this doesn't: - (it doesn't even compile - compiler throws that this is function redeclaration)
testclass1::foo<int>(2);
C++ complains that it is a function redeclaration. Is that so?
This line:
bool b = testclass1::foo<int>(2);
gets called first before anything else. Is this because static methods get created always first before anything else in C++?
Where can I find those rules? I have a few C++ books at home, so if someone would be kind enough to either point out a book (and chapter or page) or direct me to a website I would greatly appreciate it.
Here below is the sample (partial) code that I tested at home with Visual Studio 2008:
class testclass1
{
public:
testclass1(void);
~testclass1(void);
template<class A> static bool foo(int i)
{
std::cout <<"in static foo";
return true;
}
};
namespace test2
{
class testclass2
{
public:
testclass2(void);
~testclass2(void);
};
bool b = testclass1::foo<int>(2);
}
EDIT:
A few people mentioned that I need to call this inside the function and this will work without any problem.
I understand that; the only reason I asked this question is because I saw this code somewhere (in someone's elses project) and was wondering how and why this works. Since I never really seen anyone doing it before.
Also, this is used (in multiple places) as a way to call and instantiate a large number of classes like this via those function calls (that are outside). They get called first before anything else is instantiated.
| C++ is not Python. You write statements in functions and execution starts from the main method. The reason bool b = ... happens to work is that it's defining the global variable b and the function call is merely the initialization expression.
Definitions can exist outside functions while other statements can only exist inside a function body.
|
1,638,394 | 1,638,417 | When should functions be member functions? | I have a colleague in my company whose opinions I have a great deal of respect for, but I simply cannot understand one of his preferred styles of writing code in C++.
For example, given there is some class A, he'll write global functions of the type:
void foo( A *ptrToA ){}
or:
void bar( const A &refToA ){}
My first instinct upon seeing global functions like that is: "Why aren't these members of A?" He'll insist up and down that this is consistent with recommendations for good practice in C++, because foo and bar can perform all they need to perform by using the public interface of A. For example, he'll argue that this is completely consistent with Scott Meyers Effective C++ recommendations. I find it hard to reconcile this with item 19 in that book which basically says everything should be a member function with a few exceptions (operator<< and operator>> and functions that need dynamic type conversion). Furthermore, while I agree that the functions can do what they need to do with the public interface of A, in my opinion, that's largely the result of people writing classes that have getters and setters for every data member of class A. So with that public interface, A is an over-glorified struct and you certainly can do anything with the public interface. Personally, I don't think that should be exploited, I think it should be discouraged.
Obviously, this is only possible in a language like C++ that is not pure object oriented, so I guess one way of looking at it is that my colleague does not favor a pure object oriented approach to software design. Does anyone know of any literature that supports this position as a best practice? Or does anyone agree with this and can possibly explain it to me in a different way than my colleague has so that I might see the light? Or does everyone agree with my current feeling that this just doesn't make much sense?
Edit:
Let me give a better code example.
class Car
{
Wheel frontLeft;
Wheel frontRight;
Wheel rearLeft;
Wheel rearRight;
Wheel spareInTrunk;
public:
void wheelsOnCar( list< Wheel > &wheels )
{
wheels.push_back( frontLeft );
wheels.push_back( frontRight);
wheels.push_back( rearLeft);
wheels.push_back( rearRight);
}
const Wheel & getSpare(){ return spareInTrunk; }
void setSpare( const Wheel &newSpare ){ spareInTrunk = newSpare; }
// There are getters and setters for the other wheels too,
//but they aren't important for this example
};
Then I'll see a function like this:
void wheelsRelatedToCar( Car *aCar, list< Wheel > &wheels )
{
aCar->wheelsOnCar( wheels );
wheels.push_back( aCar->getSpare() );
}
This is a real example with the names of the classes and functions changed of course. Why would one want wheelsRelatedToCar to not be a member function of Car? In this real example, Car and Wheel were in the same library. The global function was defined in a source file in a specific application using that library, so the argument was made that the function was specific to the application. My response was that it was a perfectly legitimate operation on the Car and belonged with the Car class. Is there another perspective to look at it (other than one who does not prefer to use object oriented design)?
| Scott Meyers has advocated that non-member functions often improve encapsulation:
How Non-Member Functions Improve Encapsulation
Herb Sutter and Jim Hyslop also talk about this (citing Meyer's article) in "Self-Sufficient Headers"
http://www.ddj.com/cpp/184401705
These ideas have been republished (in more refined form) in the 3rd edition of Meyer's "Effective C++", "Item 23: Prefer non-member non-friend functions to member functions ", and Sutter/Alexandrescu's "C++ Coding Standards", "44 - Prefer writing nonmember nonfriend functions".
I think a lot of developers find this non-intuitive and maybe a little controversial.
|
1,638,437 | 1,638,461 | Given an angle and length, how do I calculate the coordinates | Assuming the upper left corner is (0,0) and I'm given an angle of 30 degrees, a starting point of (0,300), a line length of 600, how do I calculate the ending point of the line so
that the line is representative of the angle given.
The C pseudo-code is
main() {
int x,y;
getEndPoint(30, 600, 0, 300, &x, &y);
printf("end x=%d, end y=%d", x, y);
}
// input angle can be from 0 - 90 degrees
void getEndPoint(int angle, int len, int start_x, int start_y, int *end_x, int *end_y)
{
calculate the endpoint here for angle and length
*end_x = calculated_end_x;
*end_y = calculated_end_y;
}
| // edit to add conversion
#define radian2degree(a) (a * 57.295779513082)
#define degree2radian(a) (a * 0.017453292519)
x = start_x + len * cos(angle);
y = start_y + len * sin(angle);
|
1,638,471 | 1,638,587 | show/hide desktop icons from c++ application | Right-click on desktop, uncheck view->Show Desktop icons. All icons on desktop will disappear. Is it possible to show/hide desktop icons from c++ application? Do you have an example of c++ code for it?
Thanks a lot in advance for any suggestions.
| SHGetSetSettings fHideIcons
|
1,638,584 | 1,681,299 | Cannot load SQL driver in Visual C++ (but loads in QtCreator) | I have a QT application that requires the MySql driver. I have both a .pro file to compile the app with QtCreator and a .vcproj for Visual C++ 2008 Express. The code is identical and it compiles without a hitch, but the executable created by Visual C++ Express gives me the following output and refuses to load any driver/plugin:
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers:
I used QCoreApplication to identify the location where the plugins are and it seems that both executables have the same path, so they should both see the plugins. One does, and the other doesn't.
The code is standard.
QSqlDatabase db;
db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setPort(3306);
db.setDatabaseName("dbase");
db.setUserName("user");
db.setPassword("pwd");
bool ok = db.open();
The same thing happens with the SqlBrowser sample that came with QT, so I don't think the code is the problem.
| For anyone else who bumped into this problem I have to say this - it is much easier to use one of the packages containing QT pre-built binaries for Visual C++ than trying to build it yourself. And the Qt driver (the 4.3 version at least) is awfully hard to get to work (on some machines it works like a charm but on others it can't find the driver, using the same code and binaries), so you are much better off using a dedicated MySql library.
|
1,638,967 | 1,641,781 | How can I truncate the mangled C++ identifiers shown by GDB's disassemble command? | GDB's disassemble command is nice for short C identifiers, e.g. main. For long, mangled C++ identifiers the verbosity is overkill. For example, using icpc I see results like
(gdb) disassemble 0x49de2f 0x49de5b
Dump of assembler code from 0x49de2f to 0x49de5b:
0x000000000049de2f <_ZN5pecos8suzerain16fftw_multi_array6detail18c2c_buffer_processIPA2_dPKSt7complexIdEilNS2_26complex_copy_differentiateIS4_EEEEvT_T1_T2_T0_SD_SE_RKT3_+167>: mov 0x18(%rsp),%rsi
Displays that long are annoying in the CLI. They make GDB's TUI assembly display all but useless.
Is there a way to tell GDB to show a truncated identifier? Say clip all but 50 characters?
| Current GDB from CVS behaves the way you want when it knows that there is only one function in the disassembly:
(gdb) disas 0x000000000040071c
Dump of assembler code for function _ZNKSt8_Rb_treeIPiSt4pairIKS0_S0_ESt10_Select1stIS3_ESt4lessIS0_ESaIS3_EE21_M_get_Node_allocatorEv:
0x000000000040071c <+0>: push %rbp
0x000000000040071d <+1>: mov %rsp,%rbp
0x0000000000400720 <+4>: mov %rdi,-0x8(%rbp)
0x0000000000400724 <+8>: mov -0x8(%rbp),%rax
0x0000000000400728 <+12>: leaveq
0x0000000000400729 <+13>: retq
End of assembler dump.
When GDB can't know whether or not disassembly will cross function boundary, it still prints the "long" form:
(gdb) disas 0x000000000040071c 0x000000000040071c+1
Dump of assembler code from 0x40071c to 0x40071d:
0x000000000040071c <_ZNKSt8_Rb_treeIPiSt4pairIKS0_S0_ESt10_Select1stIS3_ESt4lessIS0_ESaIS3_EE21_M_get_Node_allocatorEv+0>: push %rbp
End of assembler dump.
Here is the patch which introduced the "short form".
|
1,639,154 | 1,639,164 | How to declare a static const char* in your header file? | I'd like to define a constant char* in my header file for my .cpp file to use. So I've tried this:
private:
static const char *SOMETHING = "sommething";
Which brings me with the following compiler error:
error C2864: 'SomeClass::SOMETHING' :
only static const integral data
members can be initialized within a
class
I'm new to C++. What is going on here? Why is this illegal? And how can you do it alternatively?
| NB : this has changed since C++11, read other answers too
You need to define static variables in a translation unit, unless they are of integral types.
In your header:
private:
static const char *SOMETHING;
static const int MyInt = 8; // would be ok
In the .cpp file:
const char *YourClass::SOMETHING = "something";
C++ standard, 9.4.2/4:
If a static data member is of const
integral or const enumeration type,
its declaration in the class
definition can specify a
constant-initializer which shall be an
integral constant expression. In that
case, the member can appear in
integral constant expressions within
its scope. The member shall still be
defined in a namespace scope if it is
used in the program and the namespace
scope definition shall not contain an
initializer.
|
1,639,286 | 1,639,475 | Boost Asio async_read doesn't stop reading? | So,
I've been playing around with the Boost asio functions and sockets (specifically the async read/write). Now, I thought that boost::asio::async_read only called the handler when a new buffer came in from the network connection... however it doesn't stop reading the same buffer and thus keeps calling the handler. I've been able to mitigate it by checking the number of bytes transferred, however it is basically in a busy-waiting loop wasting CPU cycles.
Here is what I have:
class tcp_connection : : public boost::enable_shared_from_this<tcp_connection>
{
public:
// other functions here
void start()
{
boost::asio::async_read(socket_, boost::asio::buffer(buf, TERRAINPACKETSIZE),
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
const unsigned int TERRAINPACKETSIZE = 128;
char buf[TERRAINPACKETSIZE];
void handle_read(const boost::system::error_code& error, size_t bytesT)
{
if (bytesT > 0)
{
// Do the packet handling stuff here
}
boost::asio::async_read(socket_, boost::asio::buffer(buf, TERRAINPACKETSIZE),
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
};
Some stuff is cut out, but basically a new connection gets created then start() is called. Is there something I'm missing so that the handle_read method doesn't get continuously called?
| A wild guess: Do you check error in handle_read? If the socket is in an error state for some reason, I guess that the nested call to async_read made from handle_read will immediately "complete", resulting in an immediate call to handle_read
|
1,639,393 | 1,639,431 | How do I use member functions of constant arrays in C++? | Here is a simplified version of what I have (not working):
prog.h:
...
const string c_strExample1 = "ex1";
const string c_strExample2 = "ex2";
const string c_astrExamples[] = {c_strExample1, c_strExample2};
...
prog.cpp:
...
int main()
{
int nLength = c_astrExamples.length();
for (int i = 0; i < nLength; i++)
cout << c_astrExamples[i] << "\n";
return 0;
}
...
When I try to build, I get the following error:
error C2228: left of '.length' must have class/struct/union
The error occurs only when I try to use member functions of the c_astrExamples.
If I replace "c_astrExamples.length()" with the number 2, everything appears to work correctly.
I am able to use the member functions of c_strExample1 and c_strExample2, so I think the behavior arises out of some difference between my use of strings vs arrays of strings.
Is my initialization in prog.h wrong? Do I need something special in prog.cpp?
| Arrays in C++ don't have member functions. You should use a collection like vector<string> if you want an object, or compute the length like this:
int nLength = sizeof(c_astrExamples)/sizeof(c_astrExamples[0]);
|
1,639,411 | 1,639,437 | Comparing character arrays and string literals in C++ | I have a character array and I'm trying to figure out if it matches a string literal, for example:
char value[] = "yes";
if(value == "yes") {
// code block
} else {
// code block
}
This resulted in the following error: comparison with string literal results in unspecified behavior. I also tried something like:
char value[] = "yes";
if(strcmp(value, "yes")) {
// code block
} else {
// code block
}
This didn't yield any compiler errors but it is not behaving as expected.
| std::strcmp returns 0 if strings are equal.
|
1,639,797 | 1,639,821 | Template issue causes linker error (C++) | I have very little idea what's going in regards to C++ templates, but I'm trying to implement a function that searches a vector for an element satisfying a given property (in this case, searching for one with the name given). My declaration in my .h file is as follows:
template <typename T>
T* find_name(std::vector<T*> v, std::string name);
When I compile, I get this linker error when I call the function:
Error 1 error LNK2019: unresolved external symbol "class Item * __cdecl find_name<class Item>(class std::vector<class Item *,class std::allocator<class Item *> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??$find_name@VItem@@@@YAPAVItem@@V?$vector@PAVItem@@V?$allocator@PAVItem@@@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) referenced in function "public: class Item * __thiscall Place::get_item(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?get_item@Place@@QAEPAVItem@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) place.obj Program2
Again, I'm new to templates so I don't know what's going. All instances I've found of LNK2019 through Google have been about not using the correct libraries, but since this is my own function I don't see why this would be happening.
Also, a related question: Is there a way to make a template parameter so that it has to be a subclass of a certain class, i.e. template?
| You have to have your template definitions available at the calling site. That means no .cpp files.
The reason is templates cannot be compiled. Think of functions as cookies, and the compiler is an oven.
Templates are only a cookie cutter, because they don't know what type of cookie they are. It only tells the compiler how to make the function when given a type, but in itself, it can't be used because there is no concrete type being operated on. You can't cook a cookie cutter. Only when you have the tasty cookie dough ready (i.e., given the compiler the dough [type])) can you cut the cookie and cook it.
Likewise, only when you actually use the template with a certain type can the compiler generate the actual function, and compile it. It can't do this, however, if the template definition is missing. You have to move it into the header file, so the caller of the function can make the cookie.
|
1,639,895 | 1,647,240 | Cairo and Qt integration | I want to use Cairo graphics library whith Qt, but I can't find any documenattion. I just want to make the GUI whith Qt and use Cairo for drawing graphics in a Qt window.
Thanks.
| Starting from cairo 1.17.8, the Qt support will be removed upstream.
Old answer
Recent version of cairo supports Qt by allowing to draw to a surface created with cairo_qt_surface_create(QPainter *painter): you can inspect the relevant header file here. There's no documentation because this feature is still experimental and disabled by default (you should compile cairo yourself explicitely enabling the Qt support with configure --enable-qt.
|
1,639,903 | 1,640,041 | Programmatically getting per-process disk io statistics on Windows? | I would like to display a list of processes (Windows, C++) and how much they are reading and writing from the disk in KB/sec.
The Resource Monitor of Windows 7 has the ability so I should be able to do the same.
However I have unable to find a relevant API-call or find anything in the perfmon counters. Could anyone point me in the direction?
| You can call GetProcessIoCounters to get overall disk I/O data per process - you'll need to keep track of deltas and converting to time-based rate yourself.
This API will tell you total number of I/O operations as well as total bytes.
|
1,639,914 | 1,639,942 | Calling a function on standard map element without inserting it first | Is the following code OK?
class A
{
public:
A();
void foo();
};
map<int,A> m;
m[0].foo();
Or do I have to do the following:
map<int,A> m;
m[0] = A();
m[0].foo();
And also, can I do this:
map<int,A> m;
A a = m[5];
And how about access by reference:
void foo(A & a);
map<int,A> m;
foo(m[5]);
| map::operator [] will create a new value on the fly if it doesn't already exist. So all of your code examples will work.
That said, this example:
map<int,A> m;
m[0] = A(); // redundant
m[0].foo();
is overkill as the second line is redundant.
|
1,640,154 | 1,682,618 | Determining when .NET is about to be loaded in (unmanaged) C++ | [ this is getting TLDR...sorry... ]
I work on a huge (mostly) C++/MFC application with hundreds of DLLs; it supports a dynamically-loaded "add in" mechanism via COM, thus add-ins can be developed in .NET by using COM interop. Some limited new functionality is developed in .NET w/o using this "add-in" mechanism (although still dynamically loaded); however, the end user can decide to not use this feature. Thus, .NET might not be loaded at startup.
But, when .NET is loaded, I need to do some .NET-specific initialzation (specifically setting CurrentUICulture to match the native/unmanaged UI).
One solution is to simply punt and do this .NET initialization when the code gets around to loading either the new .NET functionaliy or COM add-ins. Given the nature of this applicaton, it is probably a 95+% solution (most users will be using the new functionality).
But it's not foolproof. Somebody could "readily" add new .NET functionality at any time by building a module with the /clr flag (remember, this is a huge application).
One more robust (and obvious) solution is simply cause .NET to be loaded at startup via C++/CLI. But some of the die-hard C++ developers to whom every byte and clock cycle matter don't want to do this; somewhat understandable as there's no need to set CurrentUICulture unless/until .NET is loaded.
Another possibility I thought of is to hook LoadLibrary and look for mscorlib. Now I know .NET is about to be loaded for some reason, load it in the normal manner and do the initialization before the other code does anything. But hooking LoadLibrary (or anything else, for that matter) really isn't something I want to do.
So, is there an easy(ier)/better way to tell if .NET about to be loaded?
Edit: Reed's answer of LockClrVersion is pretty darn close. The only hiccup is that it won't work if you link in a mixed-mode DLL/assembly.
// ClrAboutToLoad.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <MSCorEE.h>
// http://community.bartdesmet.net/blogs/bart/archive/2005/07/22/2882.aspx
FLockClrVersionCallback begin_init, end_init;
STDAPI hostCallback()
{
printf("hostCallback()\n");
// we're in control; notify the shim to grant us the exclusive initialization right
begin_init();
ICLRRuntimeHost *pHost = NULL;
HRESULT hr = CorBindToRuntimeEx(NULL, L"wks", STARTUP_SERVER_GC, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (PVOID*) &pHost);
hr = pHost->Start();
// mission completed; tell the shim we're ready
end_init();
return S_OK;
}
int _tmain(int argc, _TCHAR* argv[])
{
LockClrVersion(&hostCallback, &begin_init, &end_init);
//fnTheDLL();
HMODULE hModule = LoadLibrary(L"TheDLL");
FARPROC fp = GetProcAddress(hModule, "fnTheDLL");
typedef void (*fnTheDLL_t)();
fnTheDLL_t fnTheDLL = reinterpret_cast<fnTheDLL_t>(fp);
fnTheDLL();
FreeLibrary(hModule);
return 0;
}
| I believe you can do this by having your process call the unmanaged LockClrVersion function prior to using any managed APIs. This function allows you to specify two FLockClrVersion callback methods.
The first method (pBeginHostSetup), is called prior to the CLR being initialized the first time for the hosting process. The second method (pEndHostSetup) is called when initialization of the CLR is complete.
This should allow you to specify unmanaged code that is run just prior and just after CLR initialization. In your case, you probably need to hook into the pEndHostSetup to call your managed API setup routines (you'll need to wait until the CLR is hosted successfully).
|
1,640,292 | 1,640,339 | c++ and zlib static library | I am making a c++ (windows devc++) application which downloads a file using libcurl. I have included the libcurl source code and library to mu executable, so no external dll is required. libcurl requires zlib. But I cannot find out how to include it in the executable. As a result zlib1.dll has to be present. Does anybody know how to include this as well? Thanks in advance!
| You have two options.
You said you're using Dev-C++ which compiles using GCC. zlib has a static library option Makefile, just use make libz.a and it will produce the static library you desire.
Another option would be to include the zlib source code directly into your application - that means just take the zlib sources and put them inside a dedicated directory in your application's source and set DevC++ to compile it.
|
1,640,309 | 1,640,619 | C++ static members in class | Is it possible to access to access and use static members within a class without first creating a instance of that class? Ie treat the the class as some sort of dumping ground for globals
James
| You can also call a static method through a null pointer. The code below will work but please don't use it:)
struct Foo
{
static int boo() { return 2; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo* pFoo = NULL;
int b = pFoo->boo(); // b will now have the value 2
return 0;
}
|
1,640,355 | 1,640,362 | What's the low-level difference between a pointer an a reference? | If we have this code:
int foo=100;
int& reference = foo;
int* pointer = &reference;
There's no actual binary difference in the reference's data and the pointer's data. (they both contain the location in memory of foo)
part 2
So where do all the other differences between pointers and references (discussed here) come in? Does the compiler enforce them or are they actually different types of variables on the assemebly level? In other words, do the following produce the same assembly language?
foo=100;
int& reference=foo;
reference=5;
foo=100;
int* pointer=&foo;
*pointer=5;
| Theoretically, they could be implemented in different ways.
In practice, every compiler I've seen compiles pointers and references to the same machine code. The distinction is entirely at the language level.
But, like cdiggins says, you shouldn't depend on that generalization until you've verified it's true for your compiler and platform.
|
1,640,414 | 1,640,428 | Does a base class's constructor and destructor get called with the derived ones? | I have a class called MyBase which has a constructor and destructor:
class MyBase
{
public:
MyBase(void);
~MyBase(void);
};
and I have a class called Banana, that extends MyBase like so:
class Banana:public MyBase
{
public:
Banana(void);
~Banana(void);
};
Does the implementation of the new constructor and destructor in Banana override the MyBase ones, or do they still exist, and get called say before or after the Banana constructor / destructor executes?
Thanks, and my apologies if my question seems silly.
| It should say
class Banana : public MyBase
{
public:
Banana(void);
~Banana(void);
};
The constructor of the derived class gets called after the constructor of the base class. The destructors get called in reversed order.
|
1,640,540 | 1,641,459 | How do I append elements with duplicate names using MSXML & C++? | I am write some code to update a XML DOM using MSXML4 & C++. I need a method that appends a child element to a parent element. The code I have written below works until the title of the child matches the title of another child under the parent. I cannot change the title of the children so I need to find a way to append them to the parent.
Can anyone provide some guidance?
// this call creates '<parent><child/></parent>'
AppendChild("/root/parent", "child");
// this call attempts to create '<parent><child/><child/></parent>' but the DOM remains unchanged ('<parent><child/></parent>')
AppendChild("/root/parent", "child");
void AppendChild(const std::string kPathOfParent, const std::string kNameOfChild)
{
MSXML2::IXMLDOMNodePtr pElement = m_pXmlDoc->createNode(NODE_ELEMENT, kNameOfChild.c_str(), m_xmlns.c_str());
MSXML2::IXMLDOMNodePtr pParent = m_pXmlDoc->selectSingleNode(kPathOfParent.c_str());
MSXML2::IXMLDOMNodePtr pNewChild = pParent->appendChild(pElement);
}
| I am not sure exactly what the problem was, but somewhere my binaries were out of step. I rebuilt the entire project via 'Clean Solution' instead of just the 'Build Solution' option. Now both children are created using the code above. It is not clear to me why I was able to step in to the code via the debugger, but the second child was never created until I cleaned the solution.
Jeff & Remy, thank-you for your comments.
|
1,640,608 | 1,640,620 | In C++, can you manually set the failbit of a stream? How? | I am overloading the input stream operator for use with a Time class and would like to manually set the failbit of the input stream if the input doesn't match my expected time format (hh:mm). Can this be done? How?
Thanks!
| Yes, you can set it with ios::setstate, like so:
#include <iostream>
#include <ios>
int main()
{
std::cout << "Hi\n";
std::cout.setstate(std::ios::failbit);
std::cout << "Fail!\n";
}
The second output will not be produced because cout is in the failed state.
(An exception seems cleaner to me, but YMMV)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.