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 array.
*o_len : No of bytes in third parameter
*e : Error code returned
How can I call it from c#?
What would be the P/Invoke declaration?
| 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 processes or devices from accessing this physical address?
The mapping of the physical address to linear one is done using a third party driver: TVicHW32.
EDIT: I can reproduce the scenario if I run 2 instances of my application with different flags. Both instances can access the same specific physical memory that is not a part of either process' memory space.
| 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 there is a slight asymmetry in the mapping/unmapping services, since the "mapping" service is done via DeviceIoControl, so it taked the handle obtained at CreateFile time, but the mapped area is not directly connected to the device handle anymore. Of course, you can arrange you driver's "close" method to automate the unmapping (ZwUnmapViewOfSection...).
|
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.
So I would like to implemet comparer in a base class Foo and inherit it in other hashers, such as Bar.
class Foo
{
public:
Foo(const SeedParam& dim);
Foo(const Foo& src);
Foo& operator = (const Foo& src);
virtual bool operator ()(const Index2& ind1, const Index2& ind2) const;
size_t operator() (const Index2& ind) const;
enum
{
bucket_size = 4,
min_buckets = 32768,
};
protected:
SeedParam _dim;
const hash_compare<unsigned long long> _stdHasher;
};
class Bar: public Foo
{
public:
Bar(const SeedParam& dim);
size_t operator() (const Index2& ind) const;
};
But the compilers says that "a term does not evaluate to a function taking two arguments" when compiling such a code in hash_map:
if (!this->comp(this->_Kfn(*_Where), _Keyval))
So is it possible to inherit operator() ? What's wrong with my classes?
| 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 search for operator() in Bar scope, there is one and so the overload with two parameters in Foo is not found.
The solution is to add
using Foo::operator();
in Bar.
|
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 = 7;
optional int32 BufferType = 8;
optional Guid Guid = 9;
repeated int32 EncryptedDataStart = 10;
repeated int32 EncryptedDataLength = 11;
}
My aim is to serialize this and inject it into an ASF file, as a single sample.
I call this to serialize :
MemoryStream ms = new MemoryStream();
Serializer.Serialize<ProtoScreenBuffer>(ms, ProtoScreenBuffer.CreateProtoScreenBuffer (buffer));
then I get a byte array from the ms object :
ms.ToArray();
and I put this byte array in the ASF. The big problem is on my C++ app which reads the ASF sample just fine, I get a memory access violation when I try to deserialize it :(
this is my C++ code :
m_screenBuffer.ParseFromArray(serBuffer, dwInputDataLen);
(where m_screenBuffer is ProtoScreenBuffer, serBuffer is the raw byte array I got from the ASF file, and dwInputDataLen is the length of it.)
Are any of the things I'm doing here wrong , for what I'm trying to do (serialize in C# .NET and deserialize in C++?)
Thanks alot.
Roey
| 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 via C#, to a file (or just look at the bytes on-screen in the debugger)
serialize the /same/ data via C++, to a file (or just look at the bytes on-screen in the debugger)
Then:
compare the bytes
check the length is what you expect (i.e. the number you are passing over)
That should indicate whether it is the encoding, vs something to do with passing the wrong memory address or similar.
Also - check you aren't using GetBuffer() (or at least, if you do use GetBuffer(), make sure you use the .Length from the MemoryStream, and not from the oversized byte[]).
|
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.insert( make_pair( 1, 1 ) );
cout << m1.size() << endl;
MapType m2( m1 );
cout << m2.size() << endl;
}
If your own code really doesn't copy, then I would suspect bugs in the copy constructors or the comparison functions for the contained types are screwing up memory somehow.
|
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 using the windows JOB object as mentioned in http://www.microsoft.com/msj/0399/jobkernelobj/jobkernelobj.aspx, But I am not sure if this is the best way.
| +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 SetInformationJobObject()). Monitoring the job in this way will also give you notifications of the processId's of new processes created within the job and details of when they exit.
|
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)
{
}
};
class Sorter()
{
public:
static void DoSort();
static int __cdecl SortProc(const void* elem1, const void* elem2);
};
...
void Sorter::DoSort()
{
CArray<Foo*, Foo*> data;
for (int i = 0; i < 100; i++)
{
Foo* foo = new Foo("some string", 12345678);
data.Add(foo);
}
qsort(data.GetData(), data.GetCount(), sizeof(Foo*), SortProc);
...
}
int __cdecl SortProc(const void* elem1, const void* elem2)
{
Foo* foo1 = (Foo*)elem1;
Foo* foo2 = (Foo*)elem2;
// 0xC0000005: Access violation reading location blah here
return (int)(foo1->t - foo2->t);
}
...
Sorter::DoSort();
I am about to refactor this horrible code to use std::sort instead but wondered if the above is actually unsafe?
EDIT: Sorter::DoSort is actually a static function but uses no static variables itself.
EDIT2: The SortProc function has been changed to match the real code.
| 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)
{
Foo* foo1 = *(Foo**)elem1;
Foo* foo2 = *(Foo**)elem2;
if(foo1->t < foo2->t) return -1;
else if (foo1->t > foo2->t) return 1;
else return 0;
}
|
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> &inpTree);
FunctionTree<D> operator-(FunctionTree<D> &inpTree);
FunctionTree<D> operator*(FunctionTree<D> &inpTree);
There operators work finer in simple, non-chained operations, and even in some cases when chaining the operators. Statements like
FunctionTree<3> y = a * b + c;
FunctionTree<3> z = a * b + b;
compile and seemingly work fine. The first line is actually ok, but the second line causes valgrind to tell you grim stories about memory being freed inside already freed regions and uninitialized variables being accessed. Furthermore, a statement like
FunctionTree<D> y = a + b * c;
will not even compile, because I have not defined (an ambiguous operator taking an actual object, not a reference, as argument). Of course the solution is clear: All arguments, and methods ought to be made const, and perhaps even return a const object or reference. Unfortunately this is not possible, since NONE of the objects involved are constant during the operations! This may sound strange, but this is an unavoidable consequence of the mathematics involved. I can fake it, using const_cast, but the code is still wrong!
Is there a way to solve this problem? The only solution I have currently is to make the return objects const, thus effectively disabling the operator chaining.
Regards, .jonas.
| 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 results of operations, and calculate only when someone wants to finally get result or a part of it. It might even speed up your code enormously as it helped APL
Also, you might want to make most of the members private.
#include <memory>
#include <iostream>
struct FunctionTreeProxy;
struct FunctionTree;
struct FunctionTreeProxy {
mutable std::auto_ptr<FunctionTree> ft;
explicit FunctionTreeProxy(FunctionTree * _ft): ft(_ft) {}
FunctionTreeProxy(FunctionTreeProxy const & rhs): ft(rhs.ft) {}
FunctionTreeProxy operator+(FunctionTree & rhs);
FunctionTreeProxy operator*(FunctionTree & rhs);
FunctionTreeProxy operator+(FunctionTreeProxy const & rhs);
FunctionTreeProxy operator*(FunctionTreeProxy const & rhs);
};
struct FunctionTree {
int i;
FunctionTree(int _i): i(_i) {}
FunctionTree(FunctionTreeProxy const & rhs): i(rhs.ft->i) {}
FunctionTree * add(FunctionTree & rhs) {
return new FunctionTree(i + rhs.i);
}
FunctionTree * mult(FunctionTree & rhs) {
return new FunctionTree(i * rhs.i);
}
FunctionTreeProxy operator+(FunctionTree & rhs) {
return FunctionTreeProxy(add(rhs));
}
FunctionTreeProxy operator*(FunctionTree & rhs) {
return FunctionTreeProxy(mult(rhs));
}
FunctionTreeProxy operator+(FunctionTreeProxy const & rhs) {
return FunctionTreeProxy(add(*rhs.ft));
}
FunctionTreeProxy operator*(FunctionTreeProxy const & rhs) {
return FunctionTreeProxy(mult(*rhs.ft));
}
};
FunctionTreeProxy FunctionTreeProxy::operator+(FunctionTree & rhs) {
return FunctionTreeProxy(ft.get()->add(rhs));
}
FunctionTreeProxy FunctionTreeProxy::operator*(FunctionTree & rhs) {
return FunctionTreeProxy(ft.get()->mult(rhs));
}
FunctionTreeProxy FunctionTreeProxy::operator+(FunctionTreeProxy const & rhs) {
return FunctionTreeProxy(ft.get()->add(*rhs.ft));
}
FunctionTreeProxy FunctionTreeProxy::operator*(FunctionTreeProxy const & rhs) {
return FunctionTreeProxy(ft.get()->mult(*rhs.ft));
}
int main(int argc, char* argv[])
{
FunctionTree a(1), b(2), c(3);
FunctionTree z = a + b * c;
std::cout << z.i << std::endl;
return 0;
}
|
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 Eclipse's "Internal Build" to build all other projects and we'd prefer to use it here too, but for the good of me, I can't find how to get Eclipse to build multiple small programs as result instead of linking everything into one binary.
| 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 & Symbols > Manage Configurations
Make a build configuration for each executable and name it appropriately (you can clone existing configurations like Debug and Release).
From the project explorer, right click on each source file that contains a main() function > Resource Configurations > Exclude from Build and exclude all build configurations except the one that builds the executable with this main() function
All other code is included in all build configurations by default. You may need to change this depending on your application.
You can now build an executable for each main function by going to Project > Build Configurations > Set Active , Project > Build Project
|
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 caught. For example, this catch doesn't work:
try
{
m_pSerialPort = new boost::asio::serial_port(m_IoService, "non-existing-port");
}
catch(const boost::system::system_error& e)
{
// ...
}
Error message:
terminate called after throwing an instance of
'boost::exception_detail::clone_impl
<boost::exception_detail::error_info_injector
<boost::system::system_error> >'
what(): No such file or directory
GCC version is 4.4.1, Linux OS. The same code is running successfully in Windows, MSVC.
What reason can prevent GCC program to catch exceptions properly?
| 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 program, or using the option -shared-libgcc, such that it is linked with the shared libgcc.
|
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="BootInstall"
ProjectGUID="{EBCFC92F-CD0C-4451-8FD0-4C422C5DA8C2}"
RootNamespace="BootInstall"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="IEI_PXA270_E205 (ARMV4I)"
/>........
now i reinstalled my windows and installed the same sdk but i can't load the project it just says
"The project consists entirely of configurations that require support for platforms which are not installed on this machine. The project cannot be loaded."
and if i try to create a new project the sdk is not there..
so what am i missing i know where the sdk is located on my local hard drive... is there any way to add a "platform" manualy or some thing... the only thing that has changed that i can think of is that i have visual studio 2010 installed..
| 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++ and Java software.
|
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 void Foo()
{
cout << "In base" << endl;
}
};
class Derived : public Base
{
public:
Derived()
{
}
void Foo()
{
cout << "In derived " << endl;
}
};
| 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# classes through that.
|
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 the functor object by a reference_wrapper, in a way to avoid useless copy costructor calls.
I expect the following output:
F: 6
7
It works correctly with GCC >= 4.4.0, Visual Studio 2008 and with boost by substituting std::tr1 namespace with boost. It only doesn't work with the new Visual Studio 2010 both Express Beta 2 and Release Candidate.
Are this new C++ features bugged in vs2010?
Or there is some mistake or misuse in the code?
| 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 given types. [Note: The intent is that implementations are permitted to use special compiler hooks —end note]
And then paragraph 3:
If F is not a function object defined by the standard library, and if either the implementation cannot determine the type of the expression f(t1, t2, ..., tN) or if the expression is ill-formed, the implementation shall use the following process to determine the type member:
If F is a possibly cv-qualified class type with no member named result_type or if typename F::result_type is not a type:
If N=0 (no arguments), type is void.
If N>0, type is typename F::template result<F(T1, T2,..., TN)>::type
The error message is an artefact of trying these fall-backs. Provide a typedef for result_type to int and it should work, i think. Notice that in C++0x, this is different. It does not rely on result_type or a result template, since it can use decltype.
If with <functional> it fails with MSVC10 in C++0x mode, it smells like a bug, i would say. But maybe someone else knows what's going on. It may (but is not guaranteed to) work with <tr1/functional> in C++0x mode if that header chooses to take the decltype way instead of ::result_type. I would typedef result_type - that way i think it should always work regardless of whether the tr1 header is used or the c++0x header.
Also notice that boost::tr1 says in its documentation that it does not support the function call operator (but it merely supports implicit conversions to T&).
|
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 screen but that's in dialog units not in pixel units and somehow that screw up terribly..
Look here for example, that selected thing should be a square according to visual studio, you can see in the bottom right corner it says "170 x 170" but you can clearly see it's nowhere near square, I can even test it by running my application, the openGL render gets squashed up and doesn't look right cause of the thing not being squared:
Screenshot:
http://i42.tinypic.com/xpsepf.jpg
Because I can't set it by hand I can't get it right.. I've also tried opening/editing the .rc in other resource editors but visual studio saves it with it's own type of compression which makes any other tool unable to open the file, I've tried ResourceHacker, ResourceTuner, Restorator, XYExplorer and even the WinASM resource editor which I used for my previous model viewer, all are unable to open the file.
Does anybody have an idea or know about an option in visual studio so I can see it's width and height..? I can if I make a dialog in WinASM studio for example.. VisualStudio should support this.
| 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
{
polinom Result;
constIter i, j, lastItem = Result.poly.end();
Iter it1, it2, first, last;
int nr_matches;
for (i = poly.begin() ; i != poly.end(); i++) {
for (j = P.poly.begin(); j != P.poly.end(); j++)
Result.insert(i->coef * j->coef, i->pow + j->pow);
}
Result.poly.sort(SortDescending());
lastItem--;
while (true) {
nr_matches = 0;
for (it1 = Result.poly.begin(); it1 != lastItem; it1++) {
first = it1;
last = it1;
first++;
for (it2 = first; it2 != Result.poly.end(); it2++) {
if (it2->pow == it1->pow) {
it1->coef += it2->coef;
nr_matches++;
}
}
nr_matches++;
do {
last++;
nr_matches--;
} while (nr_matches != 0);
Result.poly.erase(first, last);
}
if (nr_matches == 0)
break;
}
return Result;
}
| 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 != poly.end() && j != P.poly.end()) {
//logic while both iterators are valid
}
//handle the remaining items in each list
//note: at least one will be equal to end(), but that loop will simply be skipped
while (i != poly.end()) {
Result.insert(i->coef, i->pow);
++i;
}
while (j != P.poly.end()) {
Result.insert(j->coef, j->pow);
++j;
}
return Result;
}
The last part can probably also be left to standard library functions
#include <iterator>
#include <algorithm>
//...
//handle remaining items in either list (if any)
std::copy(i, poly.end(), std::back_inserter(Result.poly));
std::copy(j, P.poly.end(), std::back_inserter(Result.poly));
... but would probably be simpler using list.insert:
Result.poly.insert(Result.poly.end(), i, poly.end());
Result.poly.insert(Result.poly.end(), j, P.poly.end());
|
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 the string you expect it to return. However, I don't really see how that happens: isn't the char array supposed to be stored on the stack, and thus deallocated after the function exits? If I'm wrong, and it gets stored on the heap, isn't this function creating a memory leak?
| 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 file is fast to read and write, but hard to access, while database seem an easier interface to work with, but I am not sure if the performance is fast enough.
Do you guys have any experience regarding fsream or database as the choice for fast persistent storage?
| 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 files are the best solution.
|
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 behavior.
|
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 the return value to int in this case as a good practice?
| 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 just cover up the possibility of bugs. It would be OK after you have checked that such a cast won't modify the value to appease the compiler.
|
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:
float x, y ;
} ;
Vector2 operator+( const Vector2& v1, const Vector2& v2 )
{
Vector2 ans ;
ans.x = v1.x + v2.x ;
ans.y = v1.y + v2.y ;
return ans ;
}
(Apparently in C# you can only use the "outside class" method.)
In C++, which way is more correct? Which is preferable?
| 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;
where a conversion is performed to turn the char * "foo" into an std::string. So, we make operator+() for strings into a free function.
|
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 a text editor. My current (restricted) environment has in it various hooks to procedures, one of which yield the handle to the editor window. Another allows me to procure the handle to the RichEdit20A controls the window hosts.
What I'd like to do is this - Overwrite the control with my own (its .NET equivalent presumably) and patch the app's GetWindowText calls to use the new one. To implement it, I plan to write the class library in C#/managed C++ and import it to my app (which is written in unmanaged C++).
Also, there can be an arbitrary number of instances of the text editor.
| 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 should use something that fit what you think a singleton should behave like.
Now, there is other libraries providing singleton, the most generic being Loki. But it could blow your mind ;)
Update : There is now a proposed library called Singularity that is meant to provide non-global singleton (with option to make it global) that forces you to have clear creation and destruction points of the object.
See the review request : http://boost.2283326.n4.nabble.com/Review-Request-Singularity-tt3759486.html
Some boost devs seems to consider using it instead of some hacks, but C++11 makes makeing a class Singleton easier than before so it will depends on the review.
|
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 example:
// Custom numeric class
template <class T>
struct Complex {
Complex(T real, T imag) : r(real), i(imag) {}
T r, i;
// Other implementation stuff
};
// Generic arithmetic promotion template
template <class T, class U>
struct ArithmeticPromotion {
typedef typename X type; // I realize this is incorrect, but the point is it would
// figure out what X would be via trait testing, etc
};
// Specialization of arithmetic promotion template
template <>
class ArithmeticPromotion<long long, unsigned long> {
typedef typename unsigned long long type;
}
// Arithmetic promotion template actually being used
template <class T, class U>
Complex<typename ArithmeticPromotion<T, U>::type>
operator+ (Complex<T>& lhs, Complex<U>& rhs) {
return Complex<typename ArithmeticPromotion<T, U>::type>(lhs.r + rhs.r, lhs.i + rhs.i);
}
If you use these promotion templates, you can more or less treat your user defined types as if they're primitives with the same promotion rules being applied to them. So, I guess the question I have is would this be something that could be useful? And if so, what sorts of common tasks would you want templated out for ease of use? I'm working on the assumption that just having the promotion templates alone would be insufficient for practical adoption.
Incidentally, Boost has something similar in its math/tools/promotion header, but it's really more for getting values ready to be passed to the standard C math functions (that expect either 2 ints or 2 doubles) and bypasses all of the integral types. Is something that simple preferable to having complete control over how your objects are being converted?
TL;DR: What sorts of helper templates would you expect to find in an arithmetic promotion header beyond the machinery that does the promotion itself?
| 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 way, you can write a generic operator that will handle different argument types, and it will return a value of the appropriate type to avoid precision loss in the expression that it appears in. It's also useful (in things like vector sums) for properly declaring internal variables within these operators.
As for the question of what ought to go with these: I just checked in our source code where we define them, and all we have there are just the simple ArithmeticPromotion declaration you describe -- three generic versions to resolve the complex-complex, complex-real, and real-complex variants using the specific real-real ones, and then a list of real-real ones -- about 50 lines of code in all. We don't have any other helper templates with them, and it doesn't (from our usage) look like there are any natural ones that we'd use.
(FWIW, if you don't want to write this yourself, download our source from http://www.codesourcery.com/vsiplplusplus/2.2/download.html, and pull out src/vsip/core/promote.hpp. That's even in the part of our library that's BSD-licensed, though it doesn't actually say so in the file itself.)
|
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 ACM codecs.
But in any case you should be capable to prepend sound stream with RIFF-WAV header. This can be done manaully (I think the simplest way) or by using some free library (it seems libsnd is capable to do this).
|
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 know how to refresh this list as I'd like to use it under a GUI automation tool. Usually the list is there, sometimes it's not, anyone know why? My guess is that there is a function deep within the CFrameWnd class to look after this but I can't seem to find it.
Edit: I'm also using the Stingray library for GUI which could well have a bearing on the problem.
| 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 menu. After all that title in Window menu remains an empty string sometimes.
The simplest way to repair is by using the GetActiveFrame()->ActivateFrame() method call. It will refresh immediatelly the actual frame window and the owned Window menu too.
It can be used after creating the CDocument and the CView. The best place to call it is in end of OnFileNew, OnFileOpen overridden methods of (CWin)App class of application.
|
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. And if the default copy ctor does what you want, don't be tempted to write a version yourself - you will probably only get it wrong, and you will need to maintain it.
|
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 symlink from there to there actual location, it works.
Why is my LIBPATHS being ignored or not used?
Here is the Makefile
CC = g++
INCPATHS = -I/usr/local/include
CFLAGS = -c -Wall $(INCPATHS)
LIBPATHS = -L/usr/local/lib/
LIBS = $(LIBPATHS) -licuio -licui18n -licuuc -licuio -licudata
EXECUTABLE = prog
print_linking = echo -e "\033[32m" "Linking: $<" "\033[39m"
print_compiling = echo -e "\033[33m" "Compiling: $<" "\033[39m"
print_cleaning = echo -e "\033[31m" "Cleaning: `pwd`" "\033[39m"
all: main
# [target]: [dependencies]
# <tab> system command
main: main.o
@$(print_linking)
@$(CC) -o $(EXECUTABLE) main.o $(LIBS) >> /dev/null
main.o: main.cpp
@$(print_compiling)
@$(CC) $(CFLAGS) main.cpp
clean:
@$(print_cleaning)
@rm -rf *.o *~ $(EXECUTABLE)
| 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.
For instance, in C# I would use a MemoryStream to mock an IO.Stream, and am assuming this is the path I should take here.
C++ Mock/Test best practices
boost::asio::io_service Mock/Test best practices
C++ Async Handler Mock/Test best practices
I've started the process with googlemock and googletest.
| 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 library' that goes with the code that I'm developing. An example of how I do things can be found here in my 'Practical testing' articles. In the end it's not that different to mocking and testing in C#, all of the same principles apply, you just end up doing more of the heavy lifting yourself.
|
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 of the code)
class Emplyee {
public:
FullName GetName() const;
Address GetAddress() const;
PhoneNumber GetWorkPhone() const;
...
bool IsZipCodeValid( Address address);
...
private:
...
}
What Steve thinks is bad is that the functions are loosely related. Or has he writes "There's no logical connection between employees and routines that check ZIP codes, phone numbers or job classifications"
Ok I totally agree with him. Maybe something like the below example is better.
class ZipCode
{
public:
bool IsValid() const;
...
}
class Address {
public:
ZipCode GetZipCode() const;
...
}
class Employee {
public:
Address GetAddress() const;
...
}
When checking if the zip is valid you would need to do something like this.
employee.GetAddress().GetZipCode().IsValid();
And that is not good regarding to the Law of Demeter.
So if you like to remove two of the three dots, you need to use delegation and a couple of wrapper functions like this.
class ZipCode
{
public:
bool IsValid();
}
class Address {
public:
ZipCode GetZipCode() const;
bool IsZipCodeValid() {return GetZipCode()->IsValid());
}
class Employee {
public:
FullName GetName() const;
Address GetAddress() const;
bool IsZipCodeValid() {return GetAddress()->IsZipCodeValid());
PhoneNumber GetWorkPhone() const;
}
employee.IsZipCodeValid();
But then again you have routines that has no logical connection.
I personally think that all three examples in this post are bad. Is it some other way that I haven't thought about?
| 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, but pay later should you decide to change your class design in a way which breaks this code.
You get to choose your poison. ;)
|
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
ReadFile();
ParseFileIntoVector();
ProcessObjectsInVector();
/* Here I want to 'reset' the vector to 100 empty objects again */
}
}
Can I reset the vector to be vector<Object> objVector(100) since it was initially allocated on the stack? If I do objVector.clear(), it removes all 100 objects and I would have a vector with a size of 0. I need it to be a size of 100 at the start of every loop.
| 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 something similar? and convert the python output back to C++ double/float? This way I would not have the problem of rounding errors when exchanging data between the two processes...
thx for the answers!
| 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 or Java
code, and hexadecimal strings produced
by C’s %a format character or Java’s
Double.toHexString are accepted by
float.fromhex().
Example:
#include <cstdio>
int main() {
float f = 42.79;
printf("%.2f == %a\n", f, f);
fscanf(stdin, "%a", &f);
printf("%.2f == %a\n", f, f);
}
Run it:
$ g++ *.cpp && (python -c'print 12.34.hex()' | ./a.out )
Output:
42.79 == 0x1.5651ecp+5
12.34 == 0x1.8ae148p+3
|
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 get a bunch of controls all overlapping each other.
w->layout()->activate();w->layout()->update() doesn't seem to do anything.
Is there a way to force the layout to happen without showing w?
| 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 left-to-right reading order, such as &*char/ref ptr char? I'm working on a little language project, and legibility is one of my key concerns.
It seems to me that this is one of those questions to which it's easy for a person but hard for a search engine to provide an answer. Thanks in advance!
| 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 complex declarations. Many people (at least many Pascal programmers) prefer the syntax:
variable : type;
where type is something like:
array of char
which is about as readable as you are going to get, and is left-to-right.
|
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 have come across some very confusing usages.
So are there rules or are people just supposed to know from experience that this is how it is done because they have seen it done this way before?
ALSO: What is the scope of a typedef?
| 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 typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.
e.g.
Declares an int:
int a;
Declares a type that is an alias for int:
typedef int a_type;
Declares a pointer to a char:
char *p;
Declares an alias for a char *:
typedef char *pChar;
Declares a function pointer:
int (*pFn)(int);
Declares an alias for the type that is 'pointer to a function taking int and returning int':
typedef int (*pFunc)(int);
|
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 variables public?
please excuse my ignorance as I am simply trying to understand why?
Thank you in advance. ;-)
| 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 something internally, without affecting any users of your class.
For example, suppose I have a Button control with a public String text field. Now everybody starts using my Button, but I realize that the button should actually be repainted on the screen whenever the text changes. I'm out of luck, because my object can't detect when text is assigned. Had I made it private and provided a setText() instead, I could just have added a repaint call to that setter method.
As another example, suppose I have some class that opens a file in its constructor and assigns it to a public FileStream file. The constructor throws an exception if the file could not be opened. The other methods in the class can therefore assume that this field is always valid. However, if somebody goes poking around in my class and sets file to null, all methods in my class will suddenly start crashing.
|
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;
int a[] = {10, 15};
{
SR x(j), y(a[0]), z(a[1]);
j = a[0];
a[0] = a[1];
a[1] = j;
printf("j = %d, a = {%d, %d}\n", j, a[0], a[1]);
}
printf("j = %d, a = {%d, %d}\n", j, a[0], a[1]);
}
Output:
j = 10, a = {15, 10}
j = 5, a = {10, 15}
Second one:
#include <cstdio>
#include "SR.h"
int main()
{
int sum = 0;
for (int i = 1; i < 100; i++) {
SR ii(i);
while (i--)
sum += i;
}
printf("sum = %d\n", sum);
}
//The output is "sum = 161700".
| 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& var) : capture(var), value(var) {}
~SR() { capture = value; }
private:
int& capture;
int value;
};
Edit: Just a guess, but I assume SR is supposed to stand for ScopeRestorer?
|
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 coding easier.
Another way to phrase this question is: when a framework provides you with a serialization class, how do you handle serializing your own custom-type classes such that you don't have to remember how to serialize them everytime (enhance usability) and also following best software-engineering practices (following patterns).
| 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 constructor John(), and I cannot seem to figure out why.
The code included below is a stripped down version operating only on Plot*. Originally I made the linked list as a template class. And it worked fine as ll<int> and ll<char*> but for some reason it fails as ll<Plot*>.
Could youp please help me figure out why it fails? and perhaps help me understand how to make it work?
In advance: Thanks a heap!
//B2S
#include <string.h>
class Plot{
char title[80];
public:
Plot(){ }
};
class Link{
Plot* element;
Link* next;
Link* prev;
friend class ll;
};
class ll{
Link* head;
Link* tail;
public:
ll(){
head = tail = new Link();
head->prev = tail->prev = head->next = tail->next = head;
}
~ll(){
while (head!=tail){
tail = tail->prev;
delete tail->next;
}
delete head;
}
void append(Plot* element){
tail->element = element;
tail->next = new Link();
tail->next->prev = tail;
tail->next = tail;
}
};
class John{
ll* plots;
public:
John(){
plots= new ll();
}
~John(){
delete plots;
}
John(Plot* plot){
John();
plots->append(plot);
}
};
int main(){
Plot p;
John k(&p);
}
| 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, hence the crash when you call append from the John constructor.
[As Neil Butterworth comments, if you had actually constructed an ll instance there are other issues with it, this is just the most immediate problem.]
|
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 usually no impact on the implementation of the virtual function mechanism itself. The compiler must not allow you to construct an object of a type which has pure virtual functions that don't have a non-pure final override in their inheritance hierarchy and any attempt to make a virtual call to a pure virtual function directly or indirectly from an object's constructor or destructor causes undefined behaviour.
|
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's what the pointer size was in C++. I know that some of the early M68000 series chips only had a 24 bit memory address space, but it was addressed from a 32 bit register so even on those the pointer would be 32 bits.
In the bad old days of the 80286, it was worse - there was a 16 bit address register, and a 16 bit segment register. Some C++ compilers didn't hide that from you, and made you declare your pointers as near or far depending on whether you wanted to change the segment register. Mercifully, I've recycled most of those brain cells, so I forget if near pointers were 16 bits - but at the machine level, they would be.
|
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 was to use the & operator, like so:
Function(
//other parameters,
&D3DVECTOR3(x, y, 0));
but I don't know if this is a valid way to go about doing this. (It doesn't get an error, but there are a lot of things that don't give errors that aren't necassarily good). So should I use new, &, or some other technique I'm overlooking?
| 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 address.
|
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 everything into binary when i opened the stream in binary mode. What should I do, incase i need binary of every element in the array and then print it to the file.
|
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 all about. (Also, think of how you would stream an object of a user-defined type containing pointers in a binary representation.)
To actually write objects binary use std::ostream::write(). Beware, though, the result is platform-specific.
|
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(std::string &result) : result(result) {}
void operator() (char c) {
if (c == '\n') result += "\\n";
else if (c == '\r') result += "\\r";
else result += c;
}
std::string &result;
};
template <typename Parser>
void parse(const std::string &s, const Parser &p) {
std::string::const_iterator it = s.begin(), end = s.end();
bool r = phrase_parse(it, end, p, space);
std::string label;
fix f(label);
std::for_each(s.begin(), s.end(), f);
std::cout << '"' << label << "\":\n" << " - ";
if (r && it == end) std::cout << "success!\n";
else std::cout << "parse failed; r=" << r << '\n';
}
int main() {
parse("foo", lit("foo"));
parse("foo\n", lit("foo") >> eol);
parse("foo\r\n", lit("foo") >> eol);
}
Output:
"foo":
- success!
"foo\n":
- parse failed; r=0
"foo\r\n":
- parse failed; r=0
Why do the latter two fail?
Related question:
Using boost::spirit, how do I require part of a record to be on its own line?
| 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 are to it and when this counter is 0 it delete this (such as when A is passed, the receiver call A->Aquire(), when its done it call A->release();
Or I could tell B->RemoveObj(A); and C->RemoveObj(A); The problem with that is if B or C are running on a different thread, I cannot delete A until they are done with A, and they have seen The RemoveObj call. (Which require a bunch of messy flags).
Would there be a nice way to do this, possibly with Signal/Slot?
Thanks
| 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 of a boost pointer implementation.
|
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 advance.
#include <iostream>
using namespace std;
struct Value{
public:
int Val;
}*pc;
#include "header.h"
int main () {
cout << "Enter a value: ";
cin >> pc->Val;
cout << "\nYour value is " << pc->Val << ". ";
system ("pause");
return 0;
}
| 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 the program.
|
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 times. I know that body can be thrown out to another function and just call of this is to be made in every specialization's body, however it would be nicer if i could avoid writting this "void foo(..." for every type. Is there any possibility to tell the compiler that I want to use this specialization for all this types?
| 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 fooImpl(T arg, bool2type<false>) {
}
template<class T>
void foo(T arg)
{ fooImpl(arg, bool2type<std::numeric_limits<T>::is_specialized>()); }
|
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:
#include <Windows.h>
#include "COM.hpp"
namespace WindowsAPI { namespace ComponentObjectModel {
COM::COM()
{
if (CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) != S_OK) throw std::runtime_error("Couldn't start COM!");
}
COM::~COM()
{
CoUninitialize();
}
void COM::Setup()
{
static COM instance;
}
}}
Then any component that needs COM just calls COM::Setup() and forgets about it.
Does this make sense or am I breaking any "rules" of COM?
| 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 comInitGuard;
...
|
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 sync the file in use". The SQLite file is open in my app, but the lock is shared. There are some prepared statements, but all are reset immediately after using step.
Is there any way to enable synchronizing of an open SQLite database file? Thanks!
Here is the simple wrapper that I use just for testing (no error handling), in case this helps:
class Statement
{
private:
Statement(sqlite3* db, const std::wstring& sql) : db(db)
{
sqlite3_prepare16_v2(db, sql.c_str(), sql.length() * sizeof(wchar_t), &stmt, NULL);
}
public:
~Statement() { sqlite3_finalize(stmt); }
public:
void reset() { sqlite3_reset(stmt); }
int step() { return sqlite3_step(stmt); }
int getInt(int i) const { return sqlite3_column_int(stmt, i); }
std::wstring getText(int i) const
{
const wchar_t* v = (const wchar_t*)sqlite3_column_text16(stmt, i);
int sz = sqlite3_column_bytes16(stmt, i) / sizeof(wchar_t);
return std::wstring(v, v + sz);
}
private:
friend class Database;
sqlite3* db;
sqlite3_stmt* stmt;
};
class Database
{
public:
Database(const std::wstring& filename = L"")) : db(NULL)
{
sqlite3_open16(filename.c_str(), &db);
}
~Database() { sqlite3_close(db); }
void exec(const std::wstring& sql)
{
auto_ptr<Statement> st(prepare(sql));
st->step();
}
auto_ptr<Statement> prepare(const std::wstring& sql) const
{
return auto_ptr<Statement>(new Statement(db, sql));
}
private:
sqlite3* db;
};
UPD: Tried commenting out all calls to LockFile and LockFileEx in sqlite3.c - same result.
UPD2: Tried to call sqlite3_close when idle (just as proof of concept) - still same result! Filemon tells that file is still not closed, only unlocked.
UPD3: Autocommit mode is on. The numbers of BEGINs and COMMITs match (class Transaction and RAII take care of that). SQliteManager is able to connect to the DB while my app is running and make modifications to it.
| 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); a++) {
cout << word[a + after]; //and so is this
temp[a] = word[a + after];
cout << temp[a]; //and this
}
cout << endl << temp << endl; //but output here does not always match what I want
string returnString = temp;
return returnString;
}
The thing is, when the returned string is 7 chars or less, it works just as expected. When the returned string is 8 chars or more, then it starts spewing nonsense at the end of the expected output. For example, the lines
cout << after(1, "12345678") << endl;
cout << after(1, "123456789") << endl;
gives an output of:
7
22334455667788
2345678
2345678
8
2233445566778899
23456789�,�D~
23456789�,�D~
What can I do to fix this error, and are there any default C++ functions that can do this for me?
| 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, use the string constructor overload which accepts not just a char * but also a length.
Or, even better std::string::substr -- it will be easier and probably more efficient.
string after(int after, string word) {
return word.substr (after);
}
BTW, you don't need an after method, since exactly what you want already exists on the string class.
Now, to answer your specific question about why this only showed up on the 8th and later characters, it's important to understand how "C" strings work. A "C" string is a sequence of bytes which is terminated by a null (0) character. Library functions (like the string constructor you use to copy temp into a string instance which takes a char *) will start reading from the first character (temp[0]) and will keep reading until the end, where "the end" is the first null character, not the size of the memory allocation. For example, if temp is 6 characters long but you fill up all 6 characters, then a library function reading that string to "the end" will read the first 6 characters and then keep going (past the end of the allocated memory!) until it finds a null character or the program crashes (e.g. due to trying to access an invalid memory location).
Sometimes you may get lucky: if temp was 6 characters long and the first byte in memory after the end of your allocation happened to be a zero, then everything would work fine. If however the byte after the end of your allocation happened to be non-zero, then you'd see garbage characters. Although it's not random (often the same bytes will be there every time since they're filled by operations like previous method calls which are consistent from run to run of your program), but if you're accessing uninitialized memory there's no way of knowing what you'll find there. In a bounds checking environment (e.g. Java or C# or C++'s string class), an attempt to read beyond the bounds of an allocation will throw an exception. But "C" strings don't know where their end is, leaving them vulnerable to problems like the one you saw, or more nefarious problems like buffer overflows.
Finally, a logical follow-up question you'd probably ask: why exactly 8 bytes? Since you're trying to access memory that you didn't allocate and didn't initialize, whats in that RAM is what the previous user of that RAM left there. On 32-bit and 64-bit machines, memory is generally allocated in 4- or 8-byte chunks. So it's likely that the previous user of that memory location stored 8 bytes of zeroes there (e.g. one 64-bit integer zero) zeros there. But the next location in memory had something different left there by the previous user. Hence your garbage characters.
Moral of the story: when using "C" strings, be very careful about your null terminators and buffer lengths!
|
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 want to do, I would suggest using a pointer-to-member as this is a more portable technique. e.g.
int main()
{
int Foo::* pm = &Foo::b;
// Pointer to Foo somewhere else in the program
extern Foo* f;
int* p = &(f->*pm);
}
Note that this will only work if b isn't private in Foo, or alternative you could form the pointer to member in a member function or friend of Foo.
|
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 some are working & some are not.
Please give your answer or links that gives ultimate solution for handling different types of strings in visual c++.
| 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++ Cli System::String is the standard
All windows api that take strings expect null terminated cstyle string however depending on what frame work you are using you may not have to call many APi's directly especially if you are using .net
I believe there is another couple of string classes in ATL but I have not used that library much.
|
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;
iInputHeight = 160 & iInputWidth = 112
ppdata is an object for the following structure:
typedef struct ppConfigDataStruct
{
//---------------------------------------------------------------
// General controls
//---------------------------------------------------------------
UINT8 IntType;
// FIRSTMODULE_INTERRUPT: the interrupt will be
// rised once the first sub-module finished its job.
// FRAME_INTERRUPT: the interrput will be rised
// after all sub-modules finished their jobs.
//---------------------------------------------------------------
// Format controls
//---------------------------------------------------------------
// For input
idmaChannel inputIDMAChannel;
BOOL bCombineEnable;
idmaChannel inputcombIDMAChannel;
UINT8 inputcombAlpha;
UINT32 inputcombColorkey;
icAlphaType alphaType;
// For output
idmaChannel outputIDMAChannel;
CSCEQUATION CSCEquation; // Selects R2Y or Y2R CSC Equation
icCSCCoeffs CSCCoeffs; // Selects R2Y or Y2R CSC Equation
icFlipRot FlipRot; // Flip/Rotate controls for VF
BOOL allowNopPP; // flag to indicate we need a NOP PP processing
}*pPpConfigData, ppConfigData;
and idmaChannel structure is as follows:
typedef struct idmaChannelStruct
{
icFormat FrameFormat; // YUV or RGB
icFrameSize FrameSize; // frame size
UINT32 LineStride;// stride in bytes
icPixelFormat PixelFormat;// Input frame RGB format, set NULL
// to use standard settings.
icDataWidth DataWidth;// Bits per pixel for RGB format
UINT32 UBufOffset;// offset of U buffer from Y buffer start address
// ignored if non-planar image format
UINT32 VBufOffset;// offset of U buffer from Y buffer start address
// ignored if non-planar image format
} idmaChannel, *pIdmaChannel;
I want the formulae for ppData.inputIDMAChannel.UBufOffset & ppData.inputIDMAChannel.VBufOffset for YUV444
Thanks in advance
| 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 = htonl( messageSize );
if( isServer == true )
{
for( unsigned int i = ESocket_CLIENT0; i < ESocket_MAX; ++i )
{
// send the message size
if( m_Socket[ i ] > 0 )
{
if( send( m_Socket[ i ], (char*)&messageSize, sizeof( messageSize ), 0 ) == SOCKET_ERROR )
{
Log()->Write( ELogMessageType_ERROR, "[Application] Send error: %i to socket %i", WSAGetLastError(), m_Socket[ i ] );
continue;
}
// fix our message size back to host ordering
messageSize = ntohl(messageSize);
// send the actual message
if( send( m_Socket[ i ], pBuffer, messageSize, 0 ) == SOCKET_ERROR )
{
Log()->Write( ELogMessageType_ERROR, "[Application] Send error: %i to socket %i", WSAGetLastError(), m_Socket[ i ] );
continue;
}
Log()->Write( ELogMessageType_MESSAGE, "[Application] SEND: %s", pBuffer );
}
}
}
| 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 = messageSize; to_go > 0;)
{
int put = send(sock, buf, to_go);
if(put < 0)
{
perror("Socket send() error");
break;
}
buf += put;
to_go -= put;
}
This attempts to send the entire remaining message, until all of it has been sent. You will of course need to adapt for your specific variable names, do better error-handling, and so on; please view the above as a sketch.
|
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 reading back the log, I can figure out "ah, I wrote 100 complete enties, then I crashed on the 101th".
Thanks!
| 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 that if one thread segfaults, the whole process is destroyed along with the buffered data.
The solutions (for Linux) I know of are:
Transfer the logging data through a socket, without using buffering logging thread (syslog for example). In this case the OS will probably take care of the data, written to the socket, and even if your application crashes, the data should be received on the other end and logged successfully.
Don's use logging thread, every thread can log synchronously to a file. In this case the losses of the log data after the crash should be very small or none. It's slower though.
I don't know better solutions for this problem yet, it would be interesting to learn ones though.
|
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)
{
int i1=0, i2=0;
X myX(i1);
myX.f(i2);
...
}
As far as I understand, f() is changing the object myX, although it says to be const. How can I ensure my compiler complains when I do assign to y? (Visual C++ 2008)
Thank a lot!
| 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");
}
catch(...)
{
vMSWord = Variant::CreateObject("Word.Application");
}
vMSWord.OlePropertySet("Visible", true);
vWDocuments = vMSWord.OlePropertyGet("Documents");
vWDocument = vWDocuments.OleFunction("Open", vNom);
vSignets = vWDocument.OlePropertyGet("BookMarks");
if (vSignets.OleFunction("Exists", signet))
{
vSignet = vSignets.OleFunction("Item", signet);
vSignet.OleFunction("Select");
}
But once the document is opened, the user can no longer see when an other bookmark has been reached, since the application stays in background.
Does anyone know how i can do to make Word displayed in the foreground, or to light-up the document in the taskbar?
| 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 how to get the content of the match ?
The traditional way is
std::string result( mtch[1].first, mtch[1].second );
but i don't want to use this way.
I want to use the name of the subgroups as usual in Perl and in regex in general.
I tried this, but it didn't work.
std::string result( mtch["VAL"].first, mtch["VAL"].second );
Do you know how to get the value using the name of the subgroup?
Thanks
AFG
| 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 configuration used to build this release?
Is there a general way to find this information for any installation of GNU gcc? The gcc manual gives me no hint on this topic.
Thanks for your input!
| 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 --bindir=/usr/bin --sbindir=/usr/sbin --libex
ecdir=/usr/lib --datadir=/usr/share --localstatedir=/var --sysconfdir=/etc --inf
odir=/usr/share/info --mandir=/usr/share/man --datadir=/usr/share --infodir=/usr
/share/info --mandir=/usr/share/man -v --with-gmp=/usr --with-mpfr=/usr --enable
-bootstrap --enable-version-specific-runtime-libs --with-slibdir=/usr/bin --libe
xecdir=/usr/lib --enable-static --enable-shared --enable-shared-libgcc --disable
-__cxa_atexit --with-gnu-ld --with-gnu-as --with-dwarf2 --disable-sjlj-exception
s --enable-languages=ada,c,c++,fortran,java,objc,obj-c++ --disable-symvers --ena
ble-libjava --program-suffix=-4 --enable-libgomp --enable-libssp --enable-libada
--enable-threads=posix --with-arch=i686 --with-tune=generic --enable-libgcj-sub
libs CC=gcc-4 CXX=g++-4 CC_FOR_TARGET=gcc-4 CXX_FOR_TARGET=g++-4 GNATMAKE_FOR_TA
RGET=gnatmake GNATBIND_FOR_TARGET=gnatbind AS=/opt/gcc-tools/bin/as.exe AS_FOR_T
ARGET=/opt/gcc-tools/bin/as.exe LD=/opt/gcc-tools/bin/ld.exe LD_FOR_TARGET=/opt/
gcc-tools/bin/ld.exe --with-ecj-jar=/usr/share/java/ecj.jar
Thread model: posix
gcc version 4.3.4 20090804 (release) 1 (GCC)
|
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 these values manually, by
using xml_base::name(const Ch *) or
xml_base::value(const Ch *) functions.
Care must be taken to ensure that
lifetime of the string passed is at
least as long as lifetime of the
node/attribute. The easiest way to
achieve it is to allocate the string
from memory_pool owned by the
document. Use
memory_pool::allocate_string()
function for this purpose.
Now, I understand it's done this way for speed, but this feels like an car crash waiting to happen. The following code looks innocuous but 'name' and 'value' are out of scope when foo returns, so the doc is undefined.
void foo()
{
char name[]="Name";
char value[]="Value";
doc.append_node(doc.allocate_node(node_element, name, value));
}
The suggestion of using allocate_string() as per manual works, but it's so easy to forget.
Has anyone 'enhanced' RapidXML to avoid this issue?
| 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 to another if needed.
I created my own classes to represent the basic DOM entities (node, document, etc). Those classes use internally the pimpl idiom to use CPPDOM objects.
Since my node object contains the 'real' node object (from CPPDOM) I can manage anything as needed, so proper allocation and deallocation of strings wouldn't be a problem there.
Since my code is for CPPDOM, I don't think it would be much useful for you, but I can post it if you want.
BTW, if you already have too much code that already uses RapidXML you can reproduce its interfaces in your wrapper classes. I didn't do it because the code that used Xerces was not that long and I'd have to rewrite it anyway.
|
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.
So here is my working WinInet code:
DWORD dwError;
HINTERNET hOpen = NULL, hReq = NULL;
hOpen = InternetOpen(_T(""), INTERNET_OPEN_TYPE_DIRECT, _T(""), _T(""), 0);
if(hOpen == NULL)
{
dwError = GetLastError();
return false;
}
CString cstrCookies = _T("Cookie: JSESSIONID=") + cstrSession;
CString cstr = _T("https://") + cstrServer + _T("/list/") + cstrFileOrFolder;
hReq = InternetOpenUrl(hOpen, cstr, cstrCookies, -1L,
INTERNET_FLAG_SECURE | INTERNET_FLAG_NO_COOKIES, 0); // without NO_COOKIES I'll get a 401
if(hReq == NULL)
{
dwError = GetLastError();
InternetCloseHandle(hOpen);
return false;
}
DWORD dwCode, dwCodeSize;
dwCodeSize = sizeof(DWORD);
if(!HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwCode, &dwCodeSize, NULL))
{
dwError = GetLastError();
InternetCloseHandle(hReq);
InternetCloseHandle(hOpen);
return false;
}
InternetCloseHandle(hOpen);
InternetCloseHandle(hReq);
return dwCode == 200;
So I now want to do the same using the WinHTTP API. Here is what I have for the moment:
DWORD dwError = 0;
HINTERNET hConnect = NULL, hRequest = NULL;
hConnect = WinHttpConnect(m_hSession, cstrServer, INTERNET_DEFAULT_HTTPS_PORT, 0);
if (hConnect == NULL)
{
return false;
}
hRequest = WinHttpOpenRequest(hConnect, NULL, cstrMethod + _T("/list/") + cstrFileOrFolder,
NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (hRequest == NULL)
{
WinHttpCloseHandle(hConnect);
return false;
}
DWORD dwOptionValue = WINHTTP_DISABLE_COOKIES;
if (WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &dwOptionValue,
sizeof(dwOptionValue)) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
const CString cstrHeaders = _T("Cookie: JSESSIONID=") + cstrSession;
if (WinHttpAddRequestHeaders(hRequest, cstrHeaders, cstrHeaders.GetLength(),
WINHTTP_ADDREQ_FLAG_ADD) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
if (WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, -1L, WINHTTP_NO_REQUEST_DATA, 0,
0, 0) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
if (WinHttpReceiveResponse(hRequest, NULL) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
DWORD dwCode, dwCodeSize;
dwCodeSize = sizeof(DWORD);
if(!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwCode, &dwCodeSize, NULL))
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return dwCode == 200;
With that latter call I always receive a 401 but I should get a 200 like I do with the first method. I also found out that I get a 401 with the first call when I don't specify the INTERNET_FLAG_NO_COOKIES flag. So I suspect something with the cookie header is wrong. Do anyone see what I'm doing wrong? Or what is the difference between the two methods?
Thx...
| 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. So the constructed method call also contains \r\n and as therefore the user id is wrong I get the 401.
So I had to trim the user id string from the header before I could use it for further calls.
Well it's a little bit odd that the WinInet call accepted the \r\n.
|
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 existing methods of C, the
only thing that D can do is to
override them with its own versions.
If x is an object of class D, then we
can slice x with respect to C, by
throwing away all of the extensions
that made x a D, and keeping only the
C part. The result of the slicing is
always an object of class C.
slicing http://webdocs.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/slides/slice/slide1.gif
Design Principle: Slicing an object
with respect to a parent class C
should still produce a well-formed
object of class C.
Usage Warning: Even though D is-a C,
you must be careful. If you have a
argument type that is a C and you
supply a D it will be sliced if you
are doing call by value, pointer, or
reference. See the example below.
Note on virtual functions. Their
signatures are used to identify which
one to execute.
Watch out for the sliced = operator,
it can make the lhs inconsistent.
Also, the operator= is never virtual,
it wouldn't make sense. For example,
suppose classes A, B are both
subclasses of class C. Just because an
A is a C, and a B is a C, it doesn't
mean you can assign a B object to an A
object. Without run-time type
information you cannot make a safe
assignment.
|
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 part of the work should be done in native code anyway.
| 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 functions, if any, could be coded in C/C++ and exposed in python through the method of your choice (eg: boost-python), to follow the same approach.
But in my experience, python works just fine as a "composition" tool for such a use.
|
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 term& t1, const term& t2)
{
return t2.pow < t1.pow;
}
};
Can anyone tell me what's wrong?
| 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. Now i am worried to check in this code to repo as it might lead to runtime error due to formatting tool. My question is , will the size of object file be changed , if code formatting is changed.?
| 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 to insert preprocessor content, it should be byte-for-byte the same as well.
If the "reformatting" tool has actually done some micro-optimizations for you (caching repeated access to invariants in local vars, or undoing your having done that unnecessarily), that might affect the optimization choices the compiler makes, which can have an effect on the object file. But I wouldn't assume that that was the case.
|
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 audio to file. This works nicely, but I cannot figure out how to write to a memory buffer.
Is there such a memory sink filter or do I have to create it myself? (I would prefer one which is bundled with windows XP)
| 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 them.
|
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_ostream'. OK, so operator<< is returning ostream instead of ostringstream - how about casting it back to an ostringstream?
1) Is this cast safe?
f(static_cast<std::ostringstream&>(std::ostringstream() << "Value: " << 5).str().c_str()); // incorrect output
Now with this, it turns out for the operator<<("Value: ") call, it's actually calling ostream's operator<<(void*) and printing a hex address. This is wrong, I want the text.
2) Why does operator<< on the temporary std::ostringstream() call the ostream operator? Surely the temporary has a type of 'ostringstream' not 'ostream'?
I can cast the temporary to force the correct operator call too!
f(static_cast<std::ostringstream&>(static_cast<std::ostringstream&>(std::ostringstream()) << "Value: " << 5).str().c_str());
This appears to work and passes "Value: 5" to f().
3) Am I relying on undefined behavior now? The casts look unusual.
I'm aware the best alternative is something like this:
std::ostringstream ss;
ss << "Value: " << 5;
f(ss.str().c_str());
...but I'm interested in the behavior of doing it in one line. Suppose someone wanted to make a (dubious) macro:
#define make_temporary_cstr(x) (static_cast<std::ostringstream&>(static_cast<std::ostringstream&>(std::ostringstream()) << x).str().c_str())
// ...
f(make_temporary_cstr("Value: " << 5));
Would this function as expected?
| 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. seekp is a member function returning a std::ostream&. Would probably better to write this generally
template<typename T>
struct lval { T t; T &getlval() { return t; } };
f(static_cast<std::ostringstream&>(
lval<std::ostringstream>().getlval() << "Value: " << 5).str().c_str());
The reason that without anything it takes the void*, is because that operator<< is a member-function. The operator<< that takes a char const* is not.
|
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 done with it, I should call CloseHandle() on it. But for any reasonably complex loading function there will be dozens of possible exit points, not to mention exceptions.
So it would be great if I could wrap the handle in some kind of wrapper class which would automatically call CloseHandle() once execution left the scope. Even better - it could do some reference counting so I can pass it around in and out of other functions, and it would release the resource only when the last reference left scope.
The concept is simple - but is there something like that in the standard library? I'm using Visual Studio 2008, by the way, and I don't want to attach a 3rd party framework like Boost or something.
| 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: It'd have to be parametrizable so you can specify any pair of functions, and any number of arguments to them. Just instantiating such an object would likely take as many lines of code as the above class definition.
Of course, C++0x might tip the balance somewhat with the addition of lambda expressions. Two lambda expressions could easily be passed to a generic wrapper class, so once C++0x supports comes around, we might see such a generic RAII class added to Boost or something.
But at the moment, it's easier to just roll your own whenever you need it.
As for adding reference counting, I'd advise against it. Reference counting is expensive (suddenly your handle has to be dynamically allocated, and reference counters have to be maintained on every assignment), and very hard to get right. It's an area just bursting with subtle race conditions in a threaded environment.
If you do need reference counting, just do something like boost::shared_ptr<FileWrapper>: wrap your custom ad-hoc RAII classes in a shared_ptr.
|
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 thing boost docs say most functions do not require complete type, but constructor requires, so there is no way of using it. http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/smart_ptr.htm)
Can can I solve this? Thank you.
| 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 constructor of shared_ptr is called with the default deleter, it will instantiate a class that contains the line delete p; - and for this code to be correct, p must not be incomplete. The destructor will call this deleter code indirectly, so it doesn't depend on the completeness of the type.
However if you pass your own deleter, the requirements of your own deleter will apply. Be sure to define CustomDeleter after lua_State has become completed.
|
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)
{
return a + b;
}
[DllImport("tester.dll", SetLastError = true)]
public static extern int testDelegate(AddIntegersDelegate callBackProc, int a, int b);
public static void Main(string[] args)
{
int result = testDelegate(AddIntegers, 4, 5);
Console.WriteLine("Code returned:" + result.ToString());
}
When I start this small app, I get the message from the header of this post. Can someone help, please?
Thanks in advance,
D
| 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 diagnostic in the debug build of your C/C++ code.
To fix it on the C/C++ side:
typedef int (__stdcall * Callback)(int, int);
extern "C" _declspec(dllexport) int testDelegate(Callback addFunction, int a, int b)
{
int res = addFunction(a, b);
return res;
}
To fix it on the C# side:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int AddIntegersDelegate(int number1, int number2);
|
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_background.jpeg
Here is my code:
void MyDelegate::paint( QPainter* painter, const QStyleOptionViewItem& opt, const QModelIndex& index ) const
{
QBrush backBrush;
QColor foreColor;
bool hover = false;
if ( opt.state & QStyle::State_MouseOver )
{
backBrush = opt.palette.color( QPalette::Highlight ).light( 115 );
foreColor = opt.palette.color( QPalette::HighlightedText );
hover = true;
}
QStyleOptionViewItemV4 option(opt);
initStyleOption(&option, index);
painter->save();
const QStyle *style = option.widget ? option.widget->style() : QApplication::style();
const QWidget* widget = option.widget;
if( hover )
{
option.backgroundBrush = backBrush;
}
painter->save();
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, widget);
painter->restore();
switch( index.column() )
{
case 0: // we want default behavior
style->drawControl(QStyle::CE_ItemViewItem, &option, painter, widget);
break;
case 1:
// some custom drawText
break;
case 2:
// draw a QStyleOptionProgressBar
break;
}
painter->restore();
}
The result is that each individual cell receives the mousedover background only when the mouse is over it, and not the entire row. It is hard to describe so here is a screenshot:
The result of the above code http://www.binaryelysium.com/images/loader_bg.jpeg
In that picture the mouse was over the left most cell, hence the highlighted background.. but I want the background to be drawn over the entire row.
How can I achieve this?
Edit: With some more thought I've realized that the QStyle::State_MouseOver state is only being passed for actual cell which the mouse is over, and when the paint method is called for the other cells in the row QStyle::State_MouseOver is not set.
So the question becomes is there a QStyle::State_MouseOver_Row state (answer: no), so how do I go about achieving that?
| 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 the std::vector?
}
Obviously, I can call w_.resize() and then loop over the elements, or call std::copy(). Are there any better methods?
| 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://google-styleguide.googlecode.com/svn/trunk/cppguide.html
http://www.boost.org/development/requirements.html
Note: This is NOT a discussion about which style is best... only a call for official style guides that people currently use. Please refrain from bashing other style guides that you don't like.
Side question: Is there a good tool that can examine source code and tell if it matches a given style guide?
| 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 a __cxa_atexit()) and put all constructor and destructor calls to .ctors and .dtors sections?
| 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 .ctors section, which then calls __static_initialization_and_destruction_0 on each translation unit.
The issue seems to be a lot more complex than that though; gcc has to deal with individual object files in an archive, and I think this is how they keep the linker from optimizing out those calls.
|
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 struct in winnt.h.
| 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 Definition Rule).
EDIT: I also forgot the extern "C".
|
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;
//sending data to the server
if (send(socket, &data_snd, sizeof(data_snd), 0) < 0) {
cerr << "send() failed" ;
exit(1);
}
//receiving data from the client
if (recv(socket, &data_rec, sizeof(data_rec), 0) < 0) {
cerr << "recv() failed";
exit(1);
}
Thanks for help and replies-
| 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?
return true;
// ... Some other comparisons that Base does not know about ...
return false;
}
};
| 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;
ex.solve();
}
Each time I create a new class from an exercise, I have to come and modify this file to change the name of the included header as well as the class i'm instantiating.
So my questions are:
Can I include all headers in the directory so at least I don't have to change the #include line?
Better yet, can I rewrite my solution so that I don't even have to touch main.cpp, without having one file with all the code for every exercise in it?
Update:
I ended up following Poita_'s advice to generate main.cpp via a script.
Since I'm using an IDE (Visual Studio), I wanted this integrated with it, so did a bit of research on how. For those interested in how, read on (it was fairly, but not entirely, straightforward).
Visual Studio lets you use an external tool via the Tools -> External Tools menu, and contains a bunch of pre-defined variables, such as $(ItemFileName), which can be passed on to the tool. So in this instance I used a simple batch file, and it gets passed the name of the currently selected file in Visual Studio.
To add that tool to the toolbar, right click on the toolbar, select Customize -> Commands -> Tools, and select the "External Command X" and drag it to the toolbar. Substitute X with the number corresponding to the tool you created. My installation contained 5 default pre-existing tools listed in Tools -> External Tools, so the one I created was tool number 6. You have to figure out this number as it is not shown. You can then assign an icon to the shortcut (it's the BuildMain command shown below):
|
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 = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxTextCtrlNameStr)
My Code:
MainFrame::MainFrame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title)
{
wxButton * Centigrade = new wxButton(this,
BUTTON_CENTIGRADE,
_T("to Centigrade"),
wxPoint(20, 20),
wxDefaultSize,
0);
wxButton * Fahrenheit = new wxButton(this,
BUTTON_FAHRENHEIT,
_T("to Fahrenheit"),
wxPoint(20, 40),
wxDefaultSize,
0);
F_txt = new wxTextCtrl(this,
TXT_F_Main,
"0",
wxDefaultPosition,
wxDefaultSize,
wxDefaultValidator,
wxTextCtrlNameStr); /***********************************************/
C_txt = new wxTextCtrl(this,
TXT_C_Main,
"0",
wxDefaultPosition,
wxDefaultSize,
wxDefaultValidator,
wxTextCtrlNameStr); /***********************************************/
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
| 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 has a default. If you are not going to use window names, just don't pass anything, as you don't pass the name to wxButton constructor (defaults to "button").
|
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, except that
when until encounters a jump, it
automatically continues execution
until the program counter is greater
than the address of the jump.
This means that when you reach the end
of a loop after single stepping though
it, until makes your program continue
execution until it exits the loop. In
contrast, a next command at the end of
a loop simply steps back to the
beginning of the loop, which forces
you to step through the next
iteration.
|
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 a question with a high probability of 'No'. Just thought of asking this to capitalize on the very rare probability :))
On request, i am posting a sample code. Here i needed to track the enquiry, if it comes from one specific thread. I assume that, if i create that as my first thread, then it will get the thread id 1.
template<ACE_INT32 ThreadId>
bool enquire_presence( Manager* man)
{
return check(man);
}
template<>
bool enquire_presence<1>( Manager* man )
{
track_enquiry(man);
return check(man);
}
Thanks,
Gokul.
| 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 functions like this:
set_intersection(v_higher.begin(), v_higher.end(), neighbors[w].begin(), neighbors[w].end(),
insert_iterator<node_set>(tmp1, tmp1.begin()));
should they work seamlessly with both set and hash_set?
| 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 cannot be satisfied.
See tr1::unordered_set union and intersection on how to intersect unordered_sets.
|
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 Parenthesis, can I define a macro that replaces
MyClass x = new MyClass();
with
#ifdef MSC_VER
if(!(MyClass x = new MyClass())
{
throw new std::bad_alloc();
}
#else
MyClass x = new MyClass();
#endif
(or something equivalent), AND works in BOTH MS C++ and G++ ?
Or alternatively if that is not possible, a batch file to run over the Code to do this?
I have become rather dependent on this exception being thrown.
| 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 malloc and free. If you're doing conditional compilation for G++ and MSVC, you can also use HeapAlloc and HeapFree instead of malloc and free for a more WinAPI-oriented approach.
#include <iostream>
#include <cstdlib>
void *operator new(unsigned int size) throw (std::bad_alloc) {
void *ptr = malloc(size);
if (!ptr)
throw std::bad_alloc();
return ptr;
}
void operator delete(void *ptr) throw () {
free(ptr);
}
// Sample code to test the implementation.
int main(int argc, char **argv) {
int *values[10];
for (int i = 0; i < 10; ++i)
values[i] = new int(i);
for (int i = 0; i < 10; ++i)
std::cout << *values[i] << std::endl;
for (int i = 0; i < 10; ++i)
delete values[i];
return 0;
}
|
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 ReallyLongLastName T
Instead, by including only "\t"'s in my cout statement I can only manage to get
Name Last Name Middle initial
Bob Jones M
Joe ReallyLongLastName T
or
Name Last Name Middle initial
Bob Jones M
Joe ReallyLongLastName T
What else would I need to do?
EDIT: So I get that I should first count the maximum width of each column I want displayed, and then adding padding spaces accordingly. But how, and with what functions, can I go about doing this? Should I simply count the number of chars in a string and then go from there?
| 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? A free and open source would be preferred , but I'll use a commercial solution if it will get the job done.
| 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 application code derives from ConnectionBase and overrides OnEvent for the events it cares about. I can do this because the set of types is known. OnEvent is private because the user never calls it, the class creates a thread that calls it as a callback. The C++ code works.
I have wrapped this in boost.python, I can import it and publish from python. I want to create the equivalent of the following in python :
class ConnectionDerived
{
public:
ConnectionDerived();
private:
virtual void OnEvent(const Overload_b&)
{
// application code
}
};
I don't care to (do not want to) expose the default OnEvent functions, since they're never called from application code - I only want to provide a body for the C++ class to call.
But ... since python isn't typed, and all the boost.python examples I've seen dealing with internals are on the C++ side, I'm a little puzzled as to how to do this. How do I override specific overloads?
| 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) {
if (override f = get_override("OnEventOverloadA"))
f(obj);
}
void OnEvent(const Overload_b &obj) {
if (override f = get_override("OnEventOverloadB"))
f(obj);
}
};
BOOST_PYTHON_MODULE(yourmodule) {
class_<ConnectionBaseWrap, boost::noncopyable>("ConnectionBase")
//Your additional definitions here.
;
}
Some notes:
Since you won't be calling the base class's OnEvent function from Python, you don't need to define it with .def. If you did want to define it, you'd need to give the two overloaded versions different names, like here.
The two overloads will call different Python methods: OnEventOverloadA and OnEventOverloadB. Another option is to have them both call the same method OnEvent, and then one Python method will override both overloads.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.