question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,423,625 | 2,423,636 | C# :- P/invoke signature | I have a dll with following signature in C++. It is working in c++;
void Decompress(unsigned char *in,int in_len,unsigned char * out,
unsigned *o_len,int *e);
Description of parameter
*in : It is byte array passed to
function.
in_len : Length of bytes in first parameter.
*out : This would be the output as byte a... | static extern void Decompress(
byte[] input,
int in_len,
byte[] output,
ref int o_len,
out int e);
|
2,423,678 | 2,423,918 | Block Access to physical address on Windows | I'm accessing my memory-mapped device via a device-specific physical memory on the PC.
This is done using a driver that maps a specific physical address to a pointer in linear memory on my process address space.
I wanted to know if there is any way I can obtain a block the specific physical address and prevent other pr... | Youd driver must do the job by exposing a service (DeviceIoContro) that checks if a range is already mapped, maps it if it's free, and records the reservation. Also a service thar frees the reserver area and unmap it. And of course you should free all the areas related to a particular handle on close. Unfortunately the... |
2,423,816 | 2,424,094 | Is it possible in C++ to inherit operator()? | I'm writing some examples of hash functions for hash_map. If I use a hash_map defined by my compiler, I need to define Comparer in Hasher. I know that it's better to use tr1::unordered_map but in my application it's important to set minimum number of buckets rather big and define mean bucket_size - a condition to grow.... | Classes are scopes for name lookup and derived classes are (still for the purpose of name lookup) nested in their base class.
When a name is searched (and operator() is such a name), the search stop at the first scope which contains it. It doesn't continue in inclosing scopes to find potential overload.
Here, one sear... |
2,423,974 | 2,424,365 | protobuf-net - problem with deserializing on C++ side :( | I am using ProtoBuf-Net in my .NET application to serialize the following : (in .proto format)
message ProtoScreenBuffer {
optional int32 MediaId = 1;
optional bytes Data = 2;
optional bool LastBuffer = 3;
optional int64 StartTime = 4;
optional int64 StopTime = 5;
optional int32 Flags = 6;
optional int32 BufferSubType ... | Hmm... the only thing in there that I might expect to be messy is the Guid (I recently realised that my encoding of this appears to be fairly crazy-endian). So I think that should work fine, give or take some messy code to decipher the Guid.
To rule out an encoding error, what I would suggest is:
serialize the data vi... |
2,423,995 | 2,424,007 | copy a map into another map | I have a map like this:
map<prmNode,vector<prmEdge>,prmNodeComparator> nodo2archi;
I need to have an identical copy of this map. How is the fast way to make this?
I have tried this:
map<prmNode,vector<prmEdge>,prmNodeComparator> copiamap( nodo2archi );
but it doesn't work. The copiamap is empty.
Thank you very much
| Use the map's copy constructor:
map<prmNode,vector<prmEdge> > nodo2archi;
map<prmNode,vector<prmEdge> > acopy( nodo2archi ) ;
This code, which copies a map, prints the same size (1) for each.
#include <map>
#include <iostream>
using namespace std;
typedef map <int, int> MapType;
int main() {
MapType m1;
m1.... |
2,424,066 | 2,424,116 | Implicit conversion between 3rd party types | There are two classes: A and B. There are algorithms for converting from type A to type B and back. We cannot touch the source code of them. Can I write an implicit conversion between the two types?
Example code which should work:
B CalculateSomething(double x)
{
A a(x);
a.DoSomethingComplicated();
return a... | No, I don't think so. Implicit conversion is usually coded with an overloaded operator. It is done for base types too. As you can't modify A and B code there is no way to tell the compiler how to do that. Your snippet will get an error.
You have to do explicit conversion. Just
return helper.convertToB(a);
my2c
|
2,424,138 | 2,424,185 | Portable way to get file size in C/C++ | I need to determin the byte size of a file.
The coding language is C++ and the code should work with Linux, windows and any other operating system. This implies using standard C or C++ functions/classes.
This trivial need has apparently no trivial solution.
| Using std's stream you can use:
std::ifstream ifile(....);
ifile.seekg(0, std::ios_base::end);//seek to end
//now get current position as length of file
ifile.tellg();
If you deal with write only file (std::ofstream), then methods are some another:
ofile.seekp(0, std::ios_base::end);
ofile.tellp();
|
2,424,323 | 2,426,010 | How to wait for a cloned child process of an invoked process to exit? | I have a program which needs to invoke a process to perform an operation and wait for it to complete the operation. The problem is that the invoked process clones itself and exits, which causes the wait api to return when the process exits. How can I wait for the cloned process to finish execution and return?
I am usin... | +1 for using job objects ;)
Assuming the process that you're running isn't spawning the cloned version of itself in such a way that it breaks out of the job...
You should be able to simply monitor the job events and act on JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO (see JOBOBJECT_ASSOCIATE_COMPLETION_PORT and SetInformationJob... |
2,424,505 | 2,424,672 | Is qsort thread safe? | I have some old code that uses qsort to sort an MFC CArray of structures but am seeing the occasional crash that may be down to multiple threads calling qsort at the same time. The code I am using looks something like this:
struct Foo
{
CString str;
time_t t;
Foo(LPCTSTR lpsz, time_t ti) : str(lpsz), t(ti)
{
... | Your problem doesn't necessarily have anything to do with thread saftey.
The sort callback function takes in pointers to each item, not the item itself. Since you are sorting Foo* what you actually want to do is access the parameters as Foo**, like this:
int __cdecl SortProc(const void* elem1, const void* elem2)
{
... |
2,424,563 | 2,424,897 | C++ operator + and * non-const overloading | I have the following tricky problem: I have implemented a (rather complicated) class which represents mathematical functions in a multiwavelet basis. Since operations like +, - and * are quite natural in this context, I have implemented overloaded operators for this class:
FunctionTree<D> operator+(FunctionTree<D> &inp... | You can use proxies instead of real values, and proxies can be constant, as they are not going to be changed. Below is a small example of how it might look like. Be aware that all the temporaries are still going to be created in that example but if you want to be smart, you can just save the operations, not the actual ... |
2,424,795 | 19,171,230 | Building multiple binaries within one Eclipse project | How can I get Eclipse to build many binaries at a time within one project (without writing a Makefile by hand)?
I have a CGI project that results in multiple .cgi programs to be run by the web server, plus several libraries used by them. The hand-made Makefile used to build it slowly becomes unmaintainable. We use Ecli... | Solution for this described there: http://tinyguides.blogspot.ru/2013/04/multiple-binaries-in-single-eclipse-cdt.html.
There is an excerpt:
Create a managed project (File > New C++ Project > Executable)
Add the source code containing multiple main() functions
Go to Project > Properties > C/C++ General > Path & Symbol... |
2,424,807 | 2,424,825 | Most common or vicious mistakes in C# development for experienced C++ programmers | What are the most common or vicious mistakes when experienced C++ programmers develop in C#?
|
the difference between struct and class in the two
the difference between a using alias and a typedef
when do my objects get collected? how do I destroy them now?
how big is an int? (it is actually defined in C#)
where's my linker? (actually, Mono does have a full AOT linker for some scenarios)
|
2,424,836 | 2,425,177 | Exceptions are not caught in GCC program | My project contains shared library and exe client. I found that my own exception class thrown from the library is not caught by client catch block, and program terminates with "terminate called after throwing an instance of ..." message. Continuing to play with the project, I found that any exception of any type is not... | Both the client .exe and the shared library should to be linked with libgcc in order to throw across shared library boundaries. Per the GCC manual:
... if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ or GCJ driver, as appropriate for the languages used in the p... |
2,424,883 | 2,425,080 | Visual Studio 2008 c++ Smart Device Platforms | Well i wrote a c++ app for a Windows CE device and selected the platform (from the sdk that came with the CD) for it, if i open the project file it says Platform Name="IEI_PXA270_E205 (ARMV4I)"
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="B... | ok had to try i turned UAC off and restarted my pc installed the SDK and tada it works... gotta love UAC...?
|
2,424,908 | 2,424,953 | How to decode string on c++ | How to decode string in c++.
for example utf8 to cp1251 or koi8-r to utf8
| C++ has no native support for performing such conversions. You could look at ICU library.
ICU is a mature, widely used set of C/C++ and Java libraries providing Unicode and Globalization support for software applications. ICU is widely portable and gives applications the same results on all platforms and between C/C++... |
2,424,967 | 2,424,973 | virtual function issue | I am using native C++ with VSTS 2008. A quick question about virtual function. In my sample below, any differences if I declare Foo as "virtual void Foo()" or "void Foo()" in class Derived? Any impact to any future classes which will derive from class Derived?
class Base
{
public:
Base()
{
}
virtual v... | No difference. But for the sake of readbility I always keep the virtual whenever it is.
|
2,425,212 | 2,425,228 | Exporting functions from a C# class library | How would I export functions defined in a C# class library, while enabling them to be imported to and called from an unmanaged C++ application/DLL ?
| Strictly speaking, you can't just export functions as you would in a classic .dll, as .NET .dll's aren't really .dll's at all. Your only three options are:
Use managed C++
Expose your C# classes as COM objects and consume them from your C++ code
Host the .NET runtime in your C++ project and interact with your C# class... |
2,425,277 | 2,425,349 | Visual Studio 2010 and std::function | I have this code:
#include <iostream>
#include <functional>
struct A
{
int operator()(int i) const {
std::cout << "F: " << i << std::endl;
return i + 1;
}
};
int main()
{
A a;
std::tr1::function<int(int)> f = std::tr1::ref(a);
std::cout << f(6) << std::endl;
}
The aim is to pass t... | I think i found the reason. This is what TR1 3.4/2 says about result_of<T(A1, A2, ..., AN)>::type, used in the determination of the return type of reference_wrapper<T>::operator():
The implementation may determine the type member via any means that produces the exact type of the expression f(t1, t2, ..., tN) for the g... |
2,425,304 | 2,425,527 | Visual Studio dialog editor not using square dimensions | So, I'm busy making a model viewer, I'm trying to get my dialog properly setup, and get my openGL view ports squared ( I'm using picture box controls for it ), one big problem. Visual studio doesn't allow me to set the the size manually, I can't see the actual pixel size. I can only see it in the bottom right corner of... | The resource editor works in DLU ( Dialog Logical Unit), not in pixels.
see this other question (and links included) : MFC Dialog Size Question
Max.
|
2,425,452 | 2,426,534 | Polynomial operations using operator overloading | I'm trying to use operator overloading to define the basic operations (+,-,*,/) for my polynomial class but when i run the program it crashes and my computer frozes.
Update4
Ok. i successfully made three of the operations, the only one left is division.
Here's what I got:
polinom operator*(const polinom& P) const
{
... | As to getting the function correctly adding up polynomials, I'd recommend this simple logic:
polinom operator+(const polinom& P) const //fixed prototype re. const-correctness
{
polinom Result;
std::list<term>::const_iterator //fixed iterator type
i = poly.begin(), j = P.poly.begin();
while (i != po... |
2,425,469 | 2,425,489 | Isn't this legacy code which returns a local char array wrong? | I came across some legacy code that contains a function like this:
LPCTSTR returnString()
{
char buffer[50000];
LPCTSTR t;
/*Some code here that copies some string into buffer*/
t = buffer;
return t;
}
Now, I strongly suspect that this is wrong. I tried calling the function and it does return th... | Your code is exhibiting undefined behaviour - in this case, the UB is that it appears to "work". If you want the array stored on the heap, you need to allocate it with new[]. The caller of the function will then be responsible for deleting it via the pointer the function returns.
|
2,425,503 | 2,425,525 | C++ with fstream or database | I am trying to implement a image recognition program in C++.
I had completed the extracted of feature, now trying to save the large amount of numbers. I had 2 implementation in mind, one is to save the data into binary files, to reduce the overhead of computation, or I can use database to keep the information.
Binary... | You could use SQLite. It basically gives to database-style access to local files. You can also create in-memory databases with it, but i do not know if it is possible to persist those.
Also, the best choice here heavily depends on your access patterns. If it is just sequenctial write and sequential read, then binary fi... |
2,425,728 | 2,425,749 | delete vs delete[] operators in C++ | What is the difference between delete and delete[] operators in C++?
| The delete operator deallocates memory and calls the destructor for a single object created with new.
The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].
Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined b... |
2,425,745 | 2,425,851 | Which dynamic libraries on OS X can be taken for granted? | If I want to make an OS X program as self-contained as possible to ease installation, what dynamic libraries can I expect everyone or most people to have? If I know that, I won't have to compile static libraries for everything.
| All functions listed in Single UNIX Specification V3 are available.
Obviously, all Cocoa frameworks are available as well. The exact contents depend on OS version.
|
2,425,759 | 2,425,957 | Do I need to cast the result of strtol to int? | The following code does not give a warning with g++ 4.1.1 and -Wall.
int octalStrToInt(const std::string& s)
{
return strtol(s.c_str(), 0, 8);
}
I was expecting a warning because strtol returns a long int but my function is only returning a plain int. Might other compilers emit a warning here? Should I cast ... | You may need the -Wconversion flag to turn these warnings on. However, it won't warn about long -> int, since they are the same size with GCC (the value won't change because of the conversion). But it would if you convert for example long -> short
I suppose simply doing a cast would not be recommended, since that would... |
2,425,906 | 2,425,923 | Operator overloading outside class | There are two ways to overload operators for a C++ class:
Inside class
class Vector2
{
public:
float x, y ;
Vector2 operator+( const Vector2 & other )
{
Vector2 ans ;
ans.x = x + other.x ;
ans.y = y + other.y ;
return ans ;
}
} ;
Outside class
class Vector2
{
public:
... | The basic question is "Do you want conversions to be performed on the left-hand side parameter of an operator?". If yes, use a free function. If no, use a class member.
For example, for operator+() for strings, we want conversions to be performed so we can say things like:
string a = "bar";
string b = "foo" + a;
wher... |
2,426,235 | 2,426,454 | Replacing a window's control with another at runtime | I've got a handle to a window and its richEdit control. Would I be able to replace the said control with one of my own ? I'd like it to behave as the original one would, i.e., be a part of the window and suchlike.
I'll elaborate the scenario further - I'm currently disassembling an application one of whose features is ... | That sounds way too complex. Just replace its WndProc(GWL_WNDPROC), forwarding nothing, and then invalidate the HWND. That will force a redraw (WM_PAINT) which you can then capture. The owner probably wouldn't even notice (unless they had it hooked as well, of course)
|
2,426,252 | 2,429,571 | Which Singleton library in BOOST do you choose? | Google results say there are more than 1 singleton template/baseclass in boost, which one do you suggest?
| You shouldn't use the singletons in boost, they are for internal purpose only (see the "detail" folders of separate libes). That's why you don't have a Singleton library (yet) exposed on the boost website.
A singleton class is very simple to implement but there are many variants that are useful in specific cases so you... |
2,426,330 | 2,429,767 | Uses of a C++ Arithmetic Promotion Header | I've been playing around with a set of templates for determining the correct promotion type given two primitive types in C++. The idea is that if you define a custom numeric template, you could use these to determine the return type of, say, the operator+ function based on the class passed to the templates. For examp... | This is definitely useful -- we use these sorts of things in the math library that I work on for correctly typing intermediate values in expressions. For example, you might have a templated addition operator:
template<typename Atype, typename Btype>
type_promote<Atype, Btype>::type operator+(Atype A, Btype B);
This w... |
2,426,512 | 2,436,213 | MP3 codec for WAV files | Wav files support different encodings, including mp3. Is there a C/C++ library that would produce mp3-encoded wav files from uncompressed wav? If not, what would be the best place to start to implement one?
|
The best way indead to use Lame (if you do not afraid patent issues). You can use the both sources for lame and lame_enc.dll. Using the lame_enc.dll is more easier.
As for RIFF-WAV container: it is simply to create RIFF-WAV files according to RIFF-WAV specification.
There are another possibilities. For example using A... |
2,426,562 | 4,815,791 | How is the Windows menu in a MFC C++ app populated | One of the standard menus provided to a Document/View app under MFC is the Windows menu. It provides things like tiling and cascading windows, and appends an enumerated list of currently available views at the end of the menu. Problem is, sometimes it doesn't and I'd like to know why. More specifically, I'd like to ... | Updating the menu and the window title are handled separatelly in two methods.
CFrameWnd::OnUpdateFrameMenu(..) actualises only the frame menu,
CFrameWnd::OnUpdateFrameTitle(..) refreshes only the name of the frame.
I think there is somewhere a wrong call order and updating the title will be later than updating the m... |
2,426,566 | 2,426,601 | Is this a valid Copy Ctor ? | I wonder if there is something wrong with the copy constructor function below?
class A
{
private:
int m;
public:
A(A a){m=a.m}
}
| Two things:
Copy constructors must take references as parameters, otherwise they are infinitely recursive (in fact the language won't allow you to declare such constructors)
It doesn't do anything the default copy ctor doesn't do, but does it badly - you should use initialisation lists in a copy ctor wherever possible... |
2,426,720 | 2,429,446 | LIBPATHS not being used in Makefile, can't find shared object | I'm having trouble getting a sample program to link correctly (in this case against the ICU library). When I do 'make', everything builds fine. But when I run it, it says it can't find one of the .so's. I double checked they're all installed in /usr/local/lib. What I discovered was it was looking in /usr/lib. If I syml... | Your LIBPATHS tells the linker where to find the library when linking to resolve symbols.
At runtime, you need to tell the loader where to find the library. It doesn't know about what happened at compile time. You can use the LD_LIBRARY_PATH variable as mentioned above, or check into /etc/ld.so.conf and it's friends.... |
2,426,807 | 2,426,979 | C++ Mock/Test boost::asio::io_stream - based Asynch Handler | I've recently returned to C/C++ after years of C#. During those years I've found the value of Mocking and Unit testing.
Finding resources for Mocks and Units tests in C# is trivial. WRT Mocking, not so much with C++.
I would like some guidance on what others do to mock and test Asynch io_service handlers with boost.
F... | As you've probably found already, there's much less help for mocking in C++ than in C# or Java. Personally I tend to write my own mocks as and when I need them rather than use a framework. Since most of my designs tend to be heavy on the interfaces this isn't especially difficult for me and I tend to build up a 'mock l... |
2,426,813 | 2,428,604 | Symbian c++ - how to put own static lib | I'm using carbide c++. What to put in .mmp file to link some static library in path: camerawrapper\epoc32\release\armv5\lib from root?
| STATICLIBRARY foo.lib
assuming your EPOCROOT/SDK root is camerawrapper, you are building for the armv5 target and there's such a static library built with TARGETTYPE lib, not e.g. a static interface DLL.
|
2,426,944 | 2,427,072 | Code Complete 2ed, composition and delegation | After a couple of weeks reading on this forum I thought it was time for me to do my first post.
I'm currently rereading Code Complete. I think it's 15 years since the last time, and I find that I still can't write code ;-)
Anyway on page 138 in Code Complete you find this coding horror example. (I have removed some o... | It's pay now vs. pay later.
You can write the delegation and wrapper functions up front (pay now) and then have less work changing the innards of employee.IsZipCodeValid() later. Or, you can tunnel through to IsZipCodeValid by writing employee.GetAddress().GetZipCode().IsValid(); everywhere you need it in the code, bu... |
2,426,967 | 2,427,025 | Reusing a vector in C++ | I have a vector declared as a global variable that I need to be able to reuse. For example, I am reading multiple files of data, parsing the data to create objects that are then stored in a vector.
vector<Object> objVector(100);
void main()
{
while(THERE_ARE_MORE_FILES_TO_READ)
{
// Pseudocode
... | vector<Object> objVector(100);
int main()
{
while(THERE_ARE_MORE_FILES_TO_READ)
{
// Pseudocode
ReadFile();
ParseFileIntoVector();
ProcessObjectsInVector();
/* Here I want to 'reset' the vector to 100 empty objects again */
objVector.clear();
objVector.resize(100);
}
}
... |
2,427,034 | 2,427,871 | easy hex/float conversion | I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:
http://docs.python.org/library/stdtypes.html#additional-methods-on-float
Is there an easy way in C++ to to somet... | From the link you provided in your question (Additional Methods on Float):
This syntax is similar to the syntax
specified in section 6.4.4.2 of the
C99 standard, and also to the syntax
used in Java 1.5 onwards. In
particular, the output of float.hex()
is usable as a hexadecimal
floating-point literal in C... |
2,427,103 | 3,996,525 | Qt: How to force a hidden widget to calculate its layout? | What I am trying to do is render a qwidget onto a different window (manually using a QPainter)
I have a QWidget (w) with a layout and a bunch of child controls. w is hidden. Until w is shown, there is no layout calculations happening, which is expected.
When I call w->render(painter, w->mapToGlobal(QPoint(0,0)), I ge... | Forcing a layout calculation on a widget without showing it on the screen:
widget->setAttribute(Qt::WA_DontShowOnScreen);
widget->show();
The show() call will force the layout calculation, and Qt::WA_DontShowOnScreen ensures that the widget is not explicitly shown.
|
2,427,305 | 2,427,343 | Alternatives to C++ Reference/Pointer Syntax | What languages other than C and C++ have explicit reference and pointer type qualifiers? People seem to be easily confused by the right-to-left reading order of types, where char*& is "a reference to a pointer to a character", or a "character-pointer reference"; do any languages with explicit references make use of a l... | Stroustrup is on record as saying the declaration syntax is "an experiment that failed". Unfortunately, C++ has to go along with it for C compatibility. The original idea was that a declaration looked like a use, for example:
char * p; // declare
* p; // use (dereference)
but this quickly falls apart for more ... |
2,427,739 | 2,427,779 | Please explain syntax rules and scope for "typedef" | What are the rules? OTOH the simple case seems to imply the new type is the last thing on a line. Like here Uchar is the new type:
typedef unsigned char Uchar;
But a function pointer is completely different. Here the new type is pFunc:
typedef int (*pFunc)(int);
I can't think of any other examples offhand but I hav... | Basically a typedef has exactly the same syntax as an object declaration except that it is prefixed with typedef. Doing that changes the meaning of the declaration so that the new identifier declares an alias for the type that the object that would have been declared, had it been a normal declaration, would have had.
A... |
2,428,304 | 2,437,701 | CIELab Colorspace conversion | Is there a canonical colorspace conversion library? I can't find any pre-existing solutions. Is CIELab conversion is too obscure?
| It is not obscure, I have done it myself recently from RGB to CIELAB.
Look at the source of OpenCV there is a lot of color convesrion functions.
File is: ../src/cv/cvcolor.cpp
Have a look at the function icvBGRx2Lab_32f_CnC3R for example. This is probably what are you looking for.
|
2,428,355 | 2,428,385 | Access modifiers in Object-Oriented Programming | I don't understand Access Modifiers in OOP. Why do we make for example in Java instance variables private and then use public getter and setter methods to access them? I mean what's the reasoning/logic behind this?
You still get to the instance variable but why use setter and getter methods when you can just make your ... | This is called data or information hiding.
Basically, you don't want a user (read: other programmer, or yourself) poking in the internals of your class, because that makes it very hard to change things.
On the other hand, a clean separation between interface and implementation (theoretically) makes it easy to change so... |
2,428,404 | 2,428,457 | Tricky interview subject for C++ | Given the code below, how would you create/implement SR.h so that it produces the correct output WITHOUT any asterisks in your solution?
I got bummed by this question. I would like to know some of the different approaches that people use for this problem.
#include <cstdio>
#include "SR.h"
int main()
{
int j = 5;
... | SR is acting as a captured-variable-restorer. When it goes out of scope it restores some value that it previously captured.
The constructor will do two things: capture a reference, and capture the value of that reference. The destructor will restore the original value to that reference.
class SR
{
public:
SR(int& v... |
2,428,421 | 2,428,464 | Qt Should I derive from QDataStream? | I'm currently using QDataStream to serialize my classes. I have quite a few number of my own classes that I serialize often. Should I derive QDataStream to create my own DataStream class? Or is there a better pattern than this? Note that these custom classes are used by many of our projects, so maybe doing so will make... | That would get out of control very quickly. A better approach is to define operator<< and operator>> between QDataStream and your class. Even cleaner might be to simply have serialization methods on your classes that read/write to a QDataStream (so that you would call for example, obj->serialize(myStream)).
|
2,428,631 | 2,428,670 | Handwritten linked list is segfaulting and I don't understand why | Hi I was working on a bit of fun, making an interface to run gnuplot from within c++, and for some reason the my linked list implementation fails.
The code below fails on the line plots->append(&plot). Stepping through the code I discovered that for some reason the destructor ~John() is called immediately after the con... | The statement:
John();
Just constructs a new nameless John which is created and immediately destroyed. There is no way (in the current version of C++) to call a constructor from another constructor or on an already constructed object.
This means that the plots member of your John called k is never being initalized, h... |
2,428,684 | 2,428,741 | How to implement pure virtual function in C++ | I think the implementation of virtual function is talked about a lot. My question is what about pure virtual function? However it is implemented? In virtual table, how to tell it is a pure or non-pure? What the difference between pure virtual function and virtual function with implementation?
| There is no usually no implementation difference between pure and non-pure virtual functions. Provided a pure-virtual function is defined, it acts like any other virtual function. If it is not defined, it only causes a problem if it is explicitly called.
There are two major differences in behaviour, but there is usuall... |
2,428,765 | 2,428,809 | Why the size of a pointer is 4bytes in C++ | On the 32-bit machine, why the size of a pointer is 32-bit? Why not 16-bit or 64-bit? What's the cons and pros?
| Because it mimics the size of the actual "pointers" in assembler. On a machine with a 64 bit address bus, it will be 64 bits. In the old 6502, it was an 8 bit machine, but it had 16 bit address bus so that it could address 64K of memory. On most 32 bit machines, 32 bits were enough to address all the memory, so that... |
2,428,868 | 2,428,893 | How to declare a pointer to a variable as a parameter of a function in C++? | I have a function that takes a const D3DVECTOR3 *pos, but I have no reason to declare this beforehand. The most logical solution to me was using new:
Function(
//other parameters,
new D3DXVECTOR3(x, y, 0));
but I don't know how I would go about deleting it, beign intitialized in a function. My next thought w... | It's not possible to directly invoke the address-of operator to the temporary (MSVC will tell you that this is not Standard C++ at higher warning levels, too). Except you may do
Function(
//other parameters,
&(D3DXVECTOR3 const&)D3DXVECTOR3(x, y, 0));
But this is disgusting. Just declare a local variable and pass its ... |
2,429,000 | 2,429,014 | Can't write a binary file | I have the following piece of code in C++.
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ofstream output("Sample.txt", ios::out | ios::binary);
for(int i = 0; i < 10; i++)
{
output<<arr[i];
}
Now the Sample.txt is like this:
12345678910
Isn't the "Sample.txt" supposed to be in binary? Why doesn't it convert everyth... |
Isn't the "Sample.txt" supposed to be in binary?
No. What std::ios::binary does is to prevent things like the translation of '\n' from/to the platform-specific EOL. It will not skip the translation between the internal representation of the data bytes and their string translation. After all, that's what streams are a... |
2,429,301 | 2,429,383 | Best way to create an application-icon in visual studio c++ | In Visual studio I can draw 13 different application-icons in different resolutions and color depths. But do I have to do this, or is there a way to automatically produce all low-res icons from one single hi-res icon?
| The easiest way is to use a program such as IcoFX or GenIconXP to do it for you from a higher resolution image. If you're using VS2008 there's also IconWorkshopLite
|
2,429,485 | 2,430,406 | How do I parse end-of-line with boost::spirit::qi? | Shouldn't a simple eol do the trick?
#include <algorithm>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
using boost::spirit::ascii::space;
using boost::spirit::lit;
using boost::spirit::qi::eol;
using boost::spirit::qi::phrase_parse;
struct fix : std::unary_function<char, void> {
fix(s... | You are using space as the skipper for your calls to phrase_parse. This parser matches any character for which std::isspace returns true (assuming you're doing ascii based parsing). For this reason the \r\n in the input are eaten by your skipper before they can be seen by your eol parser.
|
2,429,610 | 2,429,627 | C++ Managing Shared Object's Handle issues | Is there best practice for managing Object shared by 2 or more others Object. Even when running on different thread?
For example A is created and a pointer to it is given to B and C.
ObjA A = new ObjA();
B->GiveObj(A);
C->GiveObj(A);
Now how can I delete objA?
So far what I though about is A monitor how many ref there... | The best option is to use a smart pointer implementation such as Boost's shared_ptr.
This allows you to pass around the pointers as needed, without worrying about the deletion.
Edit:
I just realized you had the signal/slot tag added. If by chance you're using Qt, you probably want QSharedPointer (or similar) instead ... |
2,429,618 | 2,429,636 | Passing values through files in C++ | I'm still pretty new to C++, and I've been making progress in making my programs not look like a cluster-bleep of confusion.
I finally got rid of the various error messages, but right now the application is crashing, and I have no idea where to start. The debugger is just throwing a random hex location.
Thank you in... | In your program, pc is not a struct - it's a pointer to the struct (because of *). You don't initialize it to anything - it points at some bogus location. So, either initialize it in the first line of main():
pc = new Value();
Or make it a non-pointer by removing *, and use . instead of -> for member access throughout... |
2,429,784 | 2,429,818 | Windows service and mingw | Is there possibility to compile windows service using only mingw c++ compiler and library?
I assume that it is possible to use compiler with Visual Studio standard library and means, but want to do to this almost fully opensourced.
Any experience?
| Since you can build programs with the Windows Platform SDK (or whatever it's called today) using MinGW, you can build Win32 services.
Services are just Win32 programs with some specific protocols used to register them with the system and interact with the operating system's service controller.
|
2,430,039 | 2,430,093 | One template specialization for multiple classes | Let's assume we have a template function "foo":
template<class T>
void foo(T arg)
{ ... }
I can make specialization for some particular type, e.g.
template<>
void foo(int arg)
{ ... }
If I wanted to use the same specialization for all builtin numeric types (int, float, double etc.) I would write those lines many time... | You could use std::numeric_limits to see whether a type is a numeric type (is_specialized is true for all float and integer fundamental types).
// small utility
template<bool> struct bool2type { };
// numeric
template<typename T>
void fooImpl(T arg, bool2type<true>) {
}
// not numeric
template<typename T>
void fooIm... |
2,430,165 | 2,431,307 | Is stdin limited in length? | Are there any stdin input length limitations (in amount of input or input speed)?
| It probably depends on the stdin driver !
stdin (as a concept) has no limitation.
I expect that kernel developers (of any systems) have made some design choices which add limitations.
|
2,430,195 | 2,430,219 | one question about iostream cout in C++ | In such code, what it is called, \\n like this?
cout<<"Hello\\n \'world\'!";
What's the basic rule about such characters?
| \n is an escape sequence to print a new line. Now if you want to print a \n ( a literal \n that is a slash followed by an n) on the screen you need to escape the \ like \\. So \\n will make \n print on the screen.
|
2,430,409 | 2,430,433 | Is this a good way to manage initializations of COM? | I'm very new to anything involving Component Object Model, and I'm wondering if this method of managing calls to CoInitalize/CoUninitalize makes sense:
COM.hpp:
#pragma once
namespace WindowsAPI { namespace ComponentObjectModel {
class COM
{
COM();
~COM();
public:
static void Setup();
};
}}
COM.cpp:
#in... | I don't believe that static storage variables are destroyed on dll unload, but you shouldn't be using this from a dll anyway.
I generally do something similar, but I don't bother with a function static, I just make the ctor/dtor public and drop an instance in my main():
int WINAPI wWinMain(...) {
Com::ComInit comIn... |
2,430,730 | 2,467,318 | SQLite file locking and DropBox | I'm developing an app in Visual C++ that uses an SQLite3 DB for storing data. Usually it sits in the tray most of the time.
I also would like to enable putting my app in a DropBox folder to share it across several PCs.
It worked really well up until DropBox has recently updated itself.
And now it says that it "can't s... | Checking the result from sqlite3_close(). Perhaps it is not working because you have not finalized all your prepared statements.
|
2,430,850 | 2,430,857 | Weird problem with string function | I'm having a weird problem with the following function, which returns a string with all the characters in it after a certain point:
string after(int after, string word) {
char temp[word.size() - after];
cout << word.size() - after << endl; //output here is as expected
for(int a = 0; a < (word.size() - after... | The behavior you're describing would be expected if you copy the characters into the string but forget to tack a null character at the end to terminate the string. Try adding a null character to the end after the loop, and make sure you allocate enough space (one more character) for the null character. Or, better, us... |
2,430,954 | 2,431,258 | C++ offset of member variables? | I have:
class Foo {
int a;
int b;
std::string s;
char d;
};
Now, I want to know the offset of a, b, s, d given a Foo*
I.e. suppose I have:
Foo *foo = new Foo();
(char*) foo->b == (char*) foo + ?? ; // what expression should I put in ?
| I don't know exactly why you want the offset of a member to your struct, but an offset is something that allows to to get a pointer to a member given the address of a struct. (Note that the standard offsetof macro only works with POD-structs (which yours is not) so is not a suitable answer here.)
If this is what you wa... |
2,430,966 | 2,431,007 | Best practices for handling string in VC++? | As I am new to Visual C++, there are so many types for handling string. When I use some type and go ahead with coding but on next step, there are in-build functions that use other types & it always require to convert one type of string to other. I found so many blogs but so confused when see so many answers & try but s... | That depends on what you are doing. Its a pain and no mater what you do you will have to deal with conversion.
For the most case the std::string class will suite almost any need and is easly readable by anyone accustomed to c++.
If you are using MFC cstring would be the most often seen and the normal choice
For C+... |
2,431,138 | 2,522,680 | Formulae for U and V buffer offset | What should be the buffer offset value for U & V in YUV444 format type?
Like for an example if i am using YV12 format the value is as follows:
ppData.inputIDMAChannel.UBufOffset =
iInputHeight * iInputWidth +
(iInputHeight * iInputWidth)/4;
ppData.inputIDMAChannel.VBufOffset = iInputHeight * iInputWidth;
iI... | Since YUV444 consist of 24 bit per pixel
Therefore the U & V buffer offset will be
ppData.inputIDMAChannel.UBufOffset = iInputHeight * iInputWidth;
ppData.inputIDMAChannel.VBufOffset = 2 * iInputHeight * iInputWidth;
|
2,431,322 | 2,431,328 | I was making this program and the server wont send to the client | void CApplication::SendData( const char pBuffer[] )
{
if( pBuffer == NULL )
{
Log()->Write( ELogMessageType_ERROR, "Cannot send NULL message.");
return;
}
// calculate the size of that data
unsigned long messageSize = strlen( pBuffer );
// fix our byte ordering
messageSize =... | You're not handling the case where send() sends less data than you've asked it to. You need to loop if that is the case, until all data has gone out. You're also not handling errors in general, if a client has disconnected, send() might return -1 for instance.
The typical approach is something like::
for(size_t to_go =... |
2,431,434 | 2,433,351 | On MacOSX, in a C++ program, what guarantees can I have on file IO | I am on MacOSX.
I am writing a multi threaded program.
One thread does logging.
The non-logging threads may crash at any time.
What conventions should I adopt in the logger / what guarantees can I have?
I would prefer a solution where even if I crash during part of a write, previous writes still go to disk, and when re... | I program on Linux, not MacOSX, but probably it's the same there.
If only one thread in your program logs, it means that you buffer the logging data in this logging thread and then it writes it to a file probably some larger portion to avoid too many I/O operations and make the logging process faster.
The bad thing is ... |
2,431,596 | 2,431,626 | Modifying reference member from const member function in C++ | I am working on const-correctness of my code and just wondered why this code compiles:
class X
{
int x;
int& y;
public:
X(int& _y):y(_y)
{
}
void f(int& newY) const
{
//x = 3; would not work, that's fine
y = newY; //does compile. Why?
}
};
int main(int argc, char **argv)
{
... | Because you are not changing any variable in X. Actually, you are changing _y which is an outsider with respect to your class. Don't forget that:
y = newY;
Is assigning the value of newY to the variable pointed by y, but not the references them selves. Only on initialization the references are considered.
|
2,431,682 | 2,432,069 | Piloting Microsoft Word With Ole in C++ Builder : how to put Word in the foreground | I've got a code (which works fine) for piloting word with C++ Builder.
It's useful for reaching different bookmarks in the document.
Variant vNom, vWDocuments, vWDocument, vMSWord, vSignets, vSignet;
vNom = WideString("blabla.doc");
try
{
vMSWord = Variant::GetActiveObject("Word.Application");
}... | There is a simple trick to do that (using Win32 API):
ShowWindow(hwnd, SW_MINIMIZE);
ShowWindow(hwnd, SW_RESTORE);
You must find the hwnd of word using the EnumWindows function.
|
2,432,101 | 2,432,113 | operator inside operator not working | char b;
operator<<(cout,(operator>>(cin,b)));
this is not compiling in vc++ because all 8 overloads cant convert this type.
can any one explain this.....
is their a problem with return type...........
| The stream extraction operation i.e. op>> returns an object of type istream&. The op<< does not have an overload which takes istream& as its second parameter. You need to split the two actions or define one such overload.
|
2,432,116 | 2,432,803 | getting names subgroups | I am working with the new version of boost 1.42 and I want to use regex with named sub groups. Below an example.
std::string line("match this here FIELD=VALUE in the middle");
boost::regex rgx("FIELD=(?<VAL>\\w+)", boost::regex::perl );
boost::smatch thisMatch;
boost::regex_search( line, thisMatch, rgx );
Do you know... | AFAIK, there is no such option. See Understanding Marked Sub-Expressions and Captures and in particular the table on Perl and Boost.Regex equivalence. You will need to use the boost::match_results<IteratorType> to access any and all matches.
|
2,432,133 | 2,432,734 | What configure options were used when building gcc / libstdc++? | After reading about the problem of passing empty std::string objects between DLLs and EXEs, I am concerned about the configure options used to build my gcc / libstdc++. More specific I want to know if --enable-fully-dynamic-string was used during ./configure.
I'm using MinGW 4.4.0 on Windows XP.
Does anybody know the ... | gcc -v prints out the configuration options among other stuff:
$ gcc -v
Using built-in specs.
Target: i686-pc-cygwin
Configured with: /gnu/gcc/releases/packaging/4.3.4-3/gcc4-4.3.4-3/src/gcc-4.3.4/
configure --srcdir=/gnu/gcc/releases/packaging/4.3.4-3/gcc4-4.3.4-3/src/gcc-4.3.
4 --prefix=/usr --exec-prefix=/usr --bind... |
2,432,478 | 2,695,561 | How to fix RapidXML String ownership concerns? | RapidXML is a fast, lightweight C++ XML DOM Parser, but it has some quirks.
The worst of these to my mind is this:
3.2 Ownership Of Strings.
Nodes and attributes produced by RapidXml do not
own their name and value strings. They
merely hold the pointers to them. This
means you have to be careful when
setting t... | I don't use RapidXML, but maybe my approach can solve your problem.
I started using Xerces, but I found it heavy, besides other minor annoyances, so I moved to CPPDOM. When I made the move I decided to create a set of wrapper classes, so that my code wouldn't be dependent from the specific XML 'engine' and I could port... |
2,432,481 | 2,447,605 | Call server with WinInet and WinHTTP | I have a request that works fine when I use the WinInet API. I now want to make that request with the WinHTTP API as I already use it in my project and as it is simply better. My request is used for calling JSON. I already authenticated before calling this. When authenticating I get a SessionID that I send via cookie.
... | Ok, I found it. Wasn't obvious from the code I posted...
The string cstrMethod contains a user id that I extracted previously from the response header from an authentication call. This id is then used for constructing the method call. Now problem was that the user id comes from a response header so it ends with \r\n. S... |
2,432,683 | 2,432,690 | What does slicing mean in C++? | It is mentioned in C++ FAQ site -- "larger derived class objects get sliced when passed by value as a base class object", what does slicing mean? Any sample to demonstrate?
http://www.parashift.com/c++-faq-lite/value-vs-ref-semantics.html#faq-31.8
I am using VSTS 2008 + native C++ as my development environment.
| Quoting this lecture:
Slicing
Suppose that class D is derived from
class C. We can think of D as class C
with some extra data and methods. In
terms of data, D has all the data that
C has, and possible more. In terms of
methods, D cannot hide any methods of
C, and may have additional methods. In
terms of... |
2,432,792 | 2,433,626 | OpenCV performance in different languages | I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program basically chains OpenCV functions, so the main p... | You've answered your own question pretty well. Most of the expensive computations should be within the OpenCV library, and thus independent of the language you use.
If you're really concerned about efficiency, you could profile your code and confirm that this is indeed the case. If need be, your custom processing func... |
2,432,857 | 2,432,946 | Sort list using STL sort function | I'm trying to sort a list (part of a class) in descending order containing items of a struct, but it doesn't compile:
error: no match for 'operator-' in '__last - __first'
sort(Result.poly.begin(), Result.poly.end(), SortDescending());
And here's SortDescending:
struct SortDescending
{
bool operator()(const ter... | The standard algorithm std::sort requires random access iterators, which std::list<>::iterators are not (list iterators are bidirectional iterators).
You should use the std::list<>::sort member function.
|
2,433,023 | 2,433,040 | Can code formatting lead to change in object file content? | I have run though a code formatting tool to my c++ files. It is supposed to make only formatting changes. Now when I built my code, I see that size of object file for some source files have changed. Since my files are very big and tool has changed almost every line, I dont know whether it has done something disastrous... | I would not check your code into the repo without thoroughly checking it first (review, testing).
Pure formatting changes should not change the object file size, unless you've done a debug build (in which case all bets are off). A release build should be not just the same size, but barring your using __DATE__ and such ... |
2,433,054 | 2,494,995 | How do I write the audio stream to a memory buffer instead of a file using DirectShow? | I have made a sample application which constructs a filter graph to capture audio from the microphone and stream it to a file. Is there any filter which allows me to stream to a memory buffer instead?
I'm following the approach outlined in an article on msdn and are currently using the CLSID_FileWriter object to write... | The easiest way to do this (although not the most elegant) is to use a Sample Grabber filter followed by a Null Renderer filter to terminate the graph. This will enable you to get access to the raw media stream using the sample grabber's ISampleGrabber interface. Once you have the samples you can do what you like with ... |
2,433,071 | 2,433,143 | Turning temporary stringstream to c_str() in single statement | Consider the following function:
void f(const char* str);
Suppose I want to generate a string using stringstream and pass it to this function. If I want to do it in one statement, I might try:
f((std::ostringstream() << "Value: " << 5).str().c_str()); // error
This gives an error: 'str()' is not a member of 'basic_o... | You cannot cast the temporary stream to std::ostringstream&. It is ill-formed (the compiler must tell you that it is wrong). The following can do it, though:
f(static_cast<std::ostringstream&>(
std::ostringstream().seekp(0) << "Value: " << 5).str().c_str());
That of course is ugly. But it shows how it can work. seek... |
2,433,240 | 2,433,320 | What wrapper class in C++ should I use for automated resource management? | I'm a C++ amateur. I'm writing some Win32 API code and there are handles and weirdly compositely allocated objects aplenty. So I was wondering - is there some wrapper class that would make resource management easier?
For example, when I want to load some data I open a file with CreateFile() and get a HANDLE. When I'm d... | Write your own. It's only a few lines of code. It's just such a simple task that it's not worth it to provide a generic reusable version.
struct FileWrapper {
FileWrapper(...) : h(CreateFile(...)) {}
~FileWrapper() { CloseHandle(h); }
private:
HANDLE h;
};
Think about what a generic version would have to do: I... |
2,433,667 | 2,433,914 | shared_ptr requires complete type; cannot use it with lua_State* | I'm writing a C++/OOP wrapper for Lua. My code is:
class LuaState
{
boost::shared_ptr<lua_State> L;
LuaState(): L( luaL_newstate(), LuaState::CustomDeleter )
{
}
}
The problem is lua_State is incomplete type and shared_ptr constructor requires complete type. And I need safe pointer sharing. (Funny... | You are using your own deleter, which means that you don't have to have a complete type upon construction. The only requirement is that CustomDeleter can handle that. (it may convert the pointer passed to a complete type, for example (say, from void* to CompleteType*).
The background of completeness is that once the c... |
2,433,950 | 2,434,217 | C# wrapper of c++ dll; "Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call." error | Here is the code in C++ dll:
extern "C" _declspec(dllexport) int testDelegate(int (*addFunction)(int, int), int a, int b)
{
int res = addFunction(a, b);
return res;
}
and here is the code in C#:
public delegate int AddIntegersDelegate(int number1, int number2);
public static int AddIntegers(int a, int b)
{
... | Adam is correct, you've got a mismatch on the calling convention on a 32-bit version of Windows. The function pointer defaults to __cdecl, the delegate declaration defaults to CallingConvention.StdCall. The mismatch causes the stack pointer to not be properly restored when the delegate call returns, triggering the di... |
2,434,004 | 2,449,358 | How does one paint the entire row's background in a QStyledItemDelegate? | I have a QTableView which I am setting a custom QStyledItemDelegate on.
In addition to the custom item painting, I want to style the row's background color for the selection/hovered states. The look I am going for is something like this KGet screenshot:
KGet's Row Background http://www.binaryelysium.com/images/kget_bac... | You need to be telling the view to update its cells when the mouse is over a row, so I would suggest tracking that in your model. Then in the paint event, you can ask for that data from the model index using a custom data role.
|
2,434,054 | 2,434,086 | What is the "munch"? How it was used with cfront | What was the munch library (or program?) from cfront package?
What is was used for?
| Munch was used to scan the nm output and look for static constructors/destructors.
See the code (with comments) at SoftwarePreservation.com.
|
2,434,059 | 2,434,095 | Visual Studio compile "filter" as C and "filters" groups as C++ | I have written the majority of my project in C++. However there are several "filters" or folders which need to be compiled as C and linked to the project. How can I configure this within VStudio? Thanks.
| You can change the Language property by right-clicking on the individual files and setting Configuration Properties > C/C++ > Advanced > Compile As To Compile As C (/TC). No such facility for the filter are present though.
|
2,434,196 | 2,434,208 | How to initialize std::vector from C-style array? | What is the cheapest way to initialize a std::vector from a C-style array?
Example: In the following class, I have a vector, but due to outside restrictions, the data will be passed in as C-style array:
class Foo {
std::vector<double> w_;
public:
void set_data(double* w, int len){
// how to cheaply initialize th... | Don't forget that you can treat pointers as iterators:
w_.assign(w, w + len);
|
2,434,213 | 2,434,223 | Links to official style guides | C++ has several types of styles: MFC, Boost, Google, etc. I would like to examine these styles and determine which one is best for my projects, but I want to read from the official style guidebook. Does anyone have an official guide that they typically use?
Here are two that I found. I bet there are more:
http://go... | Not a Coding Guideline per se, but I find this mighty useful: Bjarne Stroustrup's C++ Style and Technique FAQ
|
2,434,505 | 5,215,798 | g++ __static_initialization_and_destruction_0(int, int) - what is it | After compiling of c++ file (with global static object) I get in nm output this function:
00000000 t _Z41__static_initialization_and_destruction_0ii
__static_initialization_and_destruction_0(int, int) /* after c++filt */
What is it? It will call __cxa_atexit()
Can I disable generation of this function (and calling... | This doc file seems to tell ya all you'd wanna know about those functions: http://www.nsnam.org/docs/linker-problems.doc
From what I can grok, gcc creates a __static_initialization_and_destruction_0 for every translation unit that needs static constructors to be called. Then it places __do_global_ctors_aux into the .c... |
2,434,549 | 2,434,580 | forward declare typedef'd struct | I can't figure out how to forward declare a windows struct. The definition is
typedef struct _CONTEXT
{
....
} CONTEXT, *PCONTEXT
I really don't want to pull into this header, as it gets included everywhere.
I've tried
struct CONTEXT
and
struct _CONTEXT
with no luck (redefinition of basic types with the actuall st... | extern "C" { typedef struct _CONTEXT CONTEXT, *PCONTEXT; }
You need to declare that _CONTEXT is a struct. And declare it as extern "C" to match the external linkage of windows.h (which is a C header).
However, you don't need to provide a definition for a typedef, but if you do, all definitions must match (the One Defi... |
2,434,568 | 2,437,743 | how to send classes defined in .proto (protocol-buffers) over a socket | I am trying to send a proto over a socket, but i am getting segmentation error. Could someone please help and tell me what is wrong with this example?
file.proto
message data{
required string x1 = 1;
required uint32 x2 = 2;
required float x3 = 3;
}
xxx.cpp
...
data data_snd, data_rec;
//sen... | You're not supposed to write the protobuf object itself to the socket. Use the SerializeXXX family of methods to get a sequence of bytes which you can write to the socket.
std::string buf;
data.SerializeToString(&buf);
// now you can write buf.data() to the socket
|
2,434,632 | 2,434,653 | Concise (yet still expressive) C++ syntax to invoke base class methods | I want to specifically invoke the base class method; what's the most concise way to do this? For example:
class Base
{
public:
bool operator != (Base&);
};
class Child : public Base
{
public:
bool operator != (Child& child_)
{
if(Base::operator!=(child_)) // Is there a more concise syntax than this?
r... | No, that is as concise as it gets. Base::operator!= is the name of the method.
And yes, what you are doing is standard.
However, in your example (unless you have removed some code), you do not need Child::operator!= at all. It does the same thing as Base::operator!= will.
|
2,434,862 | 2,434,900 | How to auto-include all headers in directory | I'm going through exercises of a C++ book. For each exercise I want to minimize the boilerplate code I have to write. I've set up my project a certain way but it doesn't seem right, and requires too many changes.
Right now I have a single main.cpp file with the following:
#include "e0614.h"
int main()
{
E0614 ex;
... |
No. You have to include them all if that's what you want to do.
No. At least, not in a way that's actually going to save typing.
Of course, you could write a script to create main.cpp for you...
|
2,434,891 | 2,435,006 | Textfield - what is wxTextCtrlNameStr? | Question
I'm trying to create a basic wxWidgets program with a text entry box, in the constructor there is a variable wxTextCtrlNameStr - in researching I can't seem to find wxTextCtrlNameStr? any help?
Given Code documentation:
wxTextCtrl(wxWindow* parent, wxWindowID id, const wxString& value = "", const wxPoint& pos ... | It's the name of the window. By default wxTextCtrlNameStr might be simply "text".
You probably don't need it, but it gives you an alternative way to identify widgets.
For example it allows you to find a Window or Widget if you know the name it was given when created: wxWindow::FindWindowByName
Note that the argument ... |
2,435,232 | 2,435,307 | How to skip past loops in ddd (gdb) | During many, sometimes inundating, debugging sessions using DDD, I stumble upon loops. And I keep pressing next to get past it, and if there are many iterations, I just set a break point right after it, and press "continue." Is there any other way to go past loops?
| You want the "until" command - see the gdb manual at http://www.gnu.org/software/gdb/documentation:
Continue running until a source line
past the current line, in the current
stack frame, is reached. This command
is used to avoid single stepping
through a loop more than once. It is
like the next command, exc... |
2,435,385 | 2,435,552 | C++ Thread level constants | Is there a way by which we can simulate thread level constants in C++? For example, if i have to make a call to template functions, then i need to mention the constants as template level parameters? I can use static const variables for template metaprogramming, but they are process level constants.
I know, i am asking... | Templates are compile time constructs, threads are run-time ones - there is no way of having templates specific to a thread.
|
2,435,497 | 2,435,546 | Can set_intersection be used with hash_set in C++? | I am calculating intersection, union and differences of sets.
I have a typedef of my set type:
typedef set<node_type> node_set;
When it is replaced with
typedef hash_set<node_type> node_set;
The results are different. It's a complicated program, and before I start debugging - am I doing it right? When I use function... | I don't think so.
One of the pre-condition of set_intersection is:
[first1, last1) is ordered in ascending order according to operator<. That is, for every pair of iterators i and j in [first1, last1) such that i precedes j, *j < *i is false.
The hash_set (and unordered_set) is unordered, so the ordered condition can... |
2,435,942 | 2,439,808 | new with exception with Microsoft | As I'm coding for both Windows and Linux, I have a whole host of problems.
Microsoft Visual C++ has no stdint header, but for that I wrote my own.
Now I found out that MS C++'s new operator does not throw an exception, so I want to fix this a quickly as possible. I know I can define a Macro with Parameters in Parenthes... | The simplest alternative is to write your own implementation of operator new, overriding the compiler's default implementation (if your version of MSVC supports it). This is what Roger also suggested in his linked answer.
The following program illustrates the attempt. operator new allocates memory from the heap using m... |
2,436,004 | 2,436,079 | How do I correctly organize output into columns? | The first thing that comes to my mind is to do a bunch of \t's, but that would cause words to be misaligned if any word is longer than any other word by a few characters.
For example, I would like to have something like:
Name Last Name Middle initial
Bob Jones M
Joe ReallyLongLastNa... | Use std::setw from <iomanip>
e.g.
using std::cout;
using std::setw;
cout << setw(10) << "This" <<
setw(10) << "is" <<
setw(10) << "a" <<
setw(10) << "test" << '\n';
Output:
This is a test
|
2,436,020 | 2,436,060 | Detecting use after free() on windows. (dangling pointers) | I'm trying to detect "Use after free()" bugs, otherwise known as "Dangling pointers". I know Valgrind can be used to detect "Use after free" bugs on the *nix platform, but what about windows? What if I don't have the source? Is there a better program than Valgrind for detecting all dangling pointers in a program... | The MSVC debug memory allocator already does this. When you get 0xfeeefeee from a pointer dereference you've dangled. With some luck that will bomb the program.
|
2,436,067 | 2,436,374 | resolving overloads in boost.python | I have a C++ class like this:
class ConnectionBase
{
public:
ConnectionBase();
template <class T> Publish(const T&);
private:
virtual void OnEvent(const Overload_a&) {}
virtual void OnEvent(const Overload_b&) {}
};
My templates & overloads are a known fixed set of types at compile time. The applicati... | Creating C++ virtual functions that can be overridden in Python requires some work - see here. You will need to create a wrapper function in a derived class that calls the Python method. Here is how it can work:
struct ConnectionBaseWrap : ConnectionBase, wrapper<ConnectionBase>
{
void OnEvent(const Overload_a &obj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.