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 cyc... | 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, ... |
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 encl... | 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 ti... | 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 r... |
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... | 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 (wh... |
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 = ::CreateFile... | 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 fi... |
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++... | 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'... |
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 av... | 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_i... |
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 usual... | 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 o... |
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 ... | 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) =... |
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:
e... | 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 sugge... |
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 warnin... | 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 ... |
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... |
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-sid... | 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 tha... |
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);
l... | 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 t... |
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_bac... | 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 ... |
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(), vec... | 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, i... |
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++ Er... | 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 lo... | 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 ... |
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 gra... | 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... |
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 rep... | 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) { ... | 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<re... |
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 ap... | 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 b... |
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 cl... | 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, esp... | 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 nec... |
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 ... | 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,... |
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(cons... | 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 ar... | 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 ... |
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 = [E... | 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 wo... | 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++ ... |
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... | 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>) whi... |
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 l... | 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... |
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 opera... | 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 Inp... |
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... |
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::ma... | 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 thoug... | 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)
K... |
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... | 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, al... |
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::... | 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... |
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 ... |
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 a... |
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 __firs... | 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.... |
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... | 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 t... |
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
... | 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 Erro... | 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 proj... |
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 ... | 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... | 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 b... |
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::ve... | 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... |
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:
... |
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 ta... | 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 ... |
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 manage... | 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 fr... |
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 iterato... | 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 iterat... |
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;
}
... | 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:
// he... |
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, ... | 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’, opt... |
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,... |
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... | 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,... | 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 ... | 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... | 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 n... |
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... | 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 thr... |
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 us... |
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 mu... | 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... |
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 manua... | 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;... | 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 ... | 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 programmi... |
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>'... | 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 e... |
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;
re... | 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 ... |
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 Log... | 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
}
ou... |
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 genera... |
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 <... |
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 ... | 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("Fi... |
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 ... | 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.opaq... |
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 libra... | 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
... |
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... | 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... | 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(... |
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 comp... | 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 exis... |
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 ... | 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 f... |
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);
pri... | // 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 drive... | 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 othe... |
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_array6de... | 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
... |
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... | 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 = "somethi... |
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... | 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++)
... | 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:
c... | 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*>... | 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... |
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... |
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 poi... | 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 (althoug... | 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.... |
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 anybo... | 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 ... |
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 i... | 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 ... |
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... | 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 app... | 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 ... |
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 YMM... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.