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 |
|---|---|---|---|---|
3,108,384 | 3,109,747 | c++ static library is too big, why? | This is what I'm doing (this is an example, not a real-life syntax):
$ svn co http://svn.boost.org/svn/boost/trunk/libs/regex/src regex
$ c++ -o regex/*.obj -c regex/*.cpp
I have 17 *.obj files in regex. Now I'm trying to create a static library from them:
$ ar -r regex.lib regex/*.obj
The size of the library is 10Mb... | You can't predict the size of the output from the number of source files. A file could contain a dozen lines of simple code, or thousands of lines of spaghetti, or a vast data table. Object files (and static libraries, which are just collections of object files) contain metadata used for linking, which can be removed f... |
3,108,415 | 3,108,755 | Making C++ COM classes more test-friendly | Our code-base has a lot of COM objects, so typically we'll have something like:
//this is the IDL-generated IGetTime interface header
#include "gettime.h"
//our COM class implementation of IGetTime
class CGetTime : public IGetTime
{
public:
CGetTime(CGetTimeCF &factory,...); //COM-specific constructor params
... | Where I work, we chose to separate core C++ classes from the COM ones for several reasons:
This is easier to maintain. People that don't know COM much can focus on writing core classes and people who do know COM can safely wrap the core classes, without caring about the underlying implementation.
Code reusability. Thi... |
3,108,454 | 3,108,506 | Validation For Phone Number and Mobile Number | I need a c,c++ code for validating a Phone Number(8 Digits- Starting with 2) and Mobile Number(10 Digits- Starts with 9).
Also it should not allow to enter any space, special charcter, as well as charcters.
Here user can enter either phone number or mobile number.
Plese Help in this,
Thanks,
| Here's the code:
bool is_valid_number(const std::string& number)
{
static const std::string AllowedChars = "0123456789";
for(auto numberChar = number.begin();
numberChar != number.end(); ++numberChar)
if(AllowedChars.end() == std::find(
AllowedChars.begin(), AllowedChars.end(), *nu... |
3,108,455 | 3,108,672 | Virtual methods make the application slower, but can they speed up the linking? | As described in Virtual functions and performance - C++ virtual methods may have an impact on performance (extra lookup in vtable, no inlining, ...).
But I was wondering, could the use of virtual functions speed up the linking process?
Suppose that I have a class X, calling a method of class Y.
If the method is a non-... | I don't get it, doesn't the compiler go through the exact same process with virtual calls as non virtual calls only it has to look up where the method would be in the virtual table (as well as hold the virtual table in memory thus ruining locality) and handle generating code for the indirect call also?
If anything, vir... |
3,108,472 | 3,108,553 | How to cast an int variable to char in C++? | char a[3];
int x=9;
int y=8;
a[0]=(char)x;
a[1]=(char)y;
a[2]='\0';
unsigned char * temp=(unsigned char*)a;
but when i am displaying this temp, it's displaying ?8. should display 98.
can anyone please help???
| char a[3];
int x='9';
int y='8';
a[0]=(char)x;
a[1]=(char)y;
a[2]='\0';
unsigned char * temp=(unsigned char*)a;
printf("%s", temp);
You were giving a value of 9 and 8, instead of their ASCII values.
|
3,108,478 | 3,108,502 | Synchronize system clock with UTC time using C uder Window OS | I have UTC time which is coming from UDP, I have a program to calculate Day and Time of UTC, how can I set my system clock at that day and time, kindly give me some direction so that I can make it possible.
I am using Window OS.
| To set the current system time, use the SetSystemTime Win32 API function.
|
3,108,536 | 3,110,077 | Good cross platform functional language for library use in a C++ application? | What are my options in terms of a fast functional language for library use in a cross-platform Qt C++ application?
It seems almost all languages (functional or not) have some way of calling C/C++ code in an easy manner. I'd like to go the other way around - write an application in Qt using C++ for stateful business lo... | Haskell has this capability, though the interaction with Qt/qmake and your build process with ghc may take a little trickery to get working:
http://www.haskell.org/haskellwiki/Calling_Haskell_from_C
There is also a project called HaskellDirect which seems similar to your purpose as well:
http://www.haskell.org/hdirect/... |
3,108,631 | 3,108,762 | How to pass a pointer to a member function to a C function? |
Possible Duplicate:
Using a C++ class member function as a C callback function
I'm writing an object-oriented library using a C library (winpcap). I need to pass the callback function that is called when a network packet arrives as a function pointer. I would like to pass a member function pointer to winpcap, to kee... | Kindly refer to detailed topic about
How to Implement a Callback to a static C++ Member Function ?
How to Implement a Callback to a non-static C++ Member Function ?
http://www.newty.de/fpt/callback.html
|
3,108,965 | 3,109,021 | Error: Cannot add two pointers | It gives the error in the title about this piece of code:
string DDateTime::date2OracleDate(DATE Date)
{
string s;
s="TO_DATE('" + DateFormat("%d/%m/%Y",Date) + "','dd/MM/YYYY')";
return s;
}
I don't understand how that is possible, no pointers involved....
EDIT:
string DDateTime::DateFormat(string sFormat... | The following should work better:
string DDateTime::date2OracleDate(DATE Date)
{
string s = "TO_DATE('";
s += DateFormat("%d/%m/%Y",Date);
s += "','dd/MM/YYYY')";
return s;
}
|
3,109,134 | 3,109,160 | What should the following code do and with explanations | class A {
public:
A() { }
~A() { cout << "A Destructor \n" ; }
};
class B :public A{
public:
B() { }
virtual ~B() { cout << "B Destructor \n" ; }
};
class C : public B {
public:
C() { }
~C() { cout << "C Destructor \n"; }
};
int main()
{
A *pointA = new A;
A *pointB = new B;
A ... | It will invoke undefined behavior at the second (and third) delete, because A's destructor is not virtual.
§5.3.5/3:
if the static type of the operand is different from its dynamic type, the
static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the be... |
3,109,387 | 3,109,514 | Undefined references when compiling a static Qt build on Windows | I'd like to compile a static version of the Qt toolkit on the Windows platform (Windows XP SP3). I downloaded the latest release for Windows and successfully installed it. Then I opened the Qt 4.6.3 Command Prompt from the Start menu and invoked:
configure -static -release -nomake examples -nomake demos -fast
Configura... | I had similar problems. In my case Visual Studio had set environment parameters
INCLUDE and LIB which confused the make.
The solution was to disable them from the command line
set INCLUDE=
set LIB=
before compiling the Qt libraries.
|
3,109,392 | 3,109,601 | Signal - Slot connection inside loop | In my code I am creating new objects of same type inside loop and connecting a signal to object slot. Here is my trial.
A * a;
QList<A *> aList;
int aCounter = 0;
while(aCounter < 2)
{
a = new A;
aList.push_back(a);
connect(this,SIGNAL(somethingHappened()),aList[aCounter],SLOT(doSometing()));
aCounter++;
}... | If I understand you correctly you may want to do something like this?
A * a;
QList<A *> aList;
int aCounter = 0;
while(aCounter < 2)
{
a = new A;
aList.push_back(a);
if ( aCounter == 0 )
connect(this,SIGNAL(somethingHappened()),aList[aCounter],SLOT(doSometing()));
aCounter++;
}
This connects the si... |
3,109,414 | 3,109,494 | Library to manage menus in embedded device for C/C++ | I'm looking for a library to manage menus. I'm looking for something which is based on configuration files. It doesn't have to manage keyboard input or display, just the menu logic. What I have in mind something like:
//menu.xml
<menu>
<Start />
<Stop />
<Configuration displayname="Configure System">
... | There are things like Kaleido: http://www.digitalairways.com/kaleido-engine.htm
which are very nice, but pricey.
Emwin is simpler and cheaper but nothing like as rich in terms of functionality:
http://www.segger.com/cms/emwin.html
|
3,109,543 | 3,109,586 | What to do to make application Large Address Aware? | I am currently in process of making our application Large Address Aware. As experience has shown, there are some unexpected gotchas when doing so. I create this post to make a complete list of steps which need to be taken.
The development considerations listed in the AMD Large Address Aware guide provide a good startin... |
(obvious) select Support Address Larger than 2 Gigabytes (/LARGEADDRESSAWARE) in the project properties: Linker / System / Enable Large Address
check all pointer subtractions and verify the result is stored in a type which can contain the possible difference, or replace them with comparisons or other constructs - see ... |
3,109,565 | 3,109,592 | C++ or Python (maybe else) to create GUI for console application in C | I have a Visual C console application (created in VC++2008EE) and I need to add GUI to it.
One idea was to invoke the console app as a subprocess and communicate with it using stdin and stdout. I tried to do that with Python subprocess module - but it deadlocks (probably because my console app is running continuously).... | If you own the code for the console app, don't mess around trying to talk to it using input and output streams. Extract the logic of your console app into a library, and call that library from a GUI of your choice - either Windows.Forms from C#, Python GTK, ordinary GTK.
|
3,109,649 | 3,110,281 | Modifying a file from within an executable - permission denied in XP (but not Vista) | I have an application where I need to open an xml file, modify it, and close it again. When I test the code on a laptop running Windows Vista, it works perfectly, but under Windows XP I can't even open the file for read/write access:
errno_t _wfopen_s(&inStream, m_fileName, L"r+, ccs = UTF-8");
...without getting an e... | Well, with r+ you will ask for write access to the file. A privilege that is harder to come by, do triple-check that the user account indeed has the write privilege in the folder.
But sounds like you already checked that. The next consideration is sharing. The fopen() function is quite inappropriate on modern multit... |
3,109,737 | 3,109,865 | How to receive and decode SNMP traps in a C (or C++) application? | I am trying to write a very small SNMP trap receiver, listening to UDP port 162.
Traps come in fine, but I can not decode them.
I have found libber, but it can't decode the traps for some reason. I am probably using it wrong. I imagine decoding an SNMP trap should be fairly simple and that I am missing something crucia... | Well, using net-snmp, you usually use snmptrapd daemon that calls for you external commands/scripts. If you cannot use this way, I suggest you look at snmptrapd.c code. Moreover, if I recall correctly, they build a libsnmptrapd library. It should be easy to find the right API calls ...
If I have time I will update my a... |
3,109,943 | 3,109,979 | Returning after throwing exceptions | Is it in any way beneficial to return a value after throwing an exception? If not, can the return statement be left out and is it somehow possible to remove compiler error C4715: not all control paths return a value?
Thanks in advance.
Edit: (sample code)
for (ushort i = 0; i < itsNumUnits; ++i)
if (unitFormation[i... | There is no need to return a value after exception throw. If you have this error, you should check the paths your code can get to without throwing an exception, e.g.
if (something)
throw Exception;
else
return value;
Failing to return value in the "else" branch of "if" would cause a compile error because the e... |
3,110,022 | 3,110,066 | What do I need to download to use MFC without Visual Studio? | I've got Visual Studio 2008 express, and I need to use afx.h and some other things from MFC. Is there an SDK I can download that includes those? I downloaded the latest Windows SDK, but that didn't include it.
Thanks.
| MFC is the proprietary class collection for Microsoft paid customer so I don't think you can get them FOC (well legally of course).
You can consider Win32++ which attempt to mimic MFC functionalities and its open source.
|
3,110,140 | 3,110,178 | Take care about precedence of * and ++ in C/C++, (and any keystroke when programming) | Somebody write this function
void strToUpper(char *p) {
while (*p) {
*p = TOUPPER(*p);
*p++; //<-- Line to pay attention
}
}
I asked, why do you put the * before p++?
answer: because "It's the same", I corrected the code and then stay angry for a while, because both really work the same...
... | ++ has precedence over *. But I agree, it's unclear when you mix both in the same statement.
|
3,110,206 | 3,192,938 | Programmatically check if IPv6 is enabled on windows | Is there a way to programmatically check if IPv6 is installed/enabled on windows using c++? Either at an interface level, or system wide.
| WSCEnumProtocols() can be used to check whether IPv6 is installed as a protocol.
|
3,110,306 | 3,110,344 | Reading/Writing Nibbles (without bit fields) in C/C++ | Is there an easy way to read/write a nibble in a byte without using bit fields?
I'll always need to read both nibbles, but will need to write each nibble individually.
Thanks!
| Use masks :
char byte;
byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet
byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet
You may want to put this inside macros.
|
3,110,364 | 3,110,382 | C++: Compiler complains about variables initialization in constructor | I have in my header "Test.h" a variable of a class that doesn't have a constructor without arguments.
And I have a constructor like this:
Test::Test() // <-- Here he complains:
// error: no matching function for call to ‘Beer::Beer()’
{
int i = 2;
theVar = Beer(1, i); // Beer(int, int) is the only co... | You need to use initializer list.
Test::Test() : theVar(1, 2) {}
If the problem is that i is the result of some other function call, you can do sometihng like
Test::Test() : theVar(1, compute_i()) {}
The problem is that the constructor body is executed after all members are initialized.
They are initialized first by ... |
3,110,498 | 3,110,519 | C++ Reorganizing an array to fill in the gaps? | I'm not sure if the word Reorganizing is the correct term, but its the only way I can describe what I'm looking for.
If I have an array of say, Cats, like so:
CAT *myCats[99];
myCats[0] = new CAT;
myCats[1] = new CAT;
myCats[2] = new CAT;
myCats[3] = new CAT;
myCats[4] = new CAT;
myCats[5] = new CAT;
At one point in ... | If you are using C++, you can much more easily accomplish this using std::vector:
std::vector<CAT*> cats;
cats.push_back(new CAT);
cats.push_back(new CAT);
cats.push_back(new CAT);
// remove the second cat
delete cats[1];
cats.erase(cats.begin() + 1);
Now the vector has two cats in it (the first and third cats that w... |
3,110,557 | 3,110,600 | how can i load BitmapEx.h | I am working on MFC with c++. i got this error:
Cannot open include file: 'BitmapEx.h': No such file or directory.
plzz tell me how can i include it.
| What is this file? Is it on your disk?
If it is not one of the standard includes, you should put it in your CPP directory and include with double quotes, #include "BitmapEx.h"
|
3,110,560 | 3,111,479 | How can you link to a different version of MFC from a Visual C++ project in Visual Studio 2010? | I have a VC++ project in VS2010 that is linking to some dll's built with VS2008. Works fine until I try to pass MFC objects to the VS2008 dll. The artifact of the VS2010 VC++ project (a .dll) is linking against the latest version of MFC that shipped with VS2010, whereas the VS2008 .dll is linking against the previous... | Setting the Platform Toolset option to v90 works if and only if the Targeted framework is 3.5 (or less, I presume).
To change the Targeted framework you have to edit the .vcxproj file directly. To make the change, follow these directions. Note, that the XML element may not be present but the instructions to add the el... |
3,110,629 | 3,110,715 | convert std::string to basic_ostream? | Is there a conversion for the above?
| Convert a std::string to an output stream? Usually it's: convert a string to an input stream that reads characters from the given string:
std::string myString = //...
std::istringstream iss(myString);
See also: http://www.cplusplus.com/reference/iostream/istringstream/
|
3,110,926 | 3,112,317 | OpenCV - VideoWriter produces a video with a "repeated" image | I'm trying to process each frame in a pair of video files in OpenCV and then write the resulting frames to an output avi file. Everything works, except that the output video file looks strange: instead of one solid image, the image is repeated three times and horizontally compressed so all three copies fit into the win... | In the C++ version you have to tell cv::VideoWriter that you are sending a single channel image by setting the last paramter "false", are you sure you are doing this?
edit: alternatively you can convert a greyscale image to color using cvtColor() and CV_GRAY2RGB
|
3,110,976 | 3,111,007 | In C++, Is it good form to write code that executes before main()? | The constructors of globally declared classes are invoked before main is entered. While this can be confusing to a new reader of the code because it is done so infrequently, is it necessarily a bad idea?
| It's not necessarily a bad idea, but usually, yes.
First, it's global data, and globals are usually a bad thing.
The more global state you have, the harder it becomes to reason about your program.
Second, C++ doesn't guarantee intialization order of static objects defined in different translation units (.cpp files) -- ... |
3,111,045 | 3,111,164 | Where is disable_if in C++0x? | Boost has both enable_if and disable_if, but C++0x seems to be missing the latter. Why was it left out? Are there meta-programming facilities in C++0x that allow me to build disable_if in terms of enable_if?
Oh, I just noticed that std::enable_if is basically boost::enable_if_c, and that there is no such thing as boos... | At the risk of seeming stupid, just do !expression instead of expression in the bool template parameter in enable_if to make it behave like a disable_if? Of course if that idea works, you could just expand on it to write a class with disable_if-like behavior?
Ok, I believe you could implement disable_if like this:
temp... |
3,111,072 | 3,111,091 | c++ static function unfound | I have this definition of the function in my class.
The .hpp file:
class SomeClass
{
public:
static string DoStuff(string s);
};
The .cpp file:
#include "header.hpp"
string SomeClass::DoStuff(string s)
{
// do something
}
Compiler says:
**error C2039: 'DoStuff' : is not a member of 'SomeClass'**
Can somebody help... | Usually, .cpp files must include the matching .h or .hpp file.
Is it the case here ?
You can also have namespace issue (missing namespace in .cpp file or static method definition outside of the namespace, and so on.).
Actually, it is difficult to answer until we have the real breaking code.
Moreover, I don't know if t... |
3,111,147 | 3,111,269 | How do I configure Qt to work with Visual Studio 2010? | I downloaded open-source version of Qt from the site and have compiled it with nmake, but I'm having trouble using it in my projects. It seems that Visual Studio can't find the Qt headers, even though I added the paths to my PATH, INCLUDE, and LIB variables. I tried installing the Qt Visual Studio add-in but it only su... | Traditionally VS support was part of the paid licences, with the OS package you only get mingw support. Things are changing, but might have some rough edges for a while.
OTOH, mingw has a HUGE advantage: deployment. You don't have to chase around the vcredist_x86 files and all the associated voodoo. Just be sure to ... |
3,111,392 | 3,111,503 | Find width of a tab item? (WinAPI) | I want to be able to know how much room a particular tab takes up, is there a way to calculate this knowing it's text and having its item struct?
Thanks
| Assuming a SysTabControl how about TCM_GETITEMRECT?
|
3,111,501 | 3,111,551 | Make a template accept a specific class/family of classes? | I have a template method that is designed to work with a specific set of classes. Since I have no real need for runtime polymorphism, I've decided to not use pointers to the parent class, but rather will have the compiler put everything together for me.
I want to either restrict the type that can be passed to the temp... | Yes. It is possible using a number of different techniques depending on the specific needs of the day. There's boost::enable_if. There's MPL and static_assert...(use BOOST_STATIC_ASSERT if you're not using a C++0x compiler). There's Boost.Concepts.
Yes. It is possible.
|
3,111,647 | 3,111,695 | safe integer conversion in c++ | I want to create a simple integer range checker and converter using c++ templates.
The code looks like this:
// D is the "destination" type and S the "source" type
template <class D, class S>
inline D SafeConvert( S value );
template <class S>
inline int SafeConvert<int>( S value ) {
ASSERT( value >= S(INT_MIN) &... | You can't partially specialize function templates. You need to mimic it with a class wrapper or use standard function overloading. An example of mimicing:
template <typename T1, typename T2>
struct processor;
template < typename T1, typename T2 >
T1 fun(T2 t2) { return processor<T1,T2>::apply(t2); }
template < type... |
3,111,864 | 3,111,889 | How to create a library and call the header files using < > instead of ""? | I've been writing a library lately for my C++ computer class. I would like to put all my .lib and my header files inside a folder outside the project that's going to be calling the library. How can I call the library header files using the < > operators instead of the " "?
I'm using visual studio [specifically VS03]
Th... | To include files in a separate directory from the directory where your source files are, you must add the directory with the headers to your "Additional Include Directories" property in the "C\C++, General" property page for your project. Then you can include the headers with either <> or "".
See http://msdn.microsoft... |
3,111,873 | 3,111,906 | c++ inherit from a virtal base class | I want to do the following:
class ErrorBase
{
public:
void SetError(unsigned errorCode)
{
mErrorCode = errorCode;
}
char const* Explanation(unsigned errorCode) const
{
return errorExplanations[errorCode];
}
private:
char const* errorExplanations[];
unsigned mErrorCode;... | Either you pass the array of error messages to the base class in its constructor (syntax may not be perfect but hopefully you get the idea):
class ErrorBase {
public:
ErrorBase(char const* errorExplanations[]) {
this->errorExplanations = errorExplanations;
}
...
private:
char const* errorExpla... |
3,111,892 | 3,112,025 | Pointer-to-member-func, template & inheritance mixup | I am trying to create a generic "callback" object that will hold arbitrary data and invoke member functions of related classes. Due to internal policy, I cannot use Boost.
The callback object looks like this:
template<typename Object, typename Data>
class Callback
{
public:
typedef void (Object::*PHandler)(Callback*... | You have to pass the class type of the derived. To not break the typedef-way, you can can give that parameter a default value. Something like the following should work
template<typename Object, typename Data, typename Derived = void>
class Callback;
namespace detail {
template<typename Object, typename Data, typename... |
3,111,920 | 3,112,066 | how to transfer C++ number format to C# number format? | have the flowing C++ code:
CString info, info2;
info.Format("%2d", Value[i]);
info2.Format("%4.1f", Value[j]);
want to have the equivalent code in C#
how to do it?
| Code ported to C#:
String info;
String info2;
info = String.Format("{0,2:D}", Value[i]);
info2 = String.Format("{0,6:0.0}", Value[j]);
6 is used for aligning the string 4 digits plus decimal point plus decimal digit.
NOTE take care of the current Culture used, you might get , instead of . for some Cultures.
|
3,112,003 | 3,112,185 | Perform CRUD for todos/tasks/appointments from Outlook? | How can I perform CRUD (Create, Read, Update, Delete) for todos/tasks/appointments/etc from Outlook. Does Microsoft have a data api like Google that I can use to interact with Microsoft applications? I prefer this in C++ (Microsoft Visual C++), but Java will also work.
| Here is a tutorial article which might be along the lines of what you are looking for: Automate Microsoft Outlook from C++
|
3,112,092 | 3,112,153 | Recompile MFC DLL while client exe is running | Is it possible to recompile an MFC DLL while its "client" executable is running, and have the executable detect and pick up the new changes? If it's possible, is it foolish? Being able to recompile the DLL without restarting the exe would save some time in my coding workflow. I am using Visual Studio 2008, code is writ... | Unfortunately, unless the executable has support for hot-swapping DLLs, you can't do it. The standard DLL loading mechanism in Windows will load it either at the start of the process or at first use of a function exported by the DLL and will not watch the file for changes in order to reload it. Also, depending on how t... |
3,112,105 | 3,112,219 | C++ iostreams question | I am now diving into boost::iostreams and I'm looking for a way to create a stream that iterates over some container<char>.
Right now I have the code that work for a std::vector<char>, but it does ONLY for it, because I wrote std::vector-specific code.
I am doing the following thing:
template <class Object, class Conta... | Instead of passing the container as a parameter to your functions, what about using the approach taken by the standard library, and use iterators?
Your function would be templated on the iterator type instead of the container type and would take a begin and end iterator instead of a container. Then it's a simple matter... |
3,112,234 | 3,112,404 | multimap accumulate values | I have a multimap defined by
typedef std::pair<int, int> comp_buf_pair; //pair<comp_t, dij>
typedef std::pair<int, comp_buf_pair> node_buf_pair;
typedef std::multimap<int, comp_buf_pair> buf_map; //key=PE, value = pair<comp_t, dij>
typedef buf_map::iterator It_buf;
int summ (int x, int y) {return x+y;}
int total_bu... | Your issue is with the summ function, you actually need something better than that to be able to handle 2 mismatched types.
If you're lucky, this could work:
int summ(int x, buf_map::value_type const& v) { return x + v.second; }
If you're unlucky (depending on how accumulate is implemented), you could always:
struct S... |
3,112,278 | 3,136,097 | Is codeblocks 10.05. compatible with QtWorkbench? | windows xp sp2 , codeblocks 10.05. , Qt 4.6
Does anyone know if codeblocks_10.05 is compatible with QtWorkbench-0.6.0_alpha.
I made everything written on http://code.google.com/p/qtworkbench but when I go to compile, codeblocks freeze.
I may have made a mistake somewhere in the setup, I do not know.
The main question: ... | FROM CREATOR OF QtWorkBench:
Comment 12 by y.pagles, Jun 11, 2009
I don't think that it's going to work with any different revision than the 8.02 one.
So , the answer is 99% NO !!!
|
3,112,550 | 3,112,569 | Reference variables in C++ | Why are reference variables not present/used in C?
Why are they designed for C++?
| Because C was invented first. I don't know if they hadn't thought about references at the time (being mostly unnecessary), or if there was some particular reason not to include them (perhaps compiler complexity). They're certainly much more useful for object-oriented and generic constructs than the procedural style of ... |
3,112,602 | 3,115,063 | C++ implicit conversions and ambiguity in overloaded function call | I am facing the following problem: I have a class V (say a vector) from which I can produce two classes: CI and I (think of const_iterator and iterator).
If I have a const V then I can only produce CI (again think of iterator and const_iterator).
Essentially I would like to subsitute (const V& v) with (CI ci) and (V& ... | What you need here is explicit constructors:
struct I
{
explicit I( V& v ){}
};
struct CI
{
explicit CI( const V& v ){} //I would like to say const only
};
Too many C++ programmers overlook the explicit keyword for constructors. All unary, parameterized constructors should be explicit by default. Implicit c... |
3,112,698 | 3,112,715 | Expected a declaration (compiler error C2059) | The following is giving me a compiler error:
#include <foo.h>
#define ODP ( \
L"bar. " \ // C2059 here
L"baz.")
#define FFW (5)
What am I doing wrong?
| You forgot the line splice characters
#define ODP ( \
\
L"bar. " \
\
L"baz.")
Not sure why you put those newlines though. It all gets down to
#define ODP (L"bar. baz.")
Note that the characters must be the last ones on the line. And you cannot put a line comment (//) before them, ... |
3,112,755 | 3,113,074 | How to get nmake to push through errors ( behaviour of make -k) | I'm using cmake to generate an nmake build system using the "NMake Makefiles" generator. When I compile, even if I specify "nmake /K", the build stops after the first .cpp file which had an error. I understand that it should not compile targets who have a failed dependency, but several independent source files should... | GNU make's -k option also bails out if it gets too many errors.
Try nmake /I just like make -i
|
3,112,869 | 3,112,984 | fscanf / fscanf_s difference in behaviour | I'm puzzled by the following difference in behaviour:
// suppose myfile.txt contains a single line with the single character 's'
errno_t res;
FILE* fp;
char cmd[81];
res = fopen_s(&fp, "D:\\myfile.txt", "rb" );
fscanf(fp,"%80s",cmd); // cmd now contains 's/0'
fclose(fp);
res = fopen_s(&fp,... | From the docs on fscanf_s(), http://msdn.microsoft.com/en-us/library/6ybhk9kc.aspx:
The main difference between the secure functions (with the _s suffix) and the older functions is that the secure functions require the size of each c, C, s, S and [ type field to be passed as an argument immediately following the varia... |
3,112,933 | 3,113,052 | Function that returns a pointer to const 2-d array (C++) | I'm an intermittent programmer and seem to have forgotten a lot of basics recently.
I've created a class SimPars to hold several two-dimensional arrays; the one shown below is demPMFs. I'm going to pass a pointer to an instance of SimPars to other classes, and I want these classes to be able to read the arrays using Si... | Basically, you have three options: return the entire array by reference, return the first row by pointer, or return the entire array by pointer. Here is the implementation:
typedef double array_row[INIT_NUM_AGE_CATS];
typedef array_row array_t[NUM_SOCIODEM_FILES];
array_t demPMFs;
const array_t& return_array_by_refe... |
3,113,018 | 3,113,369 | trying to see if vector<string> has no values in map<string, string> | Just for fun I was trying to write a one line with std::find_if with boost::bind to check whether all the keys given in a vector in a map has no values, but really could not come up with a neat line of code.
Here is what I attempted
vector<string> v;
v.push_back("a");
v.push_back("2");
...
map<string, string>... | The following line of code returns true only if all elements from v are not present in m:
bool a = v.end() == std::find_if( v.begin(), v.end(), boost::bind( &str_map_t::const_iterator::operator!=, boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 ), m.end() ) );
Explanation:
Here we have two functors: ... |
3,113,055 | 3,113,128 | extraneous empty lines when reading from an ifstream | In my program, I've redirected stdout to print to a file 'console.txt'. A function writes to that file like this:
void printToConsole(const std::string& text, const TCODColor& fc, const TCODColor& bc)
{
// write the string
cout << text << "@";
// write the two color values
cout << ... | eof() status is not set until you attempt a read. You should change your read loop to do the getline() then check the fail() status instead of relying on eof(), which doesn't cover the breadth of things that can go wrong trying to read the file.
|
3,113,102 | 3,113,117 | Create a C++ container that contain the filenames within a directory | I need to generate a container of filenames within a directory in C++ and it must be cross platform compatible. Someone recommended using the WIN32_FIND_DATA data structure. Is this the best option and if so how would I implement it?
The user will not enter the filenames, but rather the C++ function will automatically ... | I'm guessing WIN32_FIND_DATA isn't your best bet for cross platform, but there are probably libraries to help provide it on linux.
Consider using boost filesystem to dump the files into a std::vector.
Something like this (adapted from here):
void show_files(const path & directory)
{
if(!exists(directory)) return;
... |
3,113,134 | 3,113,878 | Is it possible to convert vb.net source to C++? | Are there any tools converting vb.net source to C++ eg gnu C++. I know that Mono can transfer the projects to different platforms but i would rather prefer to convert the source.
Since all we know that .net uses its own binary libs not available to other complilers is there any tool at least converting vb.net to C++ .... | C, C++, or Objective-C are a totally different family of languages to VB.NET. In addition, C++/CLI (what you've called C++.NET) will never run on an iPhone in the new language obligations. I think you'd need to start from scratch.
|
3,113,139 | 3,114,231 | How to create map<string, class::method> in c++ and be able to search for function and call it? | I'm trying to create a map of string and method in C++, but I don't know how to do it. I would like to do something like that (pseudocode):
map<string, method> mapping =
{
"sin", Math::sinFunc,
"cos", Math::cosFunc,
...
};
...
string &function;
handler = mapping.find(function);
int result;
if (handler != NULL)... | Well, I'm not a member of the popular here Boost Lovers Club, so here it goes - in raw C++.
#include <map>
#include <string>
struct Math
{
double sinFunc(double x) { return 0.33; };
double cosFunc(double x) { return 0.66; };
};
typedef double (Math::*math_method_t)(double);
typedef std::map<std::string, math_... |
3,113,178 | 3,113,357 | Dealing with char buffers | As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:
char buffer[512];
sprintf(buffer, "Hello %s!", userName.c_str());
Or in Windows:
TCHAR buffer[MAX_PATH+1]; // edit: +1 added
::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), &buffer[0]);
The above sample is how I us... | I assume your interest comes about primarily from a performance perspective, since solutions like vector, string, wstring, etc. will generally work even for interacting with C APIs. I recommend learning how to use those and how to use them efficiently. If you really need it, you can even write your own memory allocator... |
3,113,229 | 3,113,259 | ofstream doesn't flush | I have the following code, running on Suse 10.1 / G++ 4.1.0, and it doesn't write to the file:
#include <fstream>
#include <iostream>
int main(){
std::ofstream file("file.out");
file << "Hello world";
}
The file is correctly created and opened, but is empty.
If I change the code to:
#include <fstream>
#includ... | If you check your file doing a cat , it may be your shell that is wrongly configured and does not print the line if there is no end of line.
std::endl adds a \n and flush.
|
3,113,413 | 3,113,431 | Converting an uint64 to string in C++ | What's the easiest way to convert an uint64 value into a standart C++ string? I checked out the assign methods from the string and could find no one that accepts an uint64 (8 bytes) as argument.
How can I do this?
Thanks
| #include <sstream>
std::ostringstream oss;
uint64 i;
oss << i;
std:string intAsString(oss.str());
|
3,113,583 | 3,113,621 | How could one implement C++ virtual functions in C | The C++ language provides virtual functions. Within the constraints of a pure C language implementation, how can a similar effect be achieved?
| Stolen from here.
From the C++ class
class A {
protected:
int a;
public:
A() {a = 10;}
virtual void update() {a++;}
int access() {update(); return a;}
};
a C code fragment can be derived. The three C++ member functions of class A are rewritten using out-of-line (standalone) code and collected by addres... |
3,113,667 | 3,113,874 | Deleting user-defined vectors - C++ | I have 2 classes, say A & B. Class B has a destructor of its own. Within class A, I have a vector of pointers to objects of class B. The vector is as follows:
vector<B*> vect;
In the destructor for class A, how do I retrieve memory? If I cycle through the vector, do I retrieve each object and use delete on every retri... | Some other posts pointed out that you're better of using smart pointers instead of pointers. If you have to use pointer for any reason whatsoever you should delete them in a loop first.
for ( std::vector<B*>::iterator it = vect.begin(); it != vect.end(); ++it)
delete (*it);
vect.clear();
edit:
If your program segf... |
3,113,904 | 3,113,972 | The python exception vs C++ exception handling | With the following code, I get the "Gotcha!" with python.
try:
x = 0
y = 3/x
except Exception:
# ZeroDivisionError
print "Gotcha!"
I think this is the equivalent C++ code, but it can't catch the exeption.
#include <iostream>
int main()
{
int x = 0;
//float y = 3.0/x;
int z = 0;
try {
z... | In C++, dividing by zero doesn't generate an exception; it causes undefined behaviour.
You must check you divisor before actually performing the division, as there is no way to know what will happen if you do actually evaluate a division expression with a zero divisor.
|
3,113,929 | 3,113,948 | How can I know the name of the exception in C++? | With Python, I could get the name of the exception easily as follows.
run the code, i.e. x = 3/0 to get the exception from python
"ZeroDivisionError: integer division or modulo by zero" tells me this is ZeroDivisionError
Modify the code i.e. try: x=3/0 except ZeroDivisionError: DO something
Is there any similar way t... | While you can't easily ask for the name of the exception, if the exception derives from std::exception you can find out the specified reason it was shown with what():
try
{
...
}
catch (const std::exception &exc)
{
std::err << exc.what() << std::endl;
}
On a side note, dividing by 0 is not guaranteed to raise ... |
3,113,962 | 3,114,214 | Question about rvalue in C++0x | I create many times I use class DataBuffer in many places in code, so it should be fast and lightweight. Moreover I use various buffer sizes, so to reduce memory allocations I wrote such template:
template<unsigned int T_buffer_size> class DataBuffer
{
public:
DataBuffer (const unsigned int &buffer_size);
... |
But because 'buffer' is a regular
pointer it takes more time to access
data stored inside it...
I think you're mistaken. Accessing an array on the heap is not necessarily slower than accessing one on the stack, e.g. The real difference will be in creating and destroying the array.
You can't really have it both wa... |
3,113,965 | 3,114,694 | Programmatically make a Header item 'hot' or 'selected' | I'm using a Win32 Header. I want to make it so that the header item I click on stays 'selected' or looks selected until I press another one. I want to avoid disabling it for aesthetic reasons.
Thanks
| If this header is part of a listview, you can provide a visual clue with ListView_SetSelectedColumn
|
3,113,997 | 3,114,098 | SVNKit like wrapper for C or C++ | Before I start building one myself;
Is there a wrapper for C or C++ which does the same thing as SVNKit?
| There is an API provided in C - see the Subversion Documentation
|
3,114,086 | 3,114,150 | Error processing : return value vs exception in C++ | In the course of asking about catching 'divide by 0' exception, I found that with C++, we can't do that. I mean, divide by 0 doesn't throw an std::exception.
Some of the hints that I found were I have to check the value, and throw the exception by self.
I say it's confusing, as I've thought that C++ adopted the except... | C++ assumes you know what you're doing, doesn't pay for things you don't ask for, and makes no assumptions about the platforms it's intended for.
If you want to divide numbers, it would be quite inefficient to mandate the compiler check the denominator and throw before dividing. (We didn't ask it to do that.) So that o... |
3,114,124 | 3,114,174 | In C/C++, are volatile variables guaranteed to have eventually consistent semantics betwen threads? | Is there any guarantee by any commonly followed standard (ISO C or C++, or
any of the POSIX/SUS specifications) that a variable (perhaps
marked volatile), not guarded by a mutex, that is being accessed
by multiple threads will become eventually consistent if it is
assigned to?
To provide a specific example, consider tw... | It's going to depend on your architecture. While it is unusual to require an explicit cache flush or memory sync to ensure memory writes are visible to other threads, nothing precludes it, and I've certainly encountered platforms (including the PowerPC-based device I am currently developing for) where explicit instruct... |
3,114,189 | 3,114,407 | Is there a simple way to forward to a member function with a matching function signature? | Is there a simple way to forward to a member function with a matching function signature?
typedef std::tr1::function<int(int,int,int,int)> TheFn;
class C
{
int MemberFn(int,int,int,int) { return 0; }
TheFn getFn() {
//is there a simpler way to write the following line?
return [this](int a,int... | Have you tried bind?
// C++0x update
struct test {
void f( int, int, int, int );
};
int main()
{
std::function<void (int,int,int,int)> fn;
test t;
fn = std::bind( &t::f, &t,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders... |
3,114,223 | 3,114,290 | How do I write a C++ dictionary to a Lua table? | I have some C++ code that interacts with some Lua code. Basically, I want to be able to get some results (in the form of a dictionary a.k.a. a collection of items) from a query message and then push them out to Lua as a table so that I can easily access all the results from Lua by using the dictionary.
Right now, I jus... | Assuming you're familiar with the Lua API in general, here's the basic process:
Create a new table on the stack (lua_newtable)
For each item in the dictionary
Push the value onto the stack
Push the key onto the stack
Call lua_settable
|
3,114,339 | 3,114,360 | Converting COFF lib file to OMF format | Is there any way to convert COFF library (lib file) to OMF library for using with C++Builder6 ? This coff is not just import library, it conatians some code.
When I try to convert it using borland's coff2omf.exe, I get 1KB file from 15KB file.
| It's fairly typical for an OMF object file to be a lot smaller than an equivalent COFF object, so what you're getting may well be valid.
If you find that it's really not, you can probably break the lib file into individual object files, disassemble the object files, re-assemble them to OMF object files, and put those t... |
3,114,376 | 3,120,737 | Can't draw triangles in OpenGL but other primitives render fine | Good afternoon,
I'm trying to learn to use a graphics library that uses OpenGL. I can draw 2D primitives (text and lines) but 3D triangles don't render. I've tried everything I can think of but as an OpenGL newcomer I've probably missed something obvious.
This code is not intended to be efficient. I'm trying to get it... | It turned out to be multiple OpenGL contexts. It wasn't setting things back before trying to draw.
|
3,114,460 | 3,114,520 | Need to make context available to C++ ostream insertion operators | For an API that I am working on, I want to allow the user to insert custom objects into an ostream, but these objects have no meaning on their own, and are too memory constrained to include an additional pointer or reference for context. (Think tens of millions of 16-/32-/48-bit objects in an embedded system with limi... | Write a custom stream manipulator that stores a reference to ddb using the iword/pword mechanism. Here is an example, you'd need to add locking around the iwork_indexes map in a multithreaded program.
class dbb
{
public:
explicit dbb(int value) : m_value(value) {}
int value() const { return m_value; }
private:
... |
3,114,577 | 3,114,620 | forward class friend declaration | Hi i have a problem, I try to do the follow, class A depends on class B and vice versa like this
class A;
class B{
A foo;
friend B A::doSomething();
};
class A {
B bar;
B doSomething;
};
The friend declartion does not work because A is an incomplete declartion. Is there any way to avoid this? (Swapp c... | What you're trying to do right now would make your classes infinitely large (as I understand, bar and foo are class member variables, hence this means that B includes A, which includes B, ...).
You could use pointers and store A* foo or B* bar in one of your classes or somehow redesign your application to avoid this ci... |
3,114,671 | 3,114,700 | Winpcap saving raw packets not from an adapter | I am trying to build an application that converts my old custom Ethernet logs (bin files) to standard winpcap style logs.
The problem is that I can't seem to find an example of how to opening a pcap_t* without using an adapter (network card). The temp.pkt has not been created.
I have looked thou the examples provided... | If all you're doing is converting your own file format to .pcap, you don't need a pcap_t*, you can just use something like:
FILE* create_pcap_file(const char *filename, int linktype)
{
struct pcap_file_header fh;
fh.magic = TCPDUMP_MAGIC;
fh.sigfigs = 0;
fh.version_major = 2;
fh.version_minor = 4;
... |
3,114,695 | 3,114,832 | Installing Allegro in Dev-C++ using their Packages | I'm trying to install Allegro in Dev-C++, and rather than do it manually, I noticed the new version was in the available packages, so that'd be easier.
Here it is in the manager.
Here it is showing itself containing the header file.
And when I try to run the simplest of Allegro programs, it doesn't recognize it.
Anyo... | You need to configure your project to reference the correct libraries. MinGW does not support auto-linking, so you'll need to configure DevCPP's project file to point MinGW at the right location.
|
3,114,776 | 3,114,989 | How to concatenate using lstrcat in Visual C++? | I would like to append two strings together so that I can rename a file using the MoveFile function. But my strings refuse to concatenate, so instead of adding "E:\" to "FILE-%s-%02d%02d%02d-%02d%02d.txt" to give me "E:\FILE-%s-%02d%02d%02d-%02d%02d.txt", it gives me just "E:\" as if nothing happened.
Here is a snippet... | Based on your casting to LPWSTR, I would assume your project is setup in Unicode mode. That means functions like lstrcpy and MoveFile are accepting pointers to strings of wchar_t not char. If you don't know what this means, you need to research the difference between Ascii and Unicode.
I would suspect that may be the s... |
3,114,806 | 3,115,007 | Creating a Lua Table from a const char ** | I have a const char ** which is going to be of varying lengths, but I want to create a Lua array from the const char **.
Myconst char ** is something like this
arg[0]="Red"
arg[1]="Purple"
arg[2]="Yellow"
I need to convert this array to a global table in Lua, but I'm not sure about how to go about this as I'm not very... | int main()
{
char* arg[3] = {
"Red",
"Purple",
"Yellow" };
//create lua state
Lua_state* L = luaL_newstate();
// create the table for arg
lua_createtable(L,3,0);
int table_index = lua_gettop(L);
for(int i =0; i<3; ++i )
{
// get the string on Lua's stack so it can be u... |
3,114,815 | 3,114,887 | What control style is this? | I want to make a control where the bottom is nice and beveled as seen here:
http://img19.imageshack.us/f/finalzh.png/
alt text http://img19.imageshack.us/f/finalzh.png/
What style must I add to my control to achieve the same look as this?
Thanks
| You could create a static control with a WS_EX_CLIENTEDGE or WS_EX_WINDOWEDGE extended style, and place it in a containing child window, which clips the top and sides so you only see the bottom bevel.
Looking at the picture, you may even not need the child window - just position the static window at -4x-4 (use GetSyste... |
3,114,949 | 3,114,978 | Anyone with experience on embedding CINT into a C++ app? | I'm talking about ROOT's CINT.
I've been developing a game in c++ which uses Python for programming the AI. As much as I love Python, and how easy it makes programming the AI (generators and FP are really sexy), it makes non trivial algorithms run so slow.
Then I remembered I read somewhere about CINT, and how it can b... | I've written classes compiled against Root, and then accessed them directly in the interpreter. That's easy, though all such classes are expected to derive from TObject. What I don't know is if that is a cint requirement or a ROOT requirement. you might be best off asking on the RootTalk CINT Support forum
To address ... |
3,114,997 | 3,586,308 | TOUGH: Dealing with deeply nested pointers in C++ | I define this structure:
struct s_molecule
{
std::string res_name;
std::vector<t_particle> my_particles;
std::vector<t_bond> my_bonds;
std::vector<t_angle> my_angles;
std::vector<t_dihedral> my_dihedrals;
s_molecule& operator=(const s_molecule &to_assign)
{
res_name = to_assign.res_name;
my_parti... | Again, this issue was answered here:
Weird Pointer issue in C++
by DeadMG. Sorry for the double post.
|
3,115,087 | 3,115,128 | Add tabs in reverse order? | By default tabs get added from right to left, so if I insert 1,2,3,4,5 then the tabs will read 5,4,3,2,1. How can I make it read 1,2,3,4,5 thanks.
http://img96.imageshack.us/i/ahhh.png/
http://img96.imageshack.us/i/ahhh.png
This is obtained from inserting Untitled Project first and Untitled 5 last.
What I would want wo... | Insert them in the correct order in the first place. If they're already there and you want to reorder them, remove them, sort them how you want, and then add them in the correct order.
|
3,115,133 | 3,115,137 | Header files included in multi .cpp files | I followed a simple example as below. But compile failed.
Could you please have a look and give me some suggestion.
vs2010 console application used.Thank you.
Error message
pgm.h(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
pgm.h(11): error C2143: syntax error : missi... | You need to namespace qualify string: std::string.
The compiler error is saying that it didn't find a type name, so it's guessing that string is an int, and continuing to try and parse your code.
Also, in one place you use fctl (fct lower-case-L) and in one place you use fct1 (fct one).
|
3,115,146 | 3,115,153 | Parsing a line with a variable number of entries in C or C++ (no boost) | I have a file containing lines of the form,
double mass, string seq, int K, int TS, int M, [variable number of ints]
688.83 AFTDSK 1 1 0 3384 2399 1200
790.00 MDSSTK 1 3 1 342 2
I need a (preferably simple) way of parsing this file without boost. If the number of... | The best way I know of to parse an ascii text file is to read it line-by-line and use strtok. It's a C function, but it'll break your input into individual tokens for you. Then, you can use the string parsing functions atoi and strtod to parse your numeric values. For the file format you specified, I'd do something ... |
3,115,147 | 3,116,917 | Creating a control like this | How could I create a control that looks like this one:
http://img195.imageshack.us/img195/4268/eeeeae.png http://img195.imageshack.us/img195/4268/eeeeae.png
I just want that small end.
Thanks
| If that's a Windows ComboBox control with a visual style applied to it, you can render its themed button wherever you like using DrawThemeBackground() and CP_DROPDOWNBUTTON.
|
3,115,188 | 3,118,879 | How does Snipping Tool do this? | I noticed that Snipping Tool (On Windows Vista / 7) has a Toolbar control. I'v used Spy++ and copied its exact styles but when I press down, it does not do like theirs. Theirs stays stuck on the clicked control, indicating that this tool is 'in use' I want to have this effect in my application.
Thanks
| I don't have a NT6 system near me ATM but I think you are just talking about the BSTYLE_CHECK toolbar button style
|
3,115,314 | 3,115,437 | Decorator vs Strategy Pattern (vs ?) to extend functionality | I've been trying to read through different implementations of Scene Graphs for 3D engine development to learn design patterns used in this domain, but unfortunately the code bases are too big for me grasp (yet, hopefully).
So, let's say we have a class Model that stores pointers to geometry, shaders, textures etc.
and... | A simple yet perfectly fine solution for this is to establish interfaces/abstact base classes for all the various things that a scene node can represent.
class Texture
{
...
};
class Geometry
{
...
};
// etc
class SceneNode
{
public:
// The following return null by default but
// can be overriden by ... |
3,115,561 | 3,116,198 | Calling shutdown and closesocket twice on same socket | In my application I call shutdown and closesocket functions twice on the same socket. I know this is not right thing to do and I have to ensure that these functions are called only once. But why don't either of these calls fail when called a second time?
If the handle of m_Socket is 1500, then what will it's value be w... | First one must distinguish two different things:
Performing operations on a socket, some of which may bring it in an unusable state.
Terminating the socket handle.
Calling shutdown with parameter 2 (which is SD_BOTH) is (1). That is, you flush all the pending out buffer, plus discard all the receive buffer. So that y... |
3,115,628 | 3,115,647 | condition execution using if or logic | when using objects I sometimes test for their existence
e.g
if(object)
object->Use();
could i just use
(object && object->Use());
and what differences are there, if any?
| They're the same assuming object->Use() returns something that's valid in a boolean context; if it returns void the compiler will complain that a void return isn't being ignored like it should be, and other return types that don't fit will give you something like no match for 'operator&&'
|
3,115,733 | 3,116,215 | Killing the focus isn't killing the focus | Here is what I'm doing. I'v created a combobox but I'm not using it for that. When I click it, it calls trackpopup and brings up a context menu. However after I'v clicked the context menu, I'd like it to close the combobox in the same way it would if you clicked anywhere (killing the focus) or selected an item from the... | I'm not sure. Need to try your code.
However I'm sure that one should not send the WM_KILLFOCUS message manually. Instead you need to set the focus to another window by calling SetFocus. The OS will automatically send messages to the window losing the focus and the new window that is gaining the focus.
|
3,116,180 | 3,150,285 | Compiling mp4v2 on Mac OS X | Anybody can help me with compiling mp4v2 on Mac OS X? I've tried configuring and compiling as per the instructions but I got a lot of errors originating from the C++ headers. The configure command was ./configure --enable-ub followed by plain make at the Terminal.
From the looks of the error messages, it seems that a... | I finally got it right:
./configure --disable-gch --enable-ub=ppc,i386,x86_64
Refer to mp4v2 issue 58.
Furthermore there are additional steps required when you use Snow Leopard to build but you also want mp4v2 to be usable under Leopard.
Thanks
|
3,116,286 | 3,116,439 | How can I programmatically launch visual studio and send it to a specific file / line? | I have a nice tidy way of capturing unhandled exceptions which I display to my users and (optionally) get emailed to myself. They generally look something like this:
Uncaught exception encountered in MyApp (Version 1.1.0)!
Exception:
Object reference not set to an instance of an object.
Exception type:
System.Nu... | You can automate Visual Studio, using for example VBScript:
filename = Wscript.Arguments(0)
lineNo = Wscript.Arguments(1)
' Creates an instance of the Visual Studio IDE.
Set dte = CreateObject("VisualStudio.DTE")
' Make it visible and keep it open after we finish this script.
dte.MainWindow.Visible = True
dte.UserCon... |
3,116,509 | 3,116,544 | Is there any advantage for Java over C# | This question may sound silly.. but my intention is to understand advantages of Java over all other programming languages ??
I guess c# is more or less similar to java.. also c# is derived from c++ which inturn is derived from C..
So learning which language is more easier or helpful in understanding concepts & deve... |
Java is supported on most platforms, whereas C# mostly runs on other platforms but is not supported by Microsoft.
There are more external tools (like static code analyzers) for Java than for C#, although it is a matter of time before this goes the other way. When a scientific study is done into VM optimization or erro... |
3,116,516 | 3,116,583 | snmp agent libraries for C/C++? | I have to implement a performance statistics MIB for a linux based device and I am looking for a good agent development library. I came across net-snmp and agent++ libraries. I am looking for easier to understand and robust library. Which is the best library if usability and robustness is main criteria?
| I have used net-snmp. It is robust and works well. The API is in C but quite simple to encapsulate. More than a library and APIs it is a well tested set of tools to handle SNMP. A reference. I don't know agent++. It is perhaps simpler to deal with as it seems to be a C++ lib.
my2c
|
3,116,563 | 3,116,716 | Doxygen: multiple \mainpage blocks in a C++ project | I wasn't able to determine what the behavior of doxygen is regarding the \mainpage section, in two cases:
If you specify no \mainpage section, does it use any other page instead and if so how is this picked?
What if two files both specify a \mainpage section?
| The \mainpage command specifies content used to customise the index page, so if you lack one it's just a blank page with the normal Doxygen header and footer.
I think the safest thing to say about having multiple \mainpage commands is that it is undefined in the classic sense of yielding unpredictable results depending... |
3,116,626 | 3,117,062 | Recursively Insert Element Into A Binary Tree | So I finished my List exercise and went ahead with Binary Trees. My code thus far:
Tree.h
#include "Node.h"
class Tree
{
private:
int mCount;
Node *root;
public:
Tree();
~Tree();
void insert(int, Node *);
};
Tree.cpp
void Tree::insert(int data, Node *node)
{
if( root == 0 )
{
No... | A few points:
First, don't use Node**. That err "uglifies" your code. Use Node*& instead (see answers here) if you really need to.
Second, you do not need a recursive call (unless you want to use one).
Non-recursive insert method:
void Tree::insert(int data)
{
if(!root)
{
root = new Node(data); // Nod... |
3,116,670 | 3,116,686 | In C and C++, can I use macros definitions containing space? | I am wondering if macro definitions can contain space. Let's take for example this code:
#define MACRO_PARAM int param2
int function(int param1, MACRO_PARAM)
{
return param1+param2;
}
This works ok with Visual Studio 8 and gcc 3.4.5 (mingw). For me this is good enough for the moment but is this standard? or can I... | You'll need to end each line of the definition with a \ (except the last).
|
3,116,980 | 3,116,995 | Do I have to set pointer to nullptr in destructor? |
Possible Duplicate:
Is it worth setting pointers to NULL in a destructor?
Do I have to do something like so:
~MyClass()
{
delete[] my_data_;
my_data_ = nullptr;//DO I HAVE TO WRITE THIS LINE?
}
Thank you.
| delete[] my_data_;
Should do all you need, after you use this then setting my_data_ to nullptr is not necessary.
|
3,117,462 | 3,117,594 | Polymorphic Enum in C++ | I have these Enum declarations:
enum MessageType{
REQ_LOGIN,
REQ_GET_FIELD,
RES_LOGIN,
RES_GET_FIELD
}
enum Request{
REQ_LOGIN,
REQ_GET_FIELD
};
enum Respond{
RES_LOGIN,
RES_GET_FIELD
};
Obviously I'm repeating elements in Enum's. Is there any way to prevent this?
EDIT:
I'm ... | Why not try something like this?
enum MainType{
REQUEST,
RESPONSE
};
enum SubType{
LOGIN,
GET_FIELD
};
class Message {
MainType type;
SubType sub_type;
...
};
|
3,117,478 | 3,117,541 | strange double pointer null check | Is this a valid null check on a DOUBLE pointer parameter passed in a function
if (!pdblValue) return E_POINTER;
| In C++ the "if" statement uses a boolean expression. If it is true, it executes the part inside the conditional block. If it is false, it doesn't.
pdblValue is of type pointer. Negating it (!pdblValue) will give a long integer expression which is different to zero if the value of the pointer was NULL, and zero otherwis... |
3,117,619 | 3,117,781 | Get/set combo-box text in Win32 (not MFC) | I can use GetDlgItemText to get the text from a control, but I want to clear the selection and SetDlgItemText(IDC_CTRL,_T("")); doesn't work. What is the right approach here?
| Assuming I'm reading the MSDN documentation for the Combo Boxes and the CB_SETCURSEL message right, you can send a CB_SETCURSEL message to the combo box with the wParam(In this case it will be the index of the string in the combo box) being set to -1. This should then clear the selection.
You can also decide to use the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.