question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,886,777 | 1,886,787 | What are .rc2 files used for in Visual Studio | I am new to Windows environment of development. I see a lot of .rc2 files used where a mapping is performed against some MACRO type constants to strings.
Q1. Why are these .rc2 files used?
Can someone give me a start on these.
| From MSDN:
The RC2 file can be included at the
top of the RC file in a project. An
RC2 file is useful for including
resources used by several different
projects. Instead of having to create
the same resources several times for
different projects, you can put them
in an RC2 file and include the RC2
file into the main RC file.
|
1,886,913 | 1,886,929 | How do you try out small/simple C or C++ source codes? | It is very easy on Linux to fire-up vi and write a 100-200 lines of code, compile and see the results: ie. Trying small simple examples of C/C++ code.
On windows however, I like Visual Studio but to use it you have create a new solution then a project which then creates a new folder, generates very large PDB and caching files and a small example of 100-200 LOC becomes a 20Mb large project(?!) after compilation.
So the question is how do you write this kind of small codes on Windows? Possibly Cygwin or Dev-C++ (which is not active since 2004?).
| You can compile from the command line using cl.exe. See the MSDN article How to: Compile a Native C++ Program from the Command Line for detailed instructions.
|
1,887,041 | 1,887,113 | What is a good way to test a file to see if its a zip file? | I am looking as a new file format specification and the specification says the file can be either xml based or a zip file containing an xml file and other files.
The file extension is the same in both cases. What ways could I test the file to decide if it needs decompressing or just reading?
| The zip file format is defined by PKWARE. You can find their file specification here.
Near the top you will find the header specification:
A. Local file header:
local file header signature 4 bytes (0x04034b50)
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
file name length 2 bytes
extra field length 2 bytes
file name (variable size)
extra field (variable size)
From this you can see that the first 4 bytes of the header should be the file signature which should be the hex value 0x04034b50. Byte order in the file is the other way round - PKWARE specify that "All values are stored in little-endian byte order unless otherwise specified.", so if you use a hex editor to view the file you will see 50 4b 03 04 as the first 4 bytes.
You can use this to check if your file is a zip file. If you open the file in notepad, you will notice that the first two bytes (50 and 4b) are the ASCII characters PK.
|
1,887,097 | 1,887,178 | Why aren't variable-length arrays part of the C++ standard? | I haven't used C very much in the last few years. When I read this question today I came across some C syntax which I wasn't familiar with.
Apparently in C99 the following syntax is valid:
void foo(int n) {
int values[n]; //Declare a variable length array
}
This seems like a pretty useful feature. Was there ever a discussion about adding it to the C++ standard, and if so, why it was omitted?
Some potential reasons:
Hairy for compiler vendors to implement
Incompatible with some other part of the standard
Functionality can be emulated with other C++ constructs
The C++ standard states that array size must be a constant expression (8.3.4.1).
Yes, of course I realize that in the toy example one could use std::vector<int> values(m);, but this allocates memory from the heap and not the stack. And if I want a multidimensional array like:
void foo(int x, int y, int z) {
int values[x][y][z]; // Declare a variable length array
}
the vector version becomes pretty clumsy:
void foo(int x, int y, int z) {
vector< vector< vector<int> > > values( /* Really painful expression here. */);
}
The slices, rows and columns will also potentially be spread all over memory.
Looking at the discussion at comp.std.c++ it's clear that this question is pretty controversial with some very heavyweight names on both sides of the argument. It's certainly not obvious that a std::vector is always a better solution.
| There recently was a discussion about this kicked off in usenet: Why no VLAs in C++0x.
I agree with those people that seem to agree that having to create a potential large array on the stack, which usually has only little space available, isn't good. The argument is, if you know the size beforehand, you can use a static array. And if you don't know the size beforehand, you will write unsafe code.
C99 VLAs could provide a small benefit of being able to create small arrays without wasting space or calling constructors for unused elements, but they will introduce rather large changes to the type system (you need to be able to specify types depending on runtime values - this does not yet exist in current C++, except for new operator type-specifiers, but they are treated specially, so that the runtime-ness doesn't escape the scope of the new operator).
You can use std::vector, but it is not quite the same, as it uses dynamic memory, and making it use one's own stack-allocator isn't exactly easy (alignment is an issue, too). It also doesn't solve the same problem, because a vector is a resizable container, whereas VLAs are fixed-size. The C++ Dynamic Array proposal is intended to introduce a library based solution, as alternative to a language based VLA. However, it's not going to be part of C++0x, as far as I know.
|
1,887,134 | 1,889,451 | Can a Silverlight client talk to a C++ server? | Our company wants to transform our current user interface to a web client. We are considering to use Microsoft's Silverlight for this, but it will need to communicate with our legacy C++ server application (native C++, not C++/CLI). I am wondering whether it would be feasible to write such an IPC library by hand, our otherwise whether there are ready-made IPC protocols available both as a C++ and a Silverlight library.
Update: I emphasize the programming languages used because they determine which libraries can be used. For example, a library written for .NET's intermediate language cannot be used by a native C++ application.
| You can certainly do this -- on my desktop right now, I'm running a C++ server application in one instance of Visual Studio, a Silverlight application in a second instance, and the Silverlight app is talking to the C++ server over sockets. However, there are several significant caveats:
(1) Silverlight will only talk to a small range of ports (4502-4532), so you may need to modify the server (or insert a proxy of some sort) to allow Silverlight to talk to it;
(2) The server has to serve up a socket policy file on port 943; and
(3) You can't easily use traditional higher-level access mechanisms like RPC or what-not. If the C++ server expects a particular protocol, you're going to have to write all the stuff yourself in Silverlight/C#. That's not necessarily rocket science, but if you're not familiar with sockets programming, there's a learning curve. Expect to spend a lot of time dealing with byte[] arrays, Buffer.BlockCopy(), BitConverter.GetBytes(), and what-not.
An alternative would be to wrap the C++ server with a WCF server, and then call the WCF server from Silverlight. WCF is generally a lot slower than sockets, but it's also a lot easier to call in Silverlight.
|
1,887,398 | 1,887,558 | C++ class hierarchy for collection providing iterators | I'm currently working on a project in which I'd like to define a generic 'collection' interface that may be implemented in different ways. The collection interface should specify that the collection has methods that return iterators by value. Using classes that wrap pointers I came up with the following (greatly simplified):
Collection.h
class Collection
{
CollectionBase *d_base;
public:
Collection(CollectionBase *base);
Iterator begin() const;
};
inline Iterator Collection::begin() const
{
return d_base->begin();
}
CollectionBase.h
class CollectionBase
{
public:
virtual Iterator begin() const = 0;
virtual Iterator end() const = 0;
};
Iterator.h
class Iterator
{
IteratorBase *d_base;
public:
bool operator!=(Iterator const &other) const;
};
inline bool Iterator::operator!=(Iterator const &other) const
{
return d_base->operator!=(*other.d_base);
}
IteratorBase.h
class IteratorBase
{
public:
virtual bool operator!=(IteratorBase const &other) const = 0;
};
Using this design, different implementations of the collection derive from CollectionBase and can return their custom iterators by returning an Iterator that wraps some specific implementation of IteratorBase.
All is fine and dandy so far. I'm currently trying to figure out how to implement operator!= though. Iterator forwards the call to IteratorBase, but how should the operator be implemented there? One straightforward way would be to just cast the IteratorBase reference to the appropriate type in implementations of IteratorBase and then perform the specific comparison for the implementation of IteratorBase. This assumes that you will play nice and not pass two different types of iterators though.
Another way would be to perform some type of type checking that checks if the iterators are of the same type. I believe this check will have to be made at run-time though, and considering this is an iterator I'd rather not perform expensive run time type checking in operator!=.
Am I missing any nicer solutions here? Perhaps there are better alternative class designs (the current design is an adaptation from something I learned in a C++ course I'm taking)? How would you approach this?
Edit: To everyone pointing me to the STL containers: I am aware of their existence. I cannot use these in all cases however, since the amounts of data I need to process are often enormous. The idea here is to implement a simple container that uses the disk as storage instead of memory.
| If you want to use inheritance for your iterators, I would recommend you to use a different approach than STL's begin()/end().
Have a look on IEnumerator from .NET framework, for example. (MSDN documentation)
Your base classes can look like this:
class CollectionBase
{
// ...
virtual IteratorBase* createIterator() const = 0;
};
class IteratorBase
{
public:
virtual bool isEnd() const = 0;
virtual void next() const = 0;
};
// usage:
for (std::auto_ptr<IteratorBase> it = collection.createIterator(); !it->isEnd(); it->next)
{
// do something
}
If you want to stay with begin()/end(), you can use dynamic_cast to check that you have a right type:
class MyIteratorBaseImpl
{
public:
virtual bool operator!=(IteratorBase const &other) const
{
MyIteratorBaseImpl * other2 = dynamic_cast<MyIteratorBaseImpl*>(&other);
if (!other2)
return false; // other is not of our type
// now you can compare to other2
}
}
|
1,887,464 | 1,887,485 | C++ preprocessor variable | I'm using the SKELETON_JAR variable on my C++ code in one header. However, I want to allow the user to define the place of the jar in the compile time easily. I think the easiest way to do that is to put this define in makefile is that so?
#define SKELETON_JAR "./Util.jar"
| In your code:
#ifndef SKELETON_JAR
#define SKELETON_JAR "./Util.jar" // default path
#endif
and then in the makefile use CPPFLAGS:=-DSKELETON_JAR="./Util.jar".
Of course you have to make sure CPPFLAGS are passed to the compiler as part of the compile rule which is the case if you're using the default implicit rules.
From GNU Make documentation:
Compiling C programs
n.o is made automatically from n.c with a command of the form `$(CC) -c $(CPPFLAGS) $(CFLAGS)'
|
1,888,003 | 1,888,213 | How to implement a tiny RTSP server? | I am implementing a client/server application where video streaming occurs between two computers (in one direction). I would like to have the server publish an SDP file when it starts streaming. The client would then be able to download this SDP file and use it to get the stream. In order to implement this it seems I need to include a RTSP server in my server application.
I am planning to use either libVLC or GStreamer for the client. Both are able to get incoming video streams using the info from an SDP file.
Server-side I don't really know where to start. Can anyone recommend a good C++ library that would allow me to create a small RTSP server?
| Use Live555 LGPL library or for fun, read the RFC and implement :-)
|
1,888,247 | 1,888,259 | Why does my inputchar function keep looping? | #include <iostream>
using namespace std;
struct Node
{
char item;
Node *next;
};
void inputChar ( Node * );
void printList (Node *);
char c;
int main()
{
Node *head;
head = NULL;
c = getchar();
if ( c != '.' )
{
head = new Node;
head->item = c;
inputChar(head);
}
printList(head);
return 0;
}
void inputChar(Node *p)
{
getchar();
while ( c != '.' )
{
p->next = new Node;
p->next->item = c;
inputChar(p->next);
}
p->next = new Node; // dot signals end of list
p->next->item = c;
}
void printList(Node *p)
{
if(p = NULL)
cout << "empty" <<endl;
else
{
while (p->item != '.')
{
cout << p->item << endl;
printList(p->next);
}
}
}
I am trying to make a linked list of characters that are input by the user. A period indicates the end of the input. My program keeps looping on the inputChar function. Any ideas?
| Perhaps you should add:
c = getchar();
Still, it's kind of dangerous what you are doing. In some platforms, getchar() will return immediately after consuming the ENTER key of the previous getchar() call. So you should consider that in your loop. Perhaps adding an extra getchar() to the inputChar function?
Also, what Paul wrote is true. You should change your while loop with a simple if.
|
1,888,293 | 1,888,337 | union members may not have constructors, but `std::pair` okay? | union members may not have destructors or constructors. So I can't template the following class Foo on my own MyClass if MyClass has a constructor:
template<class T>
struct Foo {
T val;
Foo(T val_) : val(val_) {}
size_t hash() const {
union {T f; size_t s;} u = { val };
return u.s;
}
};
struct MyClass {
bool a;
double b;
MyClass(bool a_, double b_) : a(a_), b(b_) {}
};
If I do it anyway I get this error:
member 'MyClass Foo<T>::hash() const
[with T = MyClass]::<anonymous union>::f' with constructor
not allowed in union
To get around it I created MyClass with an awkward construction function, which copies the thing around first:
struct MyClass {
bool a;
double b;
};
MyClass createMyClass(bool a, double b) {
MyClass m;
m.a = a;
m.b = b;
return m;
}
But I'm wondering if there is a better way than using this createMyClass function. A constructor would be more efficient, and as a critical component MyClass and Foo<MyClass> are constructed millions of times in my code.
std::pair
I'm also a bit surprised that it is possible to use std::pair in the union:
Foo<std::pair<bool, double> > f2(std::make_pair(true, 3.12));
To my knowledge, std::pair (see code) has a constructor?
| EDIT: My original stance on std::pair was wrong, it shouldn't be allowed in a union. For a class to be a valid member of a union it must have a trivial constructor according to standard 9.5.1. The definition of a trivial constructor is this, from paragraph 12.1.5:
If there is no user-declared
constructor for class X, a default
constructor is implicitly declared.
An implicitly-declared default
constructor is an inline public member
of its class. A constructor is trivial
if it is an implicitly-declared
default constructor and if:
its class has no virtual functions and no virtual base classes, and
all the direct base classes of its class have trivial constructors, and
for all the nonstatic data members of its class that are of class type
(or array thereof), each such class
has a trivial constructor
Paragraph 20.2.2.2 states that the following constructor must be available in a pair:
pair(const T1& x, const T2& y);
as soon as this constructor is supplied no default constructor will be implicitly declared.
The funny thing here is that my compiler (Visual Studio 2008) seems to give std::pair special treatment. If I copy the code from the std::pair implementation and place it in my own namespace foo the unions don't work :)
namespace foo {
template<class _Ty1, class _Ty2> struct pair {
typedef _Ty1 first_type;
typedef _Ty2 second_type;
pair() : first(_Ty1()), second(_Ty2()) {
}
}
}
//This doesn't work in VC2008
union Baz {
foo::pair<bool, double> a;
int b;
}
//This works in VC2008
union Buz {
std::pair<bool, double> a;
int b;
}
Your solution is a common way of getting around this problem. I usually prepend the class name with a C (short for construct) to partially mimic the ordinary constructor syntax, this would in your case become CMyClass(a, b).
As Steve and Matthieu has pointed out you're not using a very good hash function though. Firstly there's no real guarantee (I think, please correct me if I'm wrong) that f and s in the union will even partially occupy the same memory space, and secondly even if they in practice will probably will share the first min(sizeof(s), sizeof(f)) bytes this means that for MyClass you're only hashing on part of the value. In this case you will hash on the value of the bool a, in this case there's two options:
Your compiler uses int as the internal representation for the bool in which case your hash function will only return two values, one for true and one for false.
Your compiler uses char as the internal representation for the bool. In this case the value will probably be padded to at least sizeof(int), either with zeroes in which case you have the same situation as 1. or with whatever random data is on the stack when MyClass is allocated which means you get random hash values for the same input.
If you need to hash by the entire value of T I would copy the data into a temporary buffer like Steve suggests and then use one of the variable-length hash functions discussed here.
|
1,888,652 | 1,888,665 | How can I use iteration instead of recursion to input values into a linked list? | Ok so let's say we have a linked list of characters with a head pointer. How can I create a loop to enter a string of characters into the linked list? My problem is when I think of head and head->next and head->next->next . . . it only seems natural to use a recursive function to set the characters at each node.
| It's trivial to do it with iteration. You would just start at head, and use a loop to iterate over the list by doing current = current->next, until you hit a NULL.
Basically something like:
node* n = head;
while (n) {
// ... do something with n
n = n->next;
}
|
1,888,672 | 1,889,395 | Calling functions in a Lua table from C++ | I have for example, a Lua table/object:
bannana
And this Lua table has a function inside it called chew, that takes a parameter
bannana.chew(5)
I have also used SWIG, and have for example a class CPerson:
class CPerson {
public:
// ....
void Eat();
// ....
};
I can obtain an instance of this object from Lua:
person = engine:getPerson()
What I need to be able to do is the following Lua code:
person = engine:getPerson()
person:Eat(bannana)
Where person:eat would call the chew function in the bannana table, passing a parameter.
Since CPerson is implemented in C++, what changes are needed to implement Eat() assuming the CPerson class already has a Lua state pointer?
Edit1: I do not want to know how to bind C++ classes to Lua, I already have SWIG to do this for me, I want to know how to call Lua functions inside Lua tables, from C++.
Edit2: The CPerson class and bannana table, are both general examples, it can be assumed that the CPerson class already has a LuaState pointer/reference, and that the function signature of the Eat method can be changed by the person answering.
| Ignoring any error checking ...
lua_getglobal(L, "banana"); // or get 'banana' from person:Eat()
lua_getfield(L, -1, "chew");
lua_pushinteger(L, 5);
lua_pcall(L, 1, 0, 0);
|
1,888,915 | 1,889,048 | How to write these classes using Google's protobuf? | I have just come accross Google's Protocol buffers. It seems to be the solution for a C++ backend application I am writing. Problem is I cant seem to find anything regarding vector types. The documentation mentions repeated_types, but I cant seem to find anything.
Supposing I have these set of classes:
class UnifiedBinaryHeader
{
public:
UnifiedBinaryHeader();
void Serialize(std::ostream& output) const;
void Deserialize(std::istream& input);
private:
wxString m_name;
wxDateTime m_time;
};
struct UnifiedBinaryRow
{
wxDateTime date;
float value;
UnifiedBinaryRow()
{
value= 0;
}
void Serialize(std::ostream& output) const;
void Deserialize(std::istream& input);
};
class UnifiedBinaryRowCollection
{
private:
typedef std::vector<UnifiedBinaryRow> UnifiedBinaryRowVector;
public:
typedef UnifiedBinaryRowVector::iterator iterator;
typedef UnifiedBinaryRowVector::const_iterator const_iterator;
UnifiedBinaryRowCollection();
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
UnifiedBinaryRowCollection& AddRow(const UnifiedBinaryRow& row);
size_t NumRows() const;
private:
UnifiedBinaryRowVector m_rows;
};
class UnifiedBinaryFormat
{
public:
UnifiedBinaryFormat();
UnifiedBinaryHeader& Header();
const UnifiedBinaryHeader& Header() const;
UnifiedBinaryFormat& Header(UnifiedBinaryHeader& header);
UnifiedBinaryRowCollection& Rows();
const UnifiedBinaryRowCollection& Rows() const;
UnifiedBinaryFormat& Rows(const UnifiedBinaryRowCollection& rows);
void Serialize(std::ostream& output) const;
void Deserialize(std::istream& input);
private:
UnifiedBinaryHeader m_header;
UnifiedBinaryRowCollection m_rows;
};
How may I write a .proto file for these classes, seeing as I am using a lot of members that are vectors. Any help in "porting" these classes to a .proto file I can use will be much appreciated.
| I think you misunderstood the philosophy.
IMHO Google's Protocol Buffers is meant to produce 'messages' class that are distinct from your application classes. Note that Protobuf is NOT a serialization library (though it may be used as such). It is a messaging library, which allows to exchange messages between different subsystems / languages.
So, proto will generate messages class, and then for your serialization/deserialization it will convert the stream to an object of its own class and your job is to convert the proto object to your actual object, or group of objects.
It's a nice way to decouple the actual implementation of the class from the serialization / deserialization mechanism imo.
|
1,889,137 | 1,889,314 | Inherit from a template parameter and upcasting back in c++ | I have tried to use this code in VS2008 (and may have included too much context in the sample...):
class Base
{
public:
void Prepare() {
Init();
CreateSelectStatement();
// then open a recordset
}
void GetNext() { /* retrieve next record */ }
private:
virtual void Init() = 0;
virtual string CreateSelectStatement() const = 0;
};
class A : public Base
{
public:
int foo() { return 1; }
private:
virtual void Init() { /* init logic */ }
virtual string CreateSelectStatement() { /* return well formed query */ }
};
template<typename T> class SomeValueReader : protected T
{
public:
void Prepare() { T::Prepare(); }
void GetNext() { T::GetNext(); }
T& Current() { return *this; } // <<<<<<<< this is where it is interesting
SomeValue Value() { /* retrieve values from the join tables */ }
private :
string CreateSelectStatement() const
{
// special left join selection added to T statement
}
};
void reader_accessAmemberfunctions_unittest(...)
{
SomeValueReader<A> reader();
reader.Prepare();
reader.GetNext();
A a = reader.Current();
int fooresult = a.foo();
// reader.foo() >> ok, not allowed
Assert::IsEqual<int>( 1, fooresult );
};
This works as expected, i.e. having access to "A" member functions and fooresult returning 1. However, an exception is thrown when objects are deleted at the end of the unittest function:
System.AccessViolationException:
Attempted to read or write protected
memory. This is often an indication
that other memory is corrupt
If I change the return type of Current() function to :
T* Current()
{
T* current = dynamic_cast<T*>(this);
return current;
}
then everything is ok and the unit test ends with no access violation. Does someone can tell me what was wrong with the first Current() implementation? Thanks, bouchaet.
| After changing CreateSelectStatement to return a value for the implemented functions (not the pure virtual)
string CreateSelectStatement() const { return ""; }
and changing the declaration of reader (the declaration you have should strictly be interpreted as a function prototype in C++)
SomeValueReader<A> reader;
The above example compiles and executes without errors using gcc, leading me to believe the actual error may not be present in the source above. Unfortunately I'm unable to test with VC at the moment.
I can't see any obvious reason why the change you have suggested would resolve the issue, the only other error I can see is that Base does not have a virtual destructor declared meaning that if you ever delete a Base* (or some other derived class that is not the actual type) the incorrect destructor(s) will fire. You should declare it as
virtual ~Base() {}
even if it's empty.
Stylistically it's also a little odd to use templates and virtual functions in this fashion because here you're using the template to resolve functions at compile time. I can't see a reason why SomeValueReader needs to derive from T (rather than have a member variable) either.
|
1,889,170 | 1,889,272 | Can someone help spot the errors in my low lock list? | I've written a low lock list in C++ on windows 32-bit. I'm getting BIG improvements over using critical sections but I'd like someone to sanity check that what I'm doing is correct and there aren't any errors in what I've done:
#ifndef __LOW_LOCK_STACK_H_
#define __LOW_LOCK_STACK_H_
template< class T > class LowLockStack
{
protected:
struct Entry
{
Entry* pNext;
T* pData;
};
union Header
{
__int64 m_XChg;
struct
{
Entry* m_pNext;
__int16 m_Depth;
__int16 m_Counter;
};
};
Header m_Header;
public:
LowLockStack()
{
m_Header.m_pNext = NULL;
m_Header.m_Depth = 0;
m_Header.m_Counter = 0;
}
~LowLockStack()
{
}
void PushEntry( T* pData )
{
Entry* pEntry = new Entry;
pEntry->pData = pData;
Header header;
Header xchg;
do
{
xchg.m_XChg = m_Header.m_XChg;
header.m_pNext = pEntry;
header.m_Depth = xchg.m_Depth + 1;
header.m_Counter = xchg.m_Counter + 1;
pEntry->pNext = xchg.m_pNext;
} while( _InterlockedCompareExchange64( &m_Header.m_XChg, header.m_XChg, xchg.m_XChg ) != xchg.m_XChg );
}
T* PopEntry()
{
Entry* pEntry = NULL;
Header header;
Header xchg;
do
{
xchg.m_XChg = m_Header.m_XChg;
pEntry = xchg.m_pNext;
if ( pEntry == NULL )
{
return NULL;
}
header.m_pNext = pEntry->pNext;
header.m_Depth = xchg.m_Depth - 1;
} while( _InterlockedCompareExchange64( &m_Header.m_XChg, header.m_XChg, xchg.m_XChg ) != xchg.m_XChg );
T* pRet = pEntry->pData;
delete pEntry;
return pRet;
}
__int32 GetDepth()
{
return m_Header.m_Depth;
}
};
#endif
If there are no errors (which i doubt ;)) then think of it as a reference implementation :D
Edit: I've updated the code taking into account a number of criticisms.
| You do not synchronize access to the list header member. This is bad at least on 2 levels:
assigning values to the list header can be not as atomic as you think. Which means that an unsynchronized read operation can potentially get a corrupted value.
another, more probable issue with this is that if your box has multiple cores, every one of them can have in the processor cache its own copy of the value. To make them synchronize the values you need a memory barrier
|
1,889,996 | 1,890,031 | Inheritance mucking up polymorphism in C++? | Perhaps my knowledge of inheritance and polymorphism isn't what I thought it was. Can anyone shed some light?
Setup (trivialization of problem):
class X {
};
class Y {
};
class Base {
public:
void f( X* ) {}
};
class Child: public Base {
public:
void f( Y* ) {}
};
Question: This should work, right?
int main( void ) {
X* x = new X();
Y* y = new Y();
Child* c = new Child();
c->f( x );
c->f( y );
return 0;
}
I get errors (GCC 4.4) to the tune of:
`no matching function for call to 'Child::f(X*&)'`
`note: candidates are: void Child::f(Y*)`
| The virtual keyword will not help you here.
Your base class Base::f is being hidden by your derived type. You need to do the following:
class Child: public Base {
public:
using Base::f;
void f( Y* ) {}
};
Parashift goes into more detail.
|
1,890,041 | 1,890,069 | Avoid making copies with vectors of vectors | I want to be able to have a vector of vectors of some type such as:
vector<vector<MyStruct> > vecOfVec;
I then create a vector of MyStruct, and populate it.
vector<MyStruct> someStructs;
// Populate it with data
Then finally add someStructs to vecOfVec;
vecOfVec.push_back(someStructs);
What I want to do is avoid having the copy constructor calls when pushing the vector. I know this can be accomplished by using a vector of pointers, but I'd like to avoid that if possible.
One strategy I've thought of seems to work, but I don't know if I'm over-engineering this problem.
// Push back an empty vector
vecOfVec.push_back(vector<MyStruct>());
// Swap the empty with the filled vector (constant time)
vecOfVec.back().swap(someStructs);
This seems like it would add my vector without having to do any copies, but this seems like something a compiler would already be doing during optimization.
Do you think this is a good strategy?
Edit: Simplified my swap statement due to some suggestions.
| The swap trick is as good as it gets with C++03. In C++0x, you'll be able to use the vector's move constructor via std::move to achieve the same thing in a more obvious way.
Another option is to not create a separate vector<MyStruct>, but instead have the code that creates it accept it a a vector<MyStruct>& argument, and operate on it. Then, you add a new empty element to your outer vector<vector<MyStruct>>, and pass a reference to the code that will fill it.
|
1,890,448 | 1,890,553 | What's the intended use of _fread_nolock, _fseek_nolock? | we have a C++ class which basically reads and writes vectors from a binary file. An exemplary read function that loads a single vector into memory looks like this:
int load (const __int64 index, T* values) const {
int re = _fseeki64(_file, index * _vectorSize + _offsetData, SEEK_SET);
assert(re == 0);
size_t read = fread(values, sizeof(T), _vectorElements, _file);
assert(read == _vectorElements);
return 0;}
Out programs are multithreaded with OpenMP and multiple threads access the same file at the same time. To avoid issues because of multiple threads we always cover the function call within an OpenMP critical statement:
#pragma omp critical {
load(...);
}
I know that the Microsoft Visual C++ runtime contains several functions like _fseek_nolock, _fread_nolock, _fwrite_nolock and so on... For example the _fread_nolock() function is described as
This function is a non-locking version of fread. It is identical to fread except that it is not protected from interference by other threads. It might be faster because it does not incur the overhead of locking out other threads. Use this function only in thread-safe contexts such as single-threaded applications or where the calling scope already handles thread isolation.
Now my question: I understand that the function blocks "re-entrant" calls, so no other thread will enter the function before other threads have returned. However, I do not understand why it is necessary to protect a single function in that way. IMHO all functions that access/modify the file pointer (_file in the code sample) must be protected and therefore be made thread-safe. This requires to build a lock around the whole function block that actuall calls the standard C functions fseek and fread, so I do not see the point of providing such non-blocking functions.
Can someone explain me these locking mechanisms because I suppose our paranoid locking scheme wastes some performance?
Thank you in advance!
| For some simple code, the lock within the FILE * is sufficient. Consider a basic logging infrastructure where you want all threads to log via a common FILE *. The internal lock will make sure the FILE * will not be corrupted by multiple threads and since each log line should stand alone, it doesn't matter how the individual calls interleave.
|
1,890,502 | 1,890,597 | how to hook control closing in an MFC custom control class | I am interested in allocating pointers, storing those in the LPARAM data of a comboboxex control, and making that control responsible for deleting those pointers when it is destroyed.
Since I am working in MFC, I can subclass a CComboBoxEx, and add either a message handler or a virtual member function.
The question is: Is this pattern possible with Win32 / MFC?
Basically, how does a control get notified that its corresponding HWND is being destroyed?
The documentation for WM_DESTROY:
The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window procedure of the window being destroyed after the window is removed from the screen. (Emphasis Mine)
Unfortunately, my vague recollection is that this means that OnDestroy() is too late for handling anything that requires interacting with the associated HWND, no?
Can I query the elements in the comboboxex during OnDestroy()? Is there another hook I can use that occurs "Just before my window / control is destroyed (instead of after!)?"
I wonder if I overrode CBEM_DELETEITEM for my subclass and forced it to delete the LPARAM data. Are all items explicitly deleted when a comboboxex is destroyed? If so, are they all destroyed via that message (does the control send that message to itself?)
| During OnDestroy() your window will still be valid -- if it weren't, your window wouldn't have gotten the message at all, since it's sent via the standard Windows messaging system.
You are on the right track -- this type of scenario is what OnDestroy() is for.
|
1,890,555 | 1,890,702 | How can I obfuscate a test in code to prevent tampering with response processing? | I am looking for a way to obfuscate (in the object code) a test - something like what might be done to check that a license key is valid. What I am trying to prevent is someone searching through an image binary for the code that processes the response.
bool checkError = foo();
if ( checkError ) // I'd like to avoid making a simple check like this one.
{
// process response
}
This is a simplistic example, but not a recommended approach:
int check = 71 * 13;
check += 35 * isValid(); // will only return 0 or 1
//later (delayed execution of response)
if ( check % 71 )
{
//process response
}
EDIT:
Just to clarify, the actual test is already finished and I'm getting a pass/fail return. My response processing will be a basic jmp and would be interested in pointers on how to obfuscate the location of the jmp.
| One approach would be to put the code that does the license check into a separate DLL. In the main application, load the DLL at runtime and calculate the checksum of the DLL itself. The app stores the checksum that was calculated with the DLL was built. If the checksums don't match, you have several options, show a wrong-version message - a bit obvious; Do not call the license check - less obvious but will be noticed when the attacker wonders why the license check doesn't get called; call a function with a similar name to the real license-check function.
Think of it as using Public Key Encryption. Use a public key as part of the config and have a private key built into the app. If they mess with the public key, the digital signature of the app will be compromised in a detectable way.
I agree with @camccann that it would help to understand the kind of attack you expect. As a last resort, split the license-check into as many parts as is feasible to make it harder to bypass by changing a single branch point.
[EDIT]
Another thought would be to use a State Machine. See the command structure example in the top answer to this question. Put the evaluation of the license check into the form of a hash lookup and a set of dummy function calls into an array along with the proper one. The decision code that evaluates the license check into a table/hash lookup for the appropriate function will not look like your typical
if(){ pass;} else { fail; }
construct.
Two benefits,
1) there isn't a boolean condition to bypass and
2) they can't do a simple JMP instruction without knowing the address/name of the function to pass control to.
SO thread on a state machine turorial.
SO thread on state machine implementations
|
1,890,867 | 1,890,956 | Add the upper and lower 64-bits of a 128-bit xmm register | I have two packed quadword integers in xmm0 and I need to add them together and store the result in a memory location. I can guarantee that the value of the each integer is less than 2^15. Right now, I'm doing the following:
int temp;
....
movdq2q mm0, xmm0
psrldq xmm0, 8
movdq2q mm1, xmm0
paddq mm0,mm1
movd temp, mm0
Is there a better way to do this?
| First off, why are you using quadwords to represent values that would fit in a 16-bit format? Leaving that aside, a couple solutions:
pshufd xmm1, xmm0, EEh
paddq xmm0, xmm1
movd temp, xmm0
or
movdqa xmm1, xmm0
psrldq xmm1, 8
paddq xmm0, xmm1
movd temp, xmm0
or
movhlps xmm1, xmm0
paddq xmm0, xmm1
movd temp, xmm0
Note that you don't actually need to use paddq, you can get away with one of the narrower adds if you prefer.
edit summing four double quadwords -- what you have is pretty much fine. Given that you know that all the data in them fits into the low doubleword of each slot, you could try something like:
shufps xmm0, xmm2, 88h
shufps xmm4, xmm6, 88h
paddd xmm0, xmm4
psrlq xmm1, xmm0, 32
paddd xmm0, xmm1
movhlps xmm1, xmm0
paddd xmm0, xmm0
movd temp, xmm0
which may or may not prove to be faster.
As for EMMS, it's just another instruction. After any code that touches the MMX registers, before any code that uses the x87 floating-point instructions you need to have emms.
|
1,891,194 | 1,935,082 | InPlaceActivate on ATL control not called until mouse event | I have an ActiveX control written in C++ that I created with VS2008 and ATL. For the most part, it is a pretty standard (not modified much from the original template) control, except that instead of using IDispatchImpl, I have created my own IDispatchEx implementation. This control is only used in Internet Explorer, and I have been testing primarily with IE8.
Everything works great, except that for some reason, InPlaceActivate doesn't get called until I move the mouse over the region where the object tag is hosted in the browser; no window is created, no WM_CREATE message sent, etc.
I have tried implementing DISPID_READYSTATE, but nothing seems to help. If I call InPlaceActivate(OLEIVERB_UIACTIVATE); from the SetClientSite method and it usually works, but that certainly isn't normally neccesary.
Why would this happen? How does the browser determine when to call InPlaceActivate (or whatever call triggers that)?
The tag used to embed the ATL control into the page is:
<object id="plugin" type="application/x-vnd.FirebreathTemplatePlugin" width="300" height="300"></object>
You full source to the file can be found here:
http://code.google.com/p/firebreath/source/browse/src/ActiveXPlugin/FBControl.h
| I found the culprit. Aparently, the OLEMSIC_ACTIVATEWHENVISIBLE is used to auto-generate the %OLEMISC% variable in the .rgs file. However, I had overridden the default rgs handling to provide my own variables, and in the process one critical line got removed, which would have added a:
[CLSID]/MiscStatus/1 = s '131473'
to the registry. this aparently is used by the browser to decide how to initialize, and that value has OLEMISC_ACTIVATEWHENVISIBLE 'or'ed (|) into it. Added that back in and everything works again.
|
1,891,237 | 1,903,978 | Sending a struct from C++ to WPF using WM_COPYDATA | I have a native C++ application that, for the time being simply needs to send its command line string and current mouse cursor coordinates to a WPF application. The message is sent and received just fine, but I cannot convert the IntPtr instance in C# to a struct.
When I try to do so, the application will either crash without exception or the line of code that converts it is skipped and the next message in the loop is received. This probably means there's a native exception occurring, but I don't know why.
Here's the C++ program. For the time being I'm ignoring the command line string and using fake cursor coordinates just to make sure things work.
#include "stdafx.h"
#include "StackProxy.h"
#include "string"
typedef std::basic_string<WCHAR, std::char_traits<WCHAR>> wstring;
struct StackRecord
{
//wchar_t CommandLine[128];
//LPTSTR CommandLine;
//wstring CommandLine;
__int32 CursorX;
__int32 CursorY;
};
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
COPYDATASTRUCT data;
ZeroMemory(&data, sizeof(COPYDATASTRUCT));
StackRecord* record = new StackRecord();
wstring cmdLine(lpCmdLine);
//record.CommandLine = cmdLine;
record->CursorX = 5;
record->CursorY = 16;
data.dwData = 12;
data.cbData = sizeof(StackRecord);
data.lpData = record;
HWND target = FindWindow(NULL, _T("Window1"));
if(target != NULL)
{
SendMessage(target, WM_COPYDATA, (WPARAM)(HWND) target, (LPARAM)(LPVOID) &data);
}
return 0;
}
And here is the part of the WPF application that receives the message. The second line inside the IF statement is skipped over, if the whole thing doesn't just crash.
public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == Interop.WM_COPYDATA)
{
var data = (Interop.CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(Interop.CopyDataStruct));
var record = (Interop.StackRecord)Marshal.PtrToStructure(data.lpData, typeof(Interop.StackRecord));
MessageBox.Show(String.Format("X: {0}, Y: {1}", record.CursorX, record.CursorY));
}
return IntPtr.Zero;
}
And here are the C# definitions for the structs. I have toyed endlessly with marshalling attributes and gotten nowhere.
internal static class Interop
{
public static readonly int WM_COPYDATA = 0x4A;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CopyDataStruct
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct StackRecord
{
//[MarshalAs(UnmanagedType.ByValTStr)]
//public String CommandLine;
public Int32 CursorX;
public Int32 CursorY;
}
}
Any ideas?
| I am not sure what you are getting wrong necessarily without more info about your setup. I replicated the code as best I could (using WndProc in a WPF app, sending from my own win32 app) and it works fine for me. There are a few errors which will definetly crop up if you are running 64 bit applications, namely the Pack = 1 will cause the COPYDATASTRUCT to become misaligned and reading from the pointer is likely to end in pain.
It is crashing passing just the ints? Looking at your commented code passing a LPWSTR or wstring is going to cause serious issues, although that shouldn't become apparent until you unmarshal the sent data.
For what it is worth, this is snippets of my code which seem to work for me including getting the command line across.
/* C++ code */
struct StackRecord
{
wchar_t cmdline[128];
int CursorX;
int CursorY;
};
void SendCopyData(HWND hFind)
{
COPYDATASTRUCT cp;
StackRecord record;
record.CursorX = 1;
record.CursorY = -1;
_tcscpy(record.cmdline, L"Hello World!");
cp.cbData = sizeof(record);
cp.lpData = &record;
cp.dwData = 12;
SendMessage(hFind, WM_COPYDATA, NULL, (LPARAM)&cp);
}
/* C# code */
public static readonly int WM_COPYDATA = 0x4A;
[StructLayout(LayoutKind.Sequential)]
public struct CopyDataStruct
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct StackRecord
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
public string CommandLine;
public Int32 CursorX;
public Int32 CursorY;
}
protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_COPYDATA)
{
StackRecord record = new StackRecord();
try
{
CopyDataStruct cp = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
if (cp.cbData == Marshal.SizeOf(record))
{
record = (StackRecord)Marshal.PtrToStructure(cp.lpData, typeof(StackRecord));
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
handled = true;
}
else
{
handled = false;
}
return IntPtr.Zero;
}
|
1,891,249 | 1,892,865 | What's a pattern for getting two "deep" parts of a multi-threaded program talking to each other? | I have this general problem in design, refactoring or "triage":
I have an existing multi-threaded C++ application which searches for data using a number of plugin libraries. With the current search interface, a given plugin receives a search string and a pointer to a QList object. Running on a different thread, the plugin goes out and searches various data sources (locally and on the web) and adds the objects of interest to the list. When the plugin returns, the main program, still on the separate thread, adds this data to the local data store (with further processing), guarding this insertion point using a mutex. Thus each plugin can return data asynchronously.
The QT-base plugin library is based on message passing. There are a fair number of plugins which are already written and tested for the application and they work fairly well.
I would like to write some more plugins and leverage the existing application.
The problem is that the new plugins will need more information from the application. They will to need intermittent access to the local data store itself as they search. So to get this, they would need direct or indirect access both the hash array storing the data and the mutex which guards multiple access to the store. I assume the access would be encapsulated by adding an extra method in a "catalog" object.
I can see three ways to write these new plugins.
When loading a plugin, pass them
a pointer to my "catalog" at the
start. This becomes an extra,
"invisible" interface for the new
plugins. This seems quick, easy,
completely wrong according to OO but
I can't see what the future problems would be.
Add a method/message to the
existing interface so I have a
second function which could be
called for the new plugin libraries,
the message would pass a pointer to
the catalog to the plugins. This
would be easy for the plugins but it
would complicate my main code and
seems generally bad.
Redesign the plugin interface.
This seems "best" according to OO,
could have other added benefits but
would require all sorts of
rewriting.
So, my questions are
A. Can anyone tell me the concrete dangers of option 1?
B. Is there a known pattern that fits this kind of problem?
Edit1:
A typical function for calling the plugin routines looks like:
elsewhere(spec){
QList<CatItem> results;
plugins->getResult(spec, &results);
use_list(results);
}
...
void PluginHandler::getResults(QString* spec, QList<CatItem>* results)
{
if (id->count() == 0) return;
foreach(PluginInfo info, plugins) {
if (info.loaded)
info.obj->msg(MSG_GET_RESULTS, (void*) spec, (void*) results);
}
}
It's a repeated through-out the code. I'd rather extend it than break it.
| Why is it "completely wrong according to OO"? If your plugin needs access to that object, and it doesn't violate any abstraction you want to preserve, it is the correct solution.
To me it seems like you blew your abstractions the moment you decided that your plugin needs access to the list itself. You just blew up your entire application's architecture. Are you sure you need access to the actual list itself? Why? What do you need from it? Can that information be provided in a more sensible way? One which doesn't 1) increase contention over a shared resource (and increase the risk of subtle multithreading bugs like race conditions and deadlocks), and 2) doesn't undermine the architecture of the rest of the app (which specifically preserves a separation between the list and its clients, to allow asynchronicity)
If you think it's bad OO, then it is because of what you're fundamentally trying to do (violate the basic architecture of your application), not how you're doing it.
|
1,891,330 | 1,891,457 | high speed interprocess associative array | Is there library usable from c++ for sharing fairly simple data (integers,floating point numbers, strings) between cooperative processes?
Must be :
high-speed (SQL-based methods too slow due to parsing)
able to get,set,update,delete both fixed and variable data types (e.g. int and string)
ACID (atomic,consistent,isolated,durable)
usable under linux
usable by processes without a shared parent.
highly compatible license: e.g. LGPL,MIT,BSD
For bonus points:
ability to work across the network.
ability to handle aggregation/composition into more complicated structures
| Take a look at boost::interprocess. For local use, you probably can't beat a map or hash table in shared memory. Allowing networking makes things more difficult, in that case something like memcached or CouchDB might be more appropriate.
|
1,891,836 | 1,901,663 | Compiled FreeImage from source. #include FreeImage.h not found | I have compiled FreeImage 3.10.0 from source at /lib/FreeImage on Mac OS X 10.6.
I can see that after compilation these files were copied:
/usr/local/lib/libfreeimage-3.10.0.dylib
/usr/local/lib/libfreeimage.a
/usr/local/include/FreeImage.h
CMake cannot find FreeImage, but I cannot even do
#include <FreeImage.h> // not found
I am assuming I need to add FreeImage.h to the Mac OS X environment path, except I don't know which path is the right one as there are a few different files which store environment path variables.
What do I need to do to get FreeImage header to be found by my C++ app or CMake?
Here is the first part of my Makefile.osx is this helps:
# -*- Makefile -*-
# Mac OSX makefile for FreeImage
# This file can be generated by ./gensrclist.sh
include Makefile.srcs
# General configuration variables:
CC_PPC = gcc-4.0
CC_I386 = gcc-4.0
CPP_PPC = g++-4.0
CPP_I386 = g++-4.0
COMPILERFLAGS = -Os -fexceptions -fvisibility=hidden
COMPILERFLAGS_PPC = -arch ppc
COMPILERFLAGS_I386 = -arch i386
COMPILERPPFLAGS = -Wno-ctor-dtor-privacy
INCLUDE +=
INCLUDE_PPC = -isysroot /Developer/SDKs/MacOSX10.6.sdk
INCLUDE_I386 = -isysroot /Developer/SDKs/MacOSX10.6.sdk
CFLAGS_PPC = $(COMPILERFLAGS) $(COMPILERFLAGS_PPC) $(INCLUDE) $(INCLUDE_PPC)
CFLAGS_I386 = $(COMPILERFLAGS) $(COMPILERFLAGS_I386) $(INCLUDE) $(INCLUDE_I386)
CPPFLAGS_PPC = $(COMPILERPPFLAGS) $(CFLAGS_PPC)
CPPFLAGS_I386 = $(COMPILERPPFLAGS) $(CFLAGS_I386)
LIBRARIES_PPC = -Wl,-syslibroot /Developer/SDKs/MacOSX10.6.sdk
LIBRARIES_I386 = -Wl,-syslibroot /Developer/SDKs/MacOSX10.6.sdk
LIBTOOL = libtool
LIPO = lipo
Update: I added these lines into my Makefile as per Nicholas' instructions, then rebuilt but this didn't work:
CFLAGS = -I/usr/local/include
LDFLAGS = -L/usr/local/lib
| The 'INCLUDE +=' line looks like the one to attack:
INCLUDE += -I/usr/local/include
If the library is missing too, then you will need to find another line to add '-L/usr/include/lib' to.
|
1,891,843 | 1,891,870 | C++ efficient inheritance of certain methods in child classes | I find my self repeating a single line of code in child constructors, which are passed two variables. The first of these variables is always used to initiate a protected variable (defined in the parent class). I was wondering if there is a way for me to do that assignment in the parent constructor - which is then inherited, and do the rest of the assinments for the child class in each of the respective constructors (in the child classes)
is this possible? and is this good practice?
many thanks
| If I understand you correctly, you need something like this
class Parent
{
public:
Parent(int Param1, doubel param2)
:param1(Param1), param2(Param2)
{
}
protected:
int param1;
double param2;
};
class Derived: public Parent
{
public:
Derived(int Param1, doubel param2)
:Parent(Param1, Param2)
{
}
};
I would recommend to keep param1 and param2 private and expose them to derived classes via methods, though it depends of your particular task at hand.
|
1,892,040 | 1,892,263 | Linux multithreading would involve the pthreads library(in most cases) . What is the equivalent library used by MSVC? | I need to know which are the APIs/library used for multithreading by MSVC . If there are more than one , please let me know which is the most widely used.
If my question sounds too naive , its because I've never done threading before , and from my past experience , I know there are people here who can get me started/point me at the right direction , from which point I can start.
| As others have suggested you can use CreateThread or _beginthread or the threadpool APIs, the process and threads reference is best for Win32 threading, you can also use boost::thread which is very close to the C++0x std::thread standard.
The other option if you're using Visual Studio is to take a look at the Parallel Pattern Library and Asynchronous Agents Library which are part of Microsoft's Concurrency Runtime (ConcRT) and are new in Visual Studio 2010. There are several how-to help topics which in the link that can help you get started here.
The API's in ConcRT are 'task' APIs rather than thread APIs and let you work at a slightly higher level of abstraction than threads. i.e. parallel loops, parallel pipelines and groups of tasks. Like boost::thread, the APIs are primarily setup to work with functors rather than the CreateThread / ThreadPool style APIs though there are APIs which are similar syntactically to CreateThread (Concurrency::Scheduler::ScheduleTask for example).
-Rick
|
1,892,043 | 1,892,054 | Self-sufficient header files in C/C++ | I recently posted a question asking for what actions would constitute the Zen of C++. I received excellent answers, but I could not understand one recommendation:
Make header files self-sufficient
How do you ensure your header files are self-sufficient?
Any other advice or best-practice related to the design and implementation of header files in C/C++ will be welcome.
Edit: I found this question which addresses the "Best Practices" part of mine.
| A self sufficient header file is one that doesn't depend on the context of where it is included to work correctly. If you make sure you #include or define/declare everything before you use it, you have yourself a self sufficient header.
An example of a non self sufficient header might be something like this:
----- MyClass.h -----
class MyClass
{
MyClass(std::string s);
};
-
---- MyClass.cpp -----
#include <string>
#include "MyClass.h"
MyClass::MyClass(std::string s)
{}
In this example, MyClass.h uses std::string without first #including .
For this to work, in MyClass.cpp you need to put the #include <string> before #include "MyClass.h".
If MyClass's user fails to do this he will get an error that std::string is not included.
Maintaining your headers to be self sufficient can be often neglected. For instance, you have a huge MyClass header and you add to it another small method which uses std::string. In all of the places this class is currently used, is already #included before MyClass.h. then someday you #include MyClass.h as the first header and suddenly you have all these new error in a file you didn't even touch (MyClass.h)
Carefully maintaining your headers to be self sufficient help to avoid this problem.
|
1,892,050 | 1,892,061 | Why is my printList function not working? | #include <iostream>
using namespace std;
struct Node
{
char item;
Node *next;
};
void inputChar ( Node * );
void printList (Node *);
char c;
int main()
{
Node *head;
head = NULL;
c = getchar();
if ( c != '.' )
{
head = new Node;
head->item = c;
inputChar(head);
}
cout << head->item << endl;
cout << head->next->item << endl;
printList(head);
return 0;
}
void inputChar(Node *p)
{
c = getchar();
while ( c != '.' )
{
p->next = new Node;
p->next->item = c;
p = p->next;
c = getchar();
}
p->next = new Node; // dot signals end of list
p->next->item = c;
}
void printList(Node *p)
{
if(p = NULL)
cout << "empty" <<endl;
else
{
while (p->item != '.')
{
cout << p->item << endl;
p = p->next;
}
}
}
This program takes input from the user one character at a time and places it into a linked list. printList then attempts to print the linked list. The cout statements immediately before the call to printList in main work fine but for some reason the printList function hangs up in the while loop.
| if(p = NULL)
That's your problem right there. It should be
if(p == NULL)
|
1,892,064 | 1,904,124 | How do I detect a custom plugin in Firefox/IE/Chrome? | My team wants to build a "plugin" for firefox/chrome/IE.
How do I use javascript to detect if this plugin (not extension) is installed?
I would like to have a piece of javascript that can detect if a certain plugin is installed. Returns true if installed, returns false otherwise.
For example...how do I get a list of plugins, and then loop through to see if one of them match my plugin name? If match, return 1.
| solved:
document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>",
"<TH ALIGN=left>i",
"<TH ALIGN=left>name",
"<TH ALIGN=left>filename",
"<TH ALIGN=left>description",
"<TH ALIGN=left># of types</TR>")
for (i=0; i < navigator.plugins.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,
"<TD>",navigator.plugins[i].name,
"<TD>",navigator.plugins[i].filename,
"<TD>",navigator.plugins[i].description,
"<TD>",navigator.plugins[i].length,
"</TR>")
}
document.writeln("</TABLE>")
|
1,892,104 | 1,892,138 | Can a thread be pre-empted in the midst of a system call to kernel? | I'm running 2 threads ( assume they are pthreads for the moment) . Thread_1() makes a user-defined API call which ultimately does some work in the kernel . Thread_2() is totally in user-space.
My question is : Can Thread_2() start executing by pre-empting Thread_1() while the API call is in progress , the control is somewhere inside the kernel ? If not , why , and if I want this scenario to occur ( for any reasons ) , what do I have to do ?
| If you are asking whether a blocking kernel call like an fread() which requires disk IO can be pre-empted, then yes.
More specifically a blocking call will basically put Thread_1 to sleep while waiting for whatever it's waiting for. If Thread_1 is asleep then Thread_2 will be scheduled to run (unless there's something of higher priority waiting to run).
Edit: If you want a way to be "fairly confident" that Thread_1 is performing a blocking call, make Thread_2 lower priority than Thread_1 (so that it generally doesn't run unless Thread_1 is blocked) and when it runs, it elevates its priority to a higher level than Thread_1 until the hardware interrupt has been delivered, at which point it lowers its priority and calls sched_yield().
|
1,892,172 | 1,892,428 | What is coming in IDataObject? | When you implement IDropTarget you must implement this:
virtual HRESULT STDMETHODCALLTYPE Drop(
/* [unique][in] */ __RPC__in_opt IDataObject *pDataObj,
/* [in] */ DWORD grfKeyState,
/* [in] */ POINTL pt,
/* [out][in] */ __RPC__inout DWORD *pdwEffect)=0;
I want to know what kind of data is coming in the IDataObject.
I did this:
FORMATETC fdrop = {CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (SUCCEEDED(pDataObj->QueryGetData(&fdrop)) ){
STGMEDIUM stgMedium = {0};
stgMedium.tymed = TYMED_HGLOBAL;
HRESULT hr = pDataObj->GetData(&fdrop, &stgMedium);
if (SUCCEEDED(hr))
{
But this only works when someone drop files. I saw that there's also a CF_TEXT and CF_BITMAP, but I don't want to query for all types of Clipboard Formats, so I want to know if there's a way of querying IDataObject's type of data.
CF_HDROP works fine for files, but when I drop an image from a browser for example, I don't know what kind of CF_ to use... I tried CF_BITMAP but doesn't work.
| See IDataObject::EnumFormatEtc. As you can see from the documentation it may be possible to query for the data in multiple formats and EnumFormatEtc is a means to enumerate the various formats available.
|
1,892,229 | 1,892,417 | c++ iterator confusion | I have a vector<list<customClass> >
I have an iterator vector<list<customClass> >::const_iterator x
When I try to access an member of customClass like so:
x[0]->somefunc(), I get errors of a non-pointer type/not found.
| Here's a complete working snippet. To answer your question, the line with the comment [1] shows how to dereference the const_iterator, while comment [2] shows how to dereference using the operator [].
#include <vector>
#include <list>
#include <iostream>
class Foo
{
public:
void hello() const
{
std::cout << "hello - type any key to continue\n";
getchar();
}
void func( std::vector<std::list<Foo> > const& vec )
{
std::vector<std::list<Foo> >::const_iterator qVec = vec.begin();
qVec->front().hello(); // [1] dereference const_iterator
}
};
int main(int argc, char* argv[])
{
std::list<Foo> list;
Foo foo;
list.push_front(foo);
std::vector<std::list<Foo> > vec;
vec.push_back(list);
foo.func( vec );
vec[0].front().hello(); // [2] dereference vector using []
}
|
1,892,379 | 1,892,388 | Preferred implementation of '<' for multi-variable structures | Initially this may seem overly abstract or philosophical, but I am genuinely interested to see if someone has a convincing argument in favor of one implementation over the other.
Given operator< for std::pair<T1, T2>, which would be the better implementation:
return x.first < y.first ||
x.first == y.first && x.second < y.second;
or:
return x.first < y.first ||
!(y.first < x.first) && x.second < y.second;
My understanding is that the two implementations yield equivalent results. Is the latter preferred because it is defined solely in terms of operator<? Or is it legitimate to assume that a type that is less-than comparible should also be equality comparable? Does anyone else see another point that would sway you between one or the other?
Naturally any answer should be both generic and extensible. So which one would you use and why? Is there a different implementation that's even better than the above?
| It is not legitimate to assume that for any type, if it is less-than comparable, it is also equality comparable, since one can overload operator< but not overload operator==.
Thus, if you anticipate having to handle user-defined types, the second approach is preferable. However, you should add some parentheses to clarify the order of operations:
return x.first < y.first ||
(!(y.first < x.first) && x.second < y.second);
|
1,892,566 | 1,892,571 | C++ Bus error in SPARC arcitecture | I would like to understand why I am getting a bus error with this code.
int main()
{
int p=34;
int *pp= (int *) ((char *)&p+1);
cout<<*pp<<"\n";
return 0;
}
| It will no doubt be an alignment issue. On many architectures, certain types have to be aligned properly, an example being that 4-byte integers must start on a 4-byte boundary.
If you access non-aligned data, some architectures won't care, others will run slower, still others (such as in this case) will fall in a screaming heap.
When you create the integer p, it will be aligned correctly on the stack at an address which is a correct multiple.
By moving that address up on byte, and de-referencing that as an int, you're causing the SIGBUS.
This link at Oracle shows the alignment requirements. In short:
short integers are aligned on 16-bit boundaries.
int integers are aligned on 32-bit boundaries.
long integers are aligned on 64-bit boundaries for SPARC systems.
long long integers are aligned on 64-bit boundaries.
|
1,892,588 | 1,919,640 | Linking error when compiling C and C++ code with g++ | I am integrating a medium-sized (10,000 or so lines) program written in C into a C++ program. I have created a new class, BWAGenome as an interface to the C code, so any access to the C functions is encapsulated. I am compiling everything with the g++ compiler. The .o files are all generated correctly, but when I attempt to link them together into a final executable, the compiler complains that it cannot find the symbols. Here is the error message I get:
Undefined symbols:
BWAGenome::BWTRestoreBWT(char const*)", referenced from:
BWAGenome::BWAGenome(char const*)in BWAGenome.o
"BWAGenome::GetMatches(unsigned int, int, bwt_t*, bwt_t*, bwt_t*, bntseq_t*, bntseq_t*)", referenced from:
BWAGenome::getMatches(unsigned int, int)in BWAGenome.o
These functions are all in the C++ class I made. They wrap functions in the C code, but I don't understand at all how the symbols could be undefined.
A few details about the code and what I have done so far:
Everything is compiled with g++, so if I understand correctly I don't need the extern "C" {}; surrounding the c header files I include.
All of the code compiles correctly individually. The error only occurs during linking.
I heard somewhere that the C code might need to be called from static functions, so I have tried wrapping each call to a C function inside a static class method and calling that instead.
Any ideas on how to solve this problem?
edit: added definitions and declarations of BWTRestoreBWT and GetMatches
//definition in BWAGenome.h
static bwt_t * BWTRestoreBWT(const char *fn);
//declaration in BWAGenome.cpp
static bwt_t * BWTRestoreBWT(const char *fn) {
return bwt_restore_bwt(fn);
//bwt_restore_bwt is a function in the C code that I am attempting to integrate
}
second edit: After much soul searching I realized the problem was pretty unrelated to most of what I thought it was. See my answer for details.
| The error was in the order I was linking the object files together. I needed to link in the C code first, and then the BWAGenome class I created to call it. The linker couldn't find the C code symbols because they weren't linked yet. Thanks for all your help though. I imagine I frustrated some people, but thanks anyways.
|
1,892,619 | 1,892,640 | Threads and simple Dead lock cure | When dealing with threads (specifically in C++) using mutex locks and semaphores is there a simple rule of thumb to avoid Dead Locks and have nice clean Synchronization?
| A good simple rule of thumb is to always obtain your locks in a consistent predictable order from everywhere in your application. For example, if your resources have names, always lock them in alphabetical order. If they have numeric ids, always lock from lowest to highest. The exact order or criteria is arbitrary. The key is to be consistent. That way you'll never have a deadlock situation. eg.
Thread 1 locks resource A
Thread 2 locks resource B
Thread 1 waits to obtain a lock on B
Thread 2 waits to obtain a lock on A
Deadlock
The above can never happen if you follow the rule of thumb outlined above. For a more detailed discussion, see the Wikipedia entry on the Dining Philosophers problem.
|
1,892,921 | 1,892,928 | c++ operator overloading | i'm not sure if what im talking about is an operator overloading question.
is it possible to overload keywords in C++??
for example : i need to write loopOver(i=0; ;i++) instead of for(i=0;;i++) ?? is that possible in C++
and i need to have something like 2 addTo 2 instead of 2 + 2
please help
thanks in advance
| You can't do that with operator overloading (you can't change the names of the operators, only how they work).
However, evil as it is, if you don't want to change the way they work (just the names), you would be able to achieve things like this using macros:
#define loopOver for
#define addTo +
(Use macros with extreme care though - if used incorrectly they can cause hideous problems)
|
1,893,092 | 1,893,105 | How do I write a public function to return a head pointer of a linked list? | class Newstring
{
public:
Newstring();
void inputChar ( char);
void display ();
int length ();
void concatenate (char);
void concatenate (Newstring);
bool substring (Newstring);
void createList ();
Node * getHead (); // error
private:
struct Node
{
char item;
Node *next;
};
Node *head;
};
I am getting a syntax error : missing ';' before '*' on the declaration for my getHead function (yes I can't think of a better name). The purpose of this function is to return the head pointer.
| Declare Node before you use it.
|
1,893,438 | 1,893,466 | Tools for Unix <-> Windows C++ development | I am doing some C++ cross development - been doing that for a while on Windows and recently started on Unix.
I suppose what I am after is to simplify Unix development experience - I have a local windows box I do development on, and a remote Solaris box which I use to compile and test code on unix environment.
What I do now - I develop, compiled and test code on Windows (VC++) and once it is done, I move code to Solaris box using Filezilla over SSH. I also use Putty to connect to Solaris box and execute shell commands.
Since I am quite new to unix development - I suppose what I do is by far not optimal and the tools/technics I use not optimal too.
Can you recommend me a better tools - how to move code around more easily and may be a replacement for Putty (which looks quite outdated anyway).
Thanks.
| If by any chance you want to run the same C++ IDE on both Windows and Solaris, I recommend taking a look at Code::Blocks. Also, as I suggested to Charles, running an X server on the Windows box gives you a lot more flexibility than running Putty or similar.
|
1,893,490 | 1,893,518 | What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf) | What is the difference between %d and %i when used as format specifiers in printf and scanf?
| They are the same when used for output, e.g. with printf.
However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0).
So 033 would be 27 with %i but 33 with %d.
|
1,893,688 | 1,893,809 | abstract class and using array polymorphically | i'm just reading meyers "More Effective C++ 35 New Ways" - item 33, and he suggest there
always to inherit from an abstract base class, and not a concrete.
one of the reason he claims, which i can't quite get , is that with inheriting from an abstract class, treating array polymorphically (item 3 in the book) is not a problem.
can someone suggest how is that ?
In addition i would like to hear if it's really always a good thing never to let the client instantiate a class which other derives from ? (meyers in his book is showing a problem with the assignment operator for example )
code example as requested:
CLASS BST {.... };
CLASS BlanacedBST:: public BST {....}
void printBSTArray(ostream& s, const BST array[],int Numelements)
{
for(int i=0;i < Numelements;i++)
{
s << array[i];
}
}
BST BSTArray[10];
printBSTArray(BSTArray); // works fine
BlanacedBST bBSTArray[10];
printBSTArray(bBSTArray); // undefined behaviour (beacuse the subscript operator advances the pointer according to BST chunk size)
then, he addes that avoiding concreate class (BlanacedBST) inheriting from another concreat class(BST) usually avoids this problem - this i don't get how.
| While I think that avoiding inheritance from non-abstract classes is a good design guideline and something that should make you think twice about your design, I definitely do not think that it's in the category of 'never do this'.
I will say that classes designed to be inherited from that have data in them should probably be hiding their assignment operator because of the slicing issue.
I think there's a way to categorize classes that isn't often thought of, and I think that causes a lot of confusion. I think there are classes that are designed to be used by value, and classes that are designed to always be used by reference (meaning via a reference or a pointer or something like that).
In most object oriented languages user defined classes can only be used by reference, and there are a special class of 'primitive' types that can be used by value. One of C++'s big strengths is that you can create user defined classes that can be used by value. This can lead to some huge efficiency wins. In Java, for example, all of your points (to pick a random simple class) are heap allocated and need to be garbage collected, even though they're basically just two or three doubles stuck together with some nice 'final' support functions.
So classes that are designed to be used by reference should disable assignment and should seriously consider disabling copy construction and require people to use a 'make a copy of this' virtual function for that purpose. Notice that Java classes generally don't have anything like an assignment operator or standard copy constructor.
Classes that are designed to be used by value should generally not have virtual functions, though it may be very useful to have them be a part of an inheritance hierarchy. They can still be rather complex though because they can contain references to objects of classes designed to be used by reference.
If you need to treat a by reference class as being used by value you should use the handle/body design pattern or a smart pointer. The STL containers are all designed to be used on by value objects, so this is a fairly common problem.
|
1,893,835 | 1,893,856 | Internal enum as a base class template parameter | pragma once
#include "stdafx.h"
#include "Token.h"
//I would like this enum to be inside class Number
enum Number_enm {ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE};
class Number : public Token<Number_enm>//and this template parameter to be Number::Number_enm
{
private:
public:
Number(const Number_enm& num)
try:
Token(num)
{ }
catch(...)
{
cerr << "Error in Number::Number(const Number_enm&).";
return;
}
Number(const char num)
try:
Token(static_cast<Number_enm>(num & 0xf)) //get number value from char
{
#ifdef DEBUG_
cout << "Converting ctor, from char to Token.\n";
#endif
}
catch(...)
{
cerr << "Error in Number::Number(const char num).";
return;
}
};
#pragma once
/*Abstract class*/
template<class T>
class Token
{
typedef T value_type;
private:
value_type my_data_;
protected:
/*Token()
try: my_data_()
{ }
catch(...)
{
cerr << "Error in Token<T>::Token().";
return;
}*/
Token(const value_type value)
try:
my_data_(value)
{ }
catch(...)
{
cerr << "Error in Token<T>::Token(const value_type&).";
return;
}
/*Token(const Token& value): my_data(value)
{ }*/
Token& operator=(const Token& right)
{
#ifdef DEBUG_
cout << "Token& operator=(const Token& right).\n";
#endif
my_data = right;
return my_data;
}
public:
T get() const
{
return my_data_;
}
T set(const T& new_value)
{
T old = my_data_;
my_data_ = new_value;
return old;
}
};
I wonder if it is possible to do this kind of construction?
| No, you can't because it's not possible to forward declare an enum. Also, but not related, those contructor try blocks are a bad idea.
See also article by Herb Sutter at http://www.ddj.com/cpp/184401297 - he is slightly less condemnatory than me. Anyway, as I said, the try blocks have nothing to do with your question.
|
1,893,865 | 1,893,890 | How rethrow an exception without losing the original call stack? | The situation is as follows: Thread A catches an exception, saves the exception's data somewhere in memory (using GetExceptionInformation in the exception filter), and afterwords Thread B gets that exception information and wants to rethrow it. But the thing is, when thread B rethrows the caught exception, i'm missing the original call stack that lead to the exception.
How can I rethrow the exception without losing the original call stack? (note that this question is about C++).
| You could unwind the stack in the catch block and save it as part of the exception you are rethrowing. Unwinding the stack in C++ is a bit tricky, but you could have a al look at the crashdump collector code that comes with WxWidgets for an example.
|
1,894,236 | 1,894,422 | Cross Platform C++ Tool Chain | Hello I am putting together a tool chain on my windows Box for Cross Platform C++ Development. I plan on using Boost.Build for building and Boost::Test for unit testing. I will be using Mercurial for my VCS because I can just throw the repo on my external HD and then pull it to either my windows or linux partition. The main thing standing in my way is editor compiler/debugger. Anyone have any suggestions?
With Boost.Build I can technically build with whatever compilers it supports easily. That means MSVC on windows and GCC on linux by using the same script with a flag.
| May I suggest CMake on Windows and Linux as you can generate native Visual Studio projects as well as Eclipse CDT projects and plain-old makefiles.
If you are targeting multiple platforms, but find yourself primarily developing on a single platform, I highly recommend a continuous build/integration system to ensure a check-in for one platform does not break the build on the others.
|
1,894,446 | 1,894,855 | Taking advantage of SSE and other CPU extensions | Theres are couple of places in my code base where the same operation is repeated a very large number of times for a large data set. In some cases it's taking a considerable time to process these.
I believe that using SSE to implement these loops should improve their performance significantly, especially where many operations are carried out on the same set of data, so once the data is read into the cache initially, there shouldn't be any cache misses to stall it. However I'm not sure about going about this.
Is there a compiler and OS independent way writing the code to take advantage of SSE instructions? I like the VC++ intrinsics, which include SSE operations, but I haven't found any cross compiler solutions.
I still need to support some CPU's that either have no or limited SSE support (eg Intel Celeron). Is there some way to avoid having to make different versions of the program, like having some kind of "run time linker" that links in either the basic or SSE optimised code based on the CPU running it when the process is started?
What about other CPU extensions, looking at the instruction sets of various Intel and AMD CPU's shows there are a few of them?
| For your second point there are several solutions as long as you can separate out the differences into different functions:
plain old C function pointers
dynamic linking (which generally relies on C function pointers)
if you're using C++, having different classes that represent the support for different architectures and using virtual functions can help immensely with this.
Note that because you'd be relying on indirect function calls, the functions that abstract the different operations generally need to represent somewhat higher level functionality or you may lose whatever gains you get from the optimized instruction in the call overhead (in other words don't abstract the individual SSE operations - abstract the work you're doing).
Here's an example using function pointers:
typedef int (*scale_func_ptr)( int scalar, int* pData, int count);
int non_sse_scale( int scalar, int* pData, int count)
{
// do whatever work needs done, without SSE so it'll work on older CPUs
return 0;
}
int sse_scale( int scalar, in pData, int count)
{
// equivalent code, but uses SSE
return 0;
}
// at initialization
scale_func_ptr scale_func = non_sse_scale;
if (useSSE) {
scale_func = sse_scale;
}
// now, when you want to do the work:
scale_func( 12, theData_ptr, 512); // this will call the routine that tailored to SSE
// if the CPU supports it, otherwise calls the non-SSE
// version of the function
|
1,894,683 | 1,894,689 | Bitwise Or: C# versus C++ | ). Assume you have two integers, a = 8, b = 2. In C++ a | b is true. I used that behavior to work with collections of flags. For example the flags would be 1, 2, 4, 8 and so on, and any collection of them would be unique. I can't find how to do that in C#, as the | and & operators don't behave like they would in C++. I read documentation about operators in C# but I still don't get it.
EDIT:
Unfortunately, I seem to mess things up somewhere. Take this code for example:
byte flagCollection = 8;
byte flag = 3;
if ((flag | flagCollection) != 0) MessageBox.Show("y"); else MessageBox.Show("n");
This returns "y" for whatever value I put in flag. Which is obvious, because 3 | 8 would be 11. Hmmmm... what I want to do is have a flag collection: 1, 2, 4, 8, 16 and when I give a number, to be able to determine what flags is it.
| The & and | operators in C# are the same as in C/C++.
For instance, 2 | 8 is 10 and 2 & 8 is 0.
The difference is that an int is not automatically treated like a boolean value.
int and bool are distinct types in C#.
You need to compare an int to another int to get a bool.
if (2 & 8) ... // doesn't work
if ((2 & 8) != 0) ... // works
|
1,894,886 | 1,894,955 | Parsing a comma-delimited std::string | If I have a std::string containing a comma-separated list of numbers, what's the simplest way to parse out the numbers and put them in an integer array?
I don't want to generalise this out into parsing anything else. Just a simple string of comma separated integer numbers such as "1,1,1,1,2,1,1,1,0".
| Input one number at a time, and check whether the following character is ,. If so, discard it.
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "1,2,3,4,5,6";
std::vector<int> vect;
std::stringstream ss(str);
for (int i; ss >> i;) {
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
for (std::size_t i = 0; i < vect.size(); i++)
std::cout << vect[i] << std::endl;
}
|
1,894,968 | 1,895,031 | Help with object from mouse algorithm | I wasn't sure what to call this. I'm building a tile based game where the user can click on a tile.
it is a 2d c++ vector of tiles. right now I have an algorithm that positions them like this:
[][][][][][][][][][][]
[][][][][][][][][][][]
[][][][][][][][][][][]
[][][][][][][][][][][]
[][][][][][][][][][][]
[][][][][][][][][][][]
they are positioned based on their size and my tile class holds each of their x and y coordinates, and I have 2 variables for the height and width.
Basically I'd like to find an algorithm that can return the tile my mouse is on based on the mouse's position.
For example: if my mouse (relative to the game window)'s position is 37,0 and each of my tiles is 10 * 10 in size and they are each tilewidth apart then by having my mouse over 37,0 it should return (4,1) meaning the 4th element on the x and the first element on the y. I thought about doing bounding box checks against each rectangle but I think that will use up too much cpu if i check 60 times / second.
Thanks
| If you're not using an event based environment, you do need to code your own object intersection, mouse detection, etc.
Here's the formula in pseudo code for what you want to get:
tile_width = 10;
tile_height = 10;
x_tile = Math.ceil(mousex/tile_width);
y_tile = Math.ceil(mousey/tile_height);
|
1,895,262 | 1,895,271 | How to override the ++ operator in C++ and then print the output using an overriden << operator? | I'm trying to learn overriding operators in C++. But I'm stuck with this:
..\src\application.cpp: In function `int main()':
..\src\application.cpp:29: error: no match for 'operator<<' in 'std::operator<< [with _Traits = std::char_traits](((std::basic_ostream >&)(&std::cout)), ((const char*)"Poly A: ")) << (&A)->Poly::operator++(0)'
Here's the line causing the error, It seems that my postincrement operator isn't returning anything printable:
cout << "Poly A: " << A++ << endl;
I have a Poly.h and a Poly.cpp file:
class Poly{
friend istream& operator>>(istream &in, Poly &robject);
friend ostream& operator<<(ostream &out, Poly &robject);
public:
Poly();
Poly operator++(int);
Poly operator++();
private:
int data[2];
};
Poly.cpp:
Poly Poly::operator++ (){
data[0]+=1;
data[1]+=1;
return *this;}
Poly Poly::operator++ (int){
Poly result(data[0], data[1]);
++(*this);
return result;
}
ostream& operator<<(ostream &out, Poly &robject){
out << "(" << robject.data[0] << ", " << robject.data[1] << ")";
return out;
}
| I think the problem is that you declare your parameters as references:
ostream& operator<<(ostream &out, Poly &robject)
The reference will not bind to the temporaries that you return from your operator++.
If you make the Poly parameter a const reference you should be able to output it.
|
1,895,322 | 1,895,332 | adding const before the brackets in c++ | Just wondering why the syntax for virtual functions uses a const before the curly braces, as below:
virtual void print(int chw, int dus) const;
Incidentally, the code doesnt seem to work without the const, which is interesting.. not sure why?
many thanks!
| The const in the function signature signifies a const member function - Anthony Williams gave a great answer on the implications.
Note that there is nothing special about virtual member functions functions in that regard, constness is a concept that applies to all non-static member functions.
As for why its not working without - you can't call non-const members on a const instance. E.g.:
class C {
public:
void f1() {}
void f2() const {}
};
void test()
{
const C c;
c.f1(); // not allowed
c.f2(); // allowed
}
|
1,895,342 | 1,895,897 | specialization on const member function pointers | I am trying to specialize some utility code on const member functions, but have problems to get a simple test-case to work.
To simplify the work i am utilizing Boost.FunctionTypes and its components<FunctionType> template - a MPL sequence which should contain the tag const_qualified for const member functions.
But using the test-code below, the specialization on const member functions fails. Does anybody know how to make it work?
The test-code prints out (using VC8 and boost 1.40):
non-const
non-const
Expected output is:
non-const
const
The test-code itself:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/mpl/contains.hpp>
namespace ft = boost::function_types;
namespace mpl = boost::mpl;
template<typename F>
struct select
{
template<bool IsConst /* =false */>
struct helper {
static void f() { std::cout << "non-const" << std::endl; }
};
template<>
struct helper</* IsConst= */ true> {
static void f() { std::cout << "const" << std::endl; }
};
typedef ft::components<F> components;
typedef typename mpl::contains<components, ft::const_qualified>::type const_qualified;
typedef helper<const_qualified::value> result;
};
typedef boost::function<void (void)> Functor;
template<typename MF>
Functor f(MF f)
{
return boost::bind(&select<MF>::result::f);
}
class C
{
public:
void f1() {}
void f2() const {}
};
int main()
{
f(&C::f1)(); // prints "non-const" as expected
f(&C::f2)(); // prints "non-const", expected "const"
}
| While its still unclear to me why the approach via function_types::components<> doesn't work, i realized that there is a simpler approach with Boost.FunctionTypes to specialize on const member functions:
The classification meta functions like is_member_function_pointer<> optionally take a tag parameter ...
template<typename F>
struct select
{
/* ... helper-struct as before */
typedef ft::is_member_function_pointer<F, ft::const_qualified> const_qualified;
typedef helper<const_qualified::value> result;
};
|
1,895,412 | 1,895,480 | Get the ip addresses of an interface | Using the output of "ipconfig /all" i can get what I need but I want a more reliable technique to get ip of an interface (practically the interface has to be identified by it's name) in case of ipconfig was corrupted or was not available for any reason.
| Since you mentioned ipconfig, I assume you want to do this on windows.
Windows has a set of IP Helper apis designed for retrieval and modify networking settings.
And here is a simple sample: http://msdn.microsoft.com/en-us/library/aa366298(VS.85).aspx
|
1,895,437 | 1,895,521 | CEditBox or CListBox which one is better for big amout of logging data | This always was a big question for me that for a very big amount of logs (like 100,000 line log) which one is better in performance, scrolling,... also consider formatting the text with color is a must.
| Under the circumstances, I'd probably use a listbox.
You can create a virtual listbox to support lots of items relatively well.
Neither supports color1 but owner-drawn listboxes are easier.
Edit controls are "flow" oriented, not line oriented.
1Other than one foreground and one background color.
|
1,895,595 | 1,895,602 | Should screen dimension constants that hold magic numbers be refactored? | I have a few specific places in my code where I use specific pixel dimensions to blit certain things to the screen. Obviously these are placed in well named constants, but I'm worried that it's still kind of vague.
Example: This is in a small function's local scope, so I would hope it's obvious that the constant's name applies to what the method name refers to.
const int X_COORD = 430.0;
const int Y_COORD = 458.0;
ApplySurface( X_COORD, Y_COORD, .... );
...
The location on the screen was calculated specifically for that spot. I almost feel as if I should be making constants that say SCREEN_BOTTOM_RIGHT so I could do like something like const int X_COORD = SCREEN_BOTTOM_RIGHT - SOME_OTHER_NAME.
Is the code above too ambiguous? Or as a developer would you see that and say, alright, thats (430, 458) on the screen. Got it.
| Depends. Is there a particular reason those constants are what they are? (For instance, is that "430" actually 200 pixels to the left of some other element?)
If so, then it'd probably make more sense to express it in terms of the constant used for the other element (or whatever reason results in that number).
If they're all just arbitrary positions, then expressing them as coordinates makes sense. But chances are, they're not actually arbitrary.
|
1,895,922 | 1,895,947 | Sequence points and partial order | A few days back there was a discussion here about whether the expression
i = ++i + 1
invokes UB
(Undefined Behavior) or not.
Finally the conclusion was made that it invokes UB as the value of 'i' is changing more than once between two sequence points.
I was involved in a discussion with Johannes Schaub in that same thread. According to him
i=(i,i++,i)+1 ------ (1) /* invokes UB as well */
I said (1) does not invoke UB because the side effects of the previous subexpressions are cleared by the comma operator ',' between i and i++ and between i++ and i.
Then he gave the following explanation:
"Yes the sequence point after i++ completes all side effects before it, but there is nothing that stops the assignment side effect overlapping with the side effect of i++.The underlying problem is that the side effect of an assignment is not specified to happen after or before the evaluation of both operands of the assignment, and so sequence points cannot do anything with regard to protecting this: Sequence points induce a partial order: Just because there is a sequence point after and before i++ doesn't mean all side effects are sequenced with regard to i.
Also, notice that merely a sequence point means nothing: The order of evaluations isn't dictated by the form of code. It's dictated by semantic rules. In this case, there is no semantic rule saying when the assignment side effect happens with regard to evaluating both of its operands or subexpressions of those operands".
The statement written in "bold" confused me. As far as I know:
"At certain specified points in the execution sequence called sequence points,all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place."
Since,comma operators also specify execution order the side effect of i++ have been cancelled when we reach the last i.He(Johannes) would have been right had the order of evaluation been not specified(but in case of comma operator it is well specified).
So I just want to know whether (1) invokes UB or not?. Can someone give another valid explanation?
Thanks!
| The C standard says this about assignment operators (C90 6.3.16 or C99 6.5.16 Assignment operators):
The side effect of updating the stored value of the left operand shall occur between the previous and the next sequence point.
It seems to me that in the statement:
i=(i,i++,i)+1;
the sequence point 'previous' to the assignment operator would be the second comma operator and the 'next' sequence point would be the end of the expression. So I'd say that the expression doesn't invoke undefined behavior.
However, this expression:
*(some_ptr + i) = (i,i++,i)+1;
would have undefined behavior because the order of evaluation of the 2 operands of the assignment operator is undefined, and in this case instead of the problem being when the assignment operator's side effect takes place, the problem is you don't know whether the value of i used in the left handle operand will be evaluated before or after the right hand side. This order of evaluation problem doesn't occur in the first example because in that expression the value of i isn't actually used in the left-hand side - all that the assignment operator is interested in is the "lvalue-ness" of i.
But I also think that all this is sketchy enough (and my understanding of the nuances involved are sketchy enough) that I wouldn't be surprised if someone can convince me otherwise (on either count).
|
1,896,341 | 1,896,349 | Can constructor call another constructor in c++? | class A{
A(int a = 5){
DoSomething();
A();
}
A(){...}
}
Can the first constructor call the second one?
| Not before C++11.
Extract the common functionality into a separate function instead. I usually name this function construct().
The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. So, no.
A destructor, however, can be called without a problem.
|
1,896,369 | 1,896,395 | How to use a class object in C++ as a function parameter | I am not sure how to have a function that receives a class object as a parameter. Any help? Here is an example below.
#include<iostream>
void function(class object); //prototype
void function(class tempObject)
{
//do something with object
//use or change member variables
}
Basically I am just confused on how to create a function that will receive a class object as its parameters, and then to use those parameters inside the function such as tempObject.variable.
Sorry if this is kind of confusing, I am relatively new to C++.
| class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.
e.g.
class ANewType
{
// ... details
};
This defines a new type called ANewType which is a class type.
You can then use this in function declarations:
void function(ANewType object);
You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.
If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.
void function(ANewType& object); // object passed by reference
This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.
[* The class keyword is also used in template definitions, but that's a different subject.]
|
1,896,404 | 1,896,415 | fread speeds managed unmanaged | Ok, so I'm reading a binary file into a char array I've allocated with malloc.
(btw the code here isn't the actual code, I just wrote it on the spot to demonstrate, so any mistakes here are probably not mistakes in the actual program.) This method reads at about 50million bytes per second.
main
char *buffer = (char*)malloc(file_length_in_bytes*sizeof(char));
memset(buffer,0,file_length_in_bytes*sizeof(char));
//start time here
read_whole_file(buffer);
//end time here
free(buffer);
read_whole_buffer
void read_whole_buffer(char* buffer)
{
//file already opened
fseek(_file_pointer, 0, SEEK_SET);
int a = sizeof(buffer[0]);
fread(buffer, a, file_length_in_bytes*a, _file_pointer);
}
I've written something similar with managed c++ that uses filestream I believe and the function ReadByte() to read the entire file, byte by byte, and it reads at around 50million bytes per second.
Also, I have a sata and an IDE drive in my computer, and I've loading the file off of both, doesn't make any difference at all(Which is weird because I was under the assumption that SATA read much faster than IDE.)
Question
Maybe you can all understand why this doesn't make any sense to me. As far as I knew, it should be much faster to fread a whole file into an array, as opposed to reading it byte by byte. On top of that, through testing I've discovered that managed c++ is slower (only noticeable though if you are benchmarking your code and you require speed.)
SO
Why in the world am I reading at the same speed with both applications. Also is 50 million bytes from a file, into an array quick?
Maybe I my motherboard is bottle necking me? That just doesn't seem to make much sense eather.
Is there maybe a faster way to read a file into an array?
thanks.
My 'script timer'
Records start and end time with millisecond resolution...Most importantly it's not a timer
#pragma once
#ifndef __Script_Timer__
#define __Script_Timer__
#include <sys/timeb.h>
extern "C"
{
struct Script_Timer
{
unsigned long milliseconds;
unsigned long seconds;
struct timeb start_t;
struct timeb end_t;
};
void End_ST(Script_Timer *This)
{
ftime(&This->end_t);
This->seconds = This->end_t.time - This->start_t.time;
This->milliseconds = (This->seconds * 1000) + (This->end_t.millitm - This->start_t.millitm);
}
void Start_ST(Script_Timer *This)
{
ftime(&This->start_t);
}
}
#endif
Read buffer thing
char face = 0;
char comp = 0;
char nutz = 0;
for(int i=0;i<(_length*sizeof(char));++i)
{
face = buffer[i];
if(face == comp)
nutz = (face + comp)/i;
comp++;
}
| Transfers from or to main memory run at speeds of gigabytes per second. Inside the CPU data flows even faster. It is not surprising that, whatever you do at the software side, the hard drive itself remains the bottleneck.
Here are some numbers from my system, using PerformanceTest 7.0:
hard disk: Samsung HD103SI 5400 rpm: sequential read/write at 80 MB/s
memory: 3 * 2 GB at 400 MHz DDR3: read/write around 2.2 GB/s
So if your system is a bit older than mine, a hard drive speed of 50 MB/s is not surprising. The connection to the drive (IDE/SATA) is not all that relevant; it's mainly about the number of bits passing the drive heads per second, purely a hardware thing.
Another thing to keep in mind is your OS's filesystem cache. It could be that the second time round, the hard drive isn't accessed at all.
The 180 MB/s memory read speed that you mention in your comment does seem a bit on the low side, but that may well depend on the exact code. Your CPU's caches come into play here. Maybe you could post the code you used to measure this?
|
1,896,432 | 2,811,327 | How to mix C++ Qt objects and Qt Jambi objects | I'm trying to combine some existing Qt code written in C++ with some code written in Java using Qt Jambi, but I'm not quite sure how to do it. I'm basically trying to acieve two things:
Pass a QObject from C++ to Java using JNI
Pass a Qt Jambi QObject from Java to C++
It looks like I can pass the pointer directly and then wrap it in QNativePointer on the Java side, but I can't figure out how to turn a QNativePointer back into the original object, wrapped by Qt Jambi.
Eg: I can pass a QWidget* as a long to Java and then create a QNativePointer in Java, but how can I then construct a QWidget out of this? QJambiObject and QObject dont seem to have a "setNativePointer" method and I'm not sure how to convert it.
In C++:
QWidget* widget = ...
jclass cls = env->FindClass("Test");
jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
env->CallStaticVoidMethod(cls, mid, int(widget));
In Java:
public class Test {
public static void test (int ptr) {
QNativePointer pointer = new QNativePointer(QNativePointer.Type.Int);
pointer.setIntValue(ptr);
QWidget widget = ...
Thanks!
| For other people looking at this, check this out:
http://labs.trolltech.com/blogs/2007/08/24/extremely-interesting-jambi-trick-x-instantiating-java-widgets-from-c/
Especially this part:
The qtjambi_from_QWidget() call will
either create a new Java widget if the
parent widget was created in C++, or
it will return the existing Java
object if the parent was created in
Java. If it has to create a new java
object, the type of this will be the
closest Java supertype known to Qt
Jambi. If you have mapped your own C++
widgets and want to use them correctly
in calls such as these, you have to
make sure the initialization code of
your generated library is called prior
to the conversion takes place. Also
note that in qtjambi_core.h you will
find several other convenient
conversion functions that can be used
to convert back and forth between C++
and JNI, as well as other convenient,
JNI-based code.
|
1,896,505 | 1,896,520 | Strange error occurred while using cmake | Does anyone know what "The C compiler "cl" is not able to compile a simple test program." means?
I am trying to compile Wt using CMake on MSVC 9.
The OS is Windows XP.
Here is the full log:
Check for working C compiler: cl Check
for working C compiler: cl -- broken
CMake Error at I:/Program Files/CMake
2.8/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:50
(MESSAGE): The C compiler "cl" is
not able to compile a simple test
program.
It fails with the following output:
Change Dir:
I:/SophisPal/build/CMakeFiles/CMakeTmp
Run Build
Command:C:\PROGRA~1\MICROS~1.0\Common7\IDE\VCExpress.exe
CMAKE_TRY_COMPILE.sln /build Debug
/project cmTryCompileExec
Microsoft (R) Visual C++ Express
Edition Version 9.0.30729.1.
Copyright (C) Microsoft Corp 2007.
All rights reserved.
1>------ Build started: Project:
cmTryCompileExec, Configuration: Debug
Win32 ------
1>Compiling...
1>Microsoft (R) 32-bit C/C++
Optimizing Compiler Version
15.00.30729.01 for 80x86
1>Copyright (C) Microsoft
Corporation. All rights reserved.
1>cl /Od /D "WIN32" /D "_WINDOWS" /D
"_DEBUG" /D "CMAKE_INTDIR=\"Debug\""
/D "_MBCS" /FD /RTCs /MDd
/Fo"cmTryCompileExec.dir\Debug\"
/Fd"I:/SophisPal/build/CMakeFiles/CMakeTmp/Debug/cmTryCompileExec.pdb"
/W3 /c /Zi /TC /Zm1000
1> .\testCCompiler.c
1>testCCompiler.c
1>Compiling manifest to resources...
1>Microsoft (R) Windows (R) Resource
Compiler Version 6.1.6723.1
1>Copyright (C) Microsoft
Corporation. All rights reserved.
1>Linking...
1>Embedding manifest...
1>Project : error PRJ0003 : Error
spawning 'cmd.exe'.
1>Build log was saved at
"file://i:\SophisPal\build\CMakeFiles\CMakeTmp\cmTryCompileExec.dir\Debug\BuildLog.htm"
1>cmTryCompileExec - 1 error(s), 0
warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
CMake will not be able to correctly
generate this project. Call Stack
(most recent call first):
CMakeLists.txt:7 (PROJECT)
Configuring incomplete, errors
occurred!
| I googled for the cmd.exe error and came up with this page. Looks like Visual studio needs to be configured with a few paths so it knows how to find cmd.exe. Here are the steps from that thread:
What you must do is change MSVS options (Tools menu > Options > Project and Solutions > VC++ Directories) to ensure that
$(SystemRoot)
$(SystemRoot)\System32
$(SystemRoot)\System32\wbem
are specified BEFORE $(PATH).
|
1,896,527 | 1,896,548 | counting letters in a text file | Can sommebody please tell me what is not right about this code? It compiles and everything great but the output is solid zero's all the way down. So it is not counting the letters.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const char FileName[] = "c:/test.txt";
int main ()
{
string lineBuffer;
ifstream inMyStream (FileName); //open my file stream
if (inMyStream.is_open())
{
//create an array to hold the letter counts
int upperCaseCount[26] = {0};
int lowerCaseCount[26] = {0};
//read the text file
while (!inMyStream.eof() )
{
//get a line of text
getline (inMyStream, lineBuffer);
//read through each letter in the lineBuffer
char oneLetter;
for( int n=0; n < (int)lineBuffer.length(); ++n )
{
oneLetter = char( lineBuffer[n] ); //get a letter
if (oneLetter >= 'A' && oneLetter <='Z')
{ //decide if it is a capital letter
upperCaseCount[int(oneLetter)- 65]++; //make the index match the count array
if (oneLetter >= 'a' && oneLetter <='z')
{ //decide if it is a lower letter
lowerCaseCount[int(oneLetter)- 65]++; //make the index match the count array
}//end
}//end
}
}//end of while
inMyStream.close(); //close the file stream
//display the counts
for (int i= 0; i < 26; i++)
cout << char(i + 65) << "\t\t" << lowerCaseCount[i] << char(i + 95) << "\t\t" << lowerCaseCount[i] << endl;
}//end of if
else cout << "File Error: Open Failed";
return 0;
}
| You just have your if statement scoping wrong here. Each letter can be either uppercase or lowercase, but the way your if statements are scoped, you're only checking for lowercase if the letter is already uppercase, which of course is nonsensical.
You want something more like:
for(unsigned n = 0; n < lineBuffer.length(); ++n)
{
oneLetter = char( lineBuffer[n] ); // get a letter
if (oneLetter >= 'A' && oneLetter <='Z') {
upperCaseCount[int(oneLetter)- 'A']++;
}
else if (oneLetter >= 'a' && oneLetter <='z') {
lowerCaseCount[int(oneLetter)- 'a']++;
}
}
|
1,896,597 | 1,896,627 | Lame operator redefinition error | Sorry it's lame but I can't figure it out:
class Address {
public:
uint32_t addr;
uint16_t port;
public:
Address();
Address(uint32_t addr, uint16_t port);
Address(const Address & src);
Address& operator=(const Address &src);
bool isNull();
friend std::ostream& operator<<(std::ostream& os, const Address& addr);
friend std::ostream& operator<<( const Address& addr, std::ostream& os);
};
std::ostream& operator<<( std::ostream& os, const Address& addr){
return os << " ( " << addr.addr << " : " << addr.port << " ) ";
}
std::ostream& operator<<( const Address& addr, std::ostream& os){
return os << addr;
}
says:
../src/streamShare/types.h: In function ‘std::ostream& streamShare::operator<<(std::ostream&, const streamShare::Address&)’:
../src/streamShare/types.h:46: error: no match for ‘operator<<’ in ‘os << " ( "’
../src/streamShare/types.h:45: note: candidates are: std::ostream& streamShare::operator<<(std::ostream&, const streamShare::Address&)
Maybe it's just that I'm in sunday hangover... but hey ostream& << "oihoih" should work !!!
| Well, if I include
#include <cstdint>
#include <iostream>
at the beginning of your code, I can compile it using g++ -c -std=c++0x Account.cpp (g++ 4.4.1).
|
1,896,644 | 1,896,686 | CSocket Server get the client IP Address | How can I get the ip address of a client when he tries to connect to the server?
I'm using CSocket class.
|
void getPeer(unsigned short& port, std::string& peer);
Returns information about the remote
side of the socket. port is the port
on which the connection is held, and
peer is the host to which the socket
is connected. The peer is either a
fully qualified domain name (if the IP
address can be resovled via
gethostbyaddr(2) or a stringified
dotted IP address if not.
From here.
The getPeer function will either return the domain name or the IP address of the remote peer, depending on what it can find.
There appear to be two different definitions of CSocket depending on operating system or library. If you're using the MFC definition of CSocket then the function you want is actually getPeerName() or getPeerNameEx() if you're using IP6. From here:
BOOL GetPeerName(
CString& rPeerAddress,
UINT& rPeerPort
);
BOOL GetPeerName(
SOCKADDR* lpSockAddr,
int* lpSockAddrLen
);
And from here:
BOOL GetPeerNameEx(
CString& rPeerAddress,
UINT& rPeerPort
);
|
1,896,656 | 1,896,673 | simple wildcard match with std::string | I have std::string with the follwing format
std::string s = "some string with @lable"
I have to find all instances of '@' and then find the identifier right after the '@' ,
this ID has a value (in this case 'lable' stored for it in a look up table. I will then replace the @ and the id with the found value.
for example suppose the ID label has the value '1000' after the process the string will look like :
"some string with 1000"
my first version used boost::regex, but I had to dump it after I was told that new libs are not allowed in the next few builds.
so is there some elegant way to do it with vanilla std::string and std algorithms ?
| You can use std::find to search for the @, and get a pair of iterators forming a range which begins at the @ and ends at the next white space character (or end of the string). Then just pass the iterators to std::string::replace() to do the actual sub-string replacement.
For example:
std::string s = "some string with @lable";
std::string::iterator beg = std::find(s.begin(), s.end(), '@');
std::string::iterator end = std::find(beg, s.end(), ' ');
s.replace(beg, end, "whatever");
If you also want to count things like tabs or carriage returns as spaces, you can use std::find_if along with ::isspace.
|
1,896,830 | 1,896,864 | Why should I use the "using" keyword to access my base class method? | I wrote the below code in order to explain my issue. If I comment the line 11 (with the keyword "using"), the compiler does not compile the file and displays this error: invalid conversion from 'char' to 'const char*'. It seems to not see the method void action(char) of the Parent class in the Son class.
Why the compiler behave this way? Or have I done something wrong?
class Parent
{
public:
virtual void action( const char how ){ this->action( &how ); }
virtual void action( const char * how ) = 0;
};
class Son : public Parent
{
public:
using Parent::action; // Why should i write this line?
void action( const char * how ){ printf( "Action: %c\n", *how ); }
};
int main( int argc, char** argv )
{
Son s = Son();
s.action( 'a' );
return 0;
}
| The action declared in the derived class hides the action declared in the base class. If you use action on a Son object the compiler will search in the methods declared in Son, find one called action, and use that. It won't go on to search in the base class's methods, since it already found a matching name.
Then that method doesn't match the parameters of the call and you get an error.
See also the C++ FAQ for more explanations on this topic.
|
1,896,833 | 1,896,881 | linking assembly and c problem | Trying to understand how to link a function that is defined in a struct, the function is in the assembly code, and am trying to call it from c. I think am missing a step cause when I call the function, I get an unresolved external symbol...
;Assembly.asm
.686p
.mmx
.xmm
.model flat
include Definitions.inc
.code
?Initialize@Foo@@SIXPAUFee@@@Z proc
jmp $
?Initialize@Foo@@SIXPAUFee@@@Z endp
end
//CFile.c
struct Fee
{
signed long id;
}
struct Foo
{
static void Initialize(Fee *);
}
int startup(Fee * init)
{
Foo::Initialize(init); //<-- This is unresolved
return 0;
}
| Your assembly code defines a function whose decorated name decodes to
public: static void __fastcall Foo::InitializeCurrentCpu(struct Fee *)
As obtained through the undname.exe utility. Foo::InitializeCurrentCpu() won't be a match for Foo::Initialize(), the name doesn't match. Nor does the calling convention.
Write this code in C++ first and look at the .map file for the correct decorated name. Or declare the function with extern "C" to suppress C++ decoration.
|
1,897,006 | 1,897,203 | Recursive calls when trying to wrap and override the global operator new | I have not programmed C++ for a while and encountered a strange behavior when toying with overloaded global operators new and delete.
The essence of the problem seems to be that a wrapper build around the default global new and residing in a separate source file
nevertheless calls an operator new overloaded in another (and separately compiled so) source file.
Why is it so, i.e. which language rules / features am I violating / misusing?
Thanks in advance, the details are below.
Project structure:
.
..
main.cpp
mem_wrappers.h
mem_wrappers.cpp
Project files contents:
main.cpp
#include "./mem_wrappers.h"
#include <iostream>
#include <cstring>
void* operator new[] (size_t sz) throw (std::bad_alloc) {
std::cout << "overloaded new()[]" << std::endl;
return default_arr_new_wrapper(sz);
}
int main() {
const unsigned num = 5;
int * i_arr = new int [num];
return 0;
}
mem_wrappers.h
#include <cstring>
void * default_arr_new_wrapper(size_t sz);
mem_wrappers.cpp
#include <new>
#include <cstring>
#include <iostream>
void * default_arr_new_wrapper(size_t sz) {
std::cout << "default_arr_new wrapper()" << std::endl;
return ::operator new[](sz);
}
Complied with g++ main.cpp mem_wrappers.cpp --ansi --pedantic -Wall when run gives endless operator new[] to default_arr_new_wrapper and vice versa calls resulting in the following output:
overloaded new()[]
default_arr_new_wrapper()
overloaded new()[]
default_arr_new_wrapper()
...
and, finally, in SO (the MS Visual Studio Express compiler behaves alike).
Compilers I use: gcc version 3.4.2 (mingw-special) and MS Visual Studio 2008 Version 9.0.30729.1 SP.
EDIT / UPDATE
If (as the first answers and comments suggest) the global operator new is effectively redefined for the whole executable just by overloading it [the operator] in a single compilation unit, then:
is it that merely linking with an object file whose source overloads the global operator new makes any application or library change its (well, lets call it so) memory allocation policy? Is thus this overload operator efficiently providing a hook for the language runtime (I mean what's with those linker symbols in the already-compiled-without-any-overloaded-new object files, is it that there can be only one new)?
P.S. I know that malloc and free would do, and already tried them before posting here (worked ok), but nevertheless, what's behind this behavior (and what if I was actually to wrap the default operator new anyway? :)) ?
| If you read the wording in the standard, what you do to global operator new function when you define your own is called replacement (not overloading and not overriding). Most of the time when people talk about changing the global operator new functionality they use the term "overloading" and refer to new as an "operator". This often leads to confusion, when the resultant behavior does not agree with what is normally expected from operator overloading. This is apparently what happens in your case. You expect overloading behavior, but what you really get is replacement: once you defined one replacement version of global operator new function in some translation unit it works for the entire program. (And new is not really an operator.)
As a side note, replacement is one of those rare "unfair" language features, in a sense that it is not generally available to the user. You can't write "replaceable" functions in C++. You can't write anything that would behave the way default library implementations of global operator new and operator new behave. (Replacement is a language-level manifestation of the linker concept of a weak symbol).
|
1,897,026 | 1,898,361 | Task Execution Framework for VC++? | Does anyone know of a Java ExecutorService equivlent in VC++ 2008? What I want is a framework which I can pass tasks to fixed size thread pool. The framework should manage the thread pool itself (i.e. creation and destruction of threads).
| Vista has a new thread pool API (in addition to existing, rather spartan thread pool API windows has had for a while): http://msdn.microsoft.com/en-us/library/ms686766%28VS.85%29.aspx . This API is not bound to any specific version of MSVC/VS but of course to use the new stuff you need to have Vista/Server 2008 or better. QueueUserWorkItem and RegisterWaitForSingleObject may be sufficient for your needs. As Nikola points out, 2010 will have the PPL. .NET also has some nice thread pool apis if you can code against C# or maybe C++/CLI instead of C++.
|
1,897,030 | 1,898,745 | Tile sizing algorithm | I'm making a tile game in c++. Right now when the game loads all the tiles place themselves based on:
tilesize -> they are squares so this is width and height
tile_count_x
tile_count_y
I have the following variables:
desktop_width
desktop_height
game_window_width
game_window_height
tile_count_x
tile_count_y
Based on these values, I'm looking for an algorithm that will set an appropriate window size given the desktop and tile_count constraints. Then within this, I want my tiles to have an offset that will border x% around the window which will basically decide the tilesize too:
Example:
If I have 10 * 3 of tiles then:
______________________________
Window Title _[]X
------------------------------
| |
| [][][][][][][][][][] |
| [][][][][][][][][][] |
| [][][][][][][][][][] |
| |
------------------------------
I'm just not sure the formula required to do this.
EDIT (from comments):
Tilesize changes, tilecountx and y are static
I want the gamewindow to be as big as it can be given the desktop resolution, but I also want its aspect ratio to respect the tilecoutx and tilecounty
I found an example of what I mean, open up Minesweeper in Windows
| Here is how I solved it...
//WINDOW SIZE SETUP
//choose the smaller TILE_SIZE
if (DESKTOP_WIDTH / TILE_COUNT_X > DESKTOP_HEIGHT / TILE_COUNT_Y)
{
TILE_SIZE = DESKTOP_HEIGHT / TILE_COUNT_Y;
}
else
{
TILE_SIZE = DESKTOP_WIDTH / TILE_COUNT_X;
}
//Set screen size and consider a 5 tile border
SCREEN_WIDTH = TILE_SIZE * (TILE_COUNT_X + 5);
SCREEN_HEIGHT = TILE_SIZE * (TILE_COUNT_Y + 5);
//resize window until it satisfies resolution constraints
while( SCREEN_WIDTH > (DESKTOP_WIDTH - (DESKTOP_WIDTH * 0.07)))
{
TILE_SIZE --;
SCREEN_WIDTH = TILE_SIZE * (TILE_COUNT_X + 5);
SCREEN_HEIGHT = TILE_SIZE * (TILE_COUNT_Y + 5);
}
while( SCREEN_HEIGHT > (DESKTOP_HEIGHT - (DESKTOP_HEIGHT * 0.15)))
{
TILE_SIZE -- ;
SCREEN_WIDTH = TILE_SIZE * (TILE_COUNT_X + 5);
SCREEN_HEIGHT = TILE_SIZE * (TILE_COUNT_Y + 5);
}
for(int i = 0; i < 8; ++i) //Ensure resolution is multiple of 8
{
if (SCREEN_WIDTH % 8 != 0) //remainder means not multiple of 8
{
SCREEN_WIDTH += 1;
}
if (SCREEN_HEIGHT % 8 != 0)
{
SCREEN_HEIGHT += 1;
}
}
X_OFFSET = (SCREEN_WIDTH - (TILE_SIZE * TILE_COUNT_X)) / 2;
Y_OFFSET = (SCREEN_HEIGHT - (TILE_SIZE * TILE_COUNT_Y)) / 2;
|
1,897,184 | 1,897,394 | static variable initialisation code never gets called | I've got an application that's using a static library I made. One .cpp file in the library has a static variable declaration, whose ctor calls a function on a singleton that does something- e.g. adds a string.
Now when I use that library from the application, my singleton doesn't seem to contain any traces of the string that was supposed to be added.
I'm definitely missing something but I don't know what..
| If you have an object in a static library that is not EXPLICITLY used in the application. Then the linker will not pull that object from the lib into the application.
There is a big difference between static and dynamic libraries.
Dynamic Library:
At compile time nothing is pulled from the dynamic library. Extra code is added to explicitly load and resolve the symbols at run-time. At run time the whole library is loaded and thus object initializers are called (though when is implementation detail).
Static libraries are handled very differently:
When you link against a static library it pulls all the items that are not defined in application that are defined in the library into the application. This is repeated until there are no more dependencies that the library can resolve. The side effect of this is that objects/functions not explicitly used are not pulled form the library (thus global variables that are not directly accessed will not be pulled).
|
1,897,261 | 1,902,688 | C++ Boost: Split String | How can I split a string with Boost with a regex AND have the delimiter included in the result list?
for example, if I have the string "1d2" and my regex is "[a-z]" I want the results in a vector with (1, d, 2)
I have:
std::string expression = "1d2";
boost::regex re("[a-z]");
boost::sregex_token_iterator i (expression.begin (),
expression.end (),
re);
boost::sregex_token_iterator j;
std::vector <std::string> splitResults;
std::copy (i, j, std::back_inserter (splitResults));
Thanks
| I think you cannot directly extract the delimiters using boost::regex. You can, however, extract the position where the regex is found in your string:
std::string expression = "1a234bc";
boost::regex re("[a-z]");
boost::sregex_iterator i(
expression.begin (),
expression.end (),
re);
boost::sregex_iterator j;
for(; i!=j; ++i) {
std::cout << (*i).position() << " : " << (*i) << std::endl;
}
This example would show:
1 : a
5 : b
6 : c
Using this information, you can extract the delimitiers from your original string:
std::string expression = "1a234bc43";
boost::regex re("[a-z]");
boost::sregex_iterator i(
expression.begin (),
expression.end (),
re);
boost::sregex_iterator j;
size_t pos=0;
for(; i!=j;++i) {
std::string pre_delimiter = expression.substr(pos, (*i).position()-pos);
std::cout << pre_delimiter << std::endl;
std::cout << (*i) << std::endl;
pos = (*i).position() + (*i).size();
}
std::string last_delimiter = expression.substr(pos);
std::cout << last_delimiter << std::endl;
This example would show:
1
a
234
b
c
43
There is an empty string betwen b and c because there is no delimiter.
|
1,897,301 | 1,897,499 | Vectored Exception Handling During StackOverflowException | If I've registered my very own vectored exception handler (VEH) and a StackOverflow exception had occurred in my process, when I'll reach to the VEH, will I'll be able to allocate more memory on the stack? will the allocation cause me to override some other memory? what will happen?
I know that in .Net this is why the entire stack is committed during the thread's creation, but let's say i'm writing in native and such scenario occurs ... what will i able to do inside the VEH? what about memory allocation..?
| In the case of a stack overflow, you'll have a tiny bit of stack to work with. It's enough stack to start a new thread, which will have an entirely new stack. From there, you can do whatever you need to do before terminating.
You cannot recover from a stack overflow, it would involve unwinding the stack, but your entire program would be destroyed in the progress. Here's some code I wrote for a stack-dumping utility:
// stack overflows cannot be handled, try to get output then quit
set_current_thread(get_current_thread());
boost::thread t(stack_fail_thread);
t.join(); // will never exit
All this did was get the thread's handle so the stack dumping mechanism knew which thread to dump, start a new thread to do the dumping/logging, and wait for it to finish (which won't happen, the thread calls exit()).
For completeness, get_current_thread() looked like this:
const HANDLE process = GetCurrentProcess();
HANDLE thisThread = 0;
DuplicateHandle(process, GetCurrentThread(), process,
&thisThread, 0, true, DUPLICATE_SAME_ACCESS);
All of these are "simple" functions that don't require a lot of room to work (and keep in mind, the compiler will inline these msot likely, removing a function call). You cannot, contrarily, throw an exception. Not only does that require much more work, but destructors can do quite a bit of work (like deallocating memory), which tend to be complex as well.
Your best bet is to start a new thread, save as much information about your application as you can or want, then terminate.
|
1,897,675 | 1,897,701 | Overriding multiple inherited templated functions with specialized versions | Okay, sample code first; this is my attempt at communicating what it is that I'm trying to do, although it doesn't compile:
#include <iostream>
template <class T>
class Base
{
public:
virtual void my_callback() = 0;
};
class Derived1
: public Base<int>
, public Base<float>
{
public:
void my_callback<int>()
{
cout << "Int callback for Derived1.\n";
}
void my_callback<float>()
{
cout << "Float callback for Derived\n";
}
};
class Derived2
: public Base<int>
, public Base<float>
{
public:
void my_callback<int>()
{
cout << "Int callback for Derived2.\n";
}
void my_callback<float>()
{
cout << "Float callback for Derived2\n";
}
};
int main()
{
{
Derived1 d;
Base<int> * i_p = d;
Base<float> * i_f = d;
i_p->my_callback();
i_f->my_callback();
}
{
Derived2 d;
Base<int> * i_p = d;
Base<float> * i_f = d;
i_p->my_callback();
i_f->my_callback();
}
//Desired output:
// Int callback for Derived1.
// Float callback for Derived1
// Int callback for Derived2.
// Float callback for Derived2
system("Pause");
}
So, what I'm trying to do is to make a sort of wrapper class to inherit from that will automatically connect the derived class to various callback lists; it needs to connect a specific instance of the derived class to the list, and I want the "user" to have / get to make the callback functions as part of making the derived class, as you can see.
It seems like this should be able to work, although I may need to use a different syntax. If it can't work, do you have any suggestions?
| Yes, you can make this work:
#include <iostream>
using namespace std;
template <class T>
class Base
{
public:
virtual void my_callback() = 0;
};
class Derived1 : public Base<int>, public Base<float>
{
public:
void Base<int>::my_callback() {
cout << "Int callback for Derived1.\n";
}
void Base<float>::my_callback() {
cout << "Float callback for Derived\n";
}
};
class Derived2 : public Base<int>, public Base<float>
{
public:
void Base<int>::my_callback() {
cout << "Int callback for Derived2.\n";
}
void Base<float>::my_callback() {
cout << "Float callback for Derived2\n";
}
};
int main()
{
{
Derived1 d;
Base<int> * i_p = &d;
Base<float> * i_f = &d;
i_p->my_callback();
i_f->my_callback();
}
{
Derived2 d;
Base<int> * i_p = &d;
Base<float> * i_f = &d;
i_p->my_callback();
i_f->my_callback();
}
}
Output:
Int callback for Derived1.
Float callback for Derived
Int callback for Derived2.
Float callback for Derived2
|
1,897,821 | 1,897,845 | Performance of C++ Operators | Is there any sort of performance difference between the arithmetic operators in c++, or do they all run equally fast? E.g. is "++" faster than "+=1"? What about "+=10000"? Does it make a significant difference if the numbers are floats instead of integers? Does "*" take appreciably longer than "+"?
I tried performing 1 billion each of "++", "+=1", and "+=10000". The strange thing is that the number of clock cycles (according to time.h) is actually counterintuitive. One might expect that if any of them are the fastest, it is "++", followed by "+=1", then "+=10000", but the data shows a slight trend in the opposite direction. The difference is more pronounced on 10 billion operations. This is all for integers.
I am dabbling in scientific computing, so I wanted to test the performance of operators. If any of the operators operated in time that was linear in terms of the inputs, for example.
| No, no, yes*, yes*, respectively.
* but do you really care?
EDIT: to give some kind of idea with a modern processor, you may be able to do 200 integer additions in the time it takes to make one memory access, and only 50 integer multiplications. If you think about it, you're still going to be bound by the memory accesses most of the time.
|
1,897,844 | 1,897,888 | C++ templates and ambiguity problem | I have a subset of a pointer class that look like:
template <typename T>
struct Pointer
{
Pointer();
Pointer(T *const x);
Pointer(const Pointer &x);
template <typename t>
Pointer(const Pointer<t> &x);
operator T *() const;
};
The goal of the last constructor is to allow to pass a Pointer of a subclass, or basically any type that is implicitly convertable to T *. This actual rule is only enforced by the definition of the constructor and the compiler can't actually figure it out by the declaration alone. If I drop it, and try to pass a Pointer<Sub> to a constructor of Pointer<Base>, I get a compile error, despite of the possible path through operator T *().
While it solves the above problem, it creates another one. If I have an overloaded function whose one overload takes a Pointer<UnrelatedClass> and the other takes Pointer<BaseClass>, and I try to invoke it with a Pointer<SubClass>, I get an ambiguity between the two overloads, with the intention, ofcourse, that the latter overload will be called.
Any suggestions? (Hopefully I was clear enough)
| The cure for your problem is called SFINAE (substitution failure is not an error)
#include "boost/type_traits/is_convertible.hpp"
#include "boost/utility/enable_if.hpp"
template<typename T>
class Pointer {
...
template<typename U>
Pointer(const Pointer<U> &x,
typename boost::enable_if<
boost::is_convertible<U*,T*>
>::type* =0)
: ...
{
...
}
...
};
If U* is convertible to T* the enable_if will have a typedef member type defaulting to void. Then, everything is fine. If U* is not convertible to T* this typedef member is missing, substitution fails and the constructor template is ignored.
This solves your conversion and ambiguity problems.
In response to the comment: is_convertible looks something like this:
typedef char one; // sizeof == 1 per definition
struct two {char c[2];}; // sizeof != 1
template<typename T, typename U>
class is_convertible {
static T source();
static one sink(U);
static two sink(...);
public:
static const bool value = sizeof(sink(source()))==1;
};
|
1,897,860 | 1,902,525 | Parsing the map file? | I am looking to use the map file to resolve addresses that I get from the exe. Is there a library for parsing it or a more easier to parse format?
| The primary issue is that the format of map files varies with compiler vendors and there are too many compiler vendors out there for us to guess which one you are using. BTW, there is no standard format for map files; as there is no requirement for one.
I look at the layout of the map file and write my own search programs using awk, Perl, Java, C, or whatever is handy and quick (or a language I want to learn).
|
1,897,940 | 1,897,979 | In what ways do C++ exceptions slow down code when there are no exceptions thown? | I have read that there is some overhead to using C++ exceptions for exception handling as opposed to, say, checking return values. I'm only talking about overhead that is incurred when no exception is thrown. I'm also assuming that you would need to implement the code that actually checks the return value and does the appropriate thing, whatever would be the equivalent to what the catch block would have done. And, it's also not fair to compare code that throws exception objects with 45 state variables inside to code that returns a negative integer for every error.
I'm not trying to build a case for or against C++ exceptions solely based on which one might execute faster. I heard someone make the case recently that code using exceptions ought to run just as fast as code based on return codes, once you take into account all the extra bookkeeping code that would be needed to check the return values and handle the errors. What am I missing?
| There is a cost associated with exception handling on some platforms and with some compilers.
Namely, Visual Studio, when building a 32-bit target, will register a handler in every function that has local variables with non-trivial destructor. Basically, it sets up a try/finally handler.
The other technique, employed by gcc and Visual Studio targeting 64-bits, only incurs overhead when an exception is thrown (the technique involves traversing the call stack and table lookup). In cases where exceptions are rarely thrown, this can actually lead to a more efficient code, as error codes don't have to be processed.
|
1,898,212 | 1,898,255 | Convert a vector<unsigned char> to vector<unsigned short> | I'm getting data from a binary file, reading from file and writing in a vector of unsigned char. I can't edit it, because I'm using a external library.
But the data that I'm reading from file is a 16 bits image, and I'd like to put the data in a vector of unsigned short
Maybe I can do a cast for it?
Rgds.
| A generic approach (not bullet proof):
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
typedef unsigned char u8;
typedef unsigned short u16;
u16 combine_two_bytes(u8 a, u8 b) {
return a | (b << 8);
}
template<typename InIter, typename OutIter, typename InT, typename OutT>
void combine_pairs(InIter in, InIter in_end, OutIter out, OutT (*func)(InT, InT)) {
while(1) {
if(in == in_end) {
break;
}
InT &left = *in++;
if(in == in_end) {
break;
}
InT &right = *in++;
*out++ = func(left, right);
}
}
int main() {
using namespace std; // lazy
u8 input[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
const size_t in_size = sizeof(input) / sizeof(*input);
u16 output[in_size / 2];
cout << "Original: ";
copy(input, input + in_size, ostream_iterator<int>(cout, " "));
cout << endl;
combine_pairs(input, input + in_size, output, combine_two_bytes);
cout << "Transformed: ";
copy(output, output + in_size / 2, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
|
1,898,284 | 1,898,302 | Declare default parameter circular reference without pointers? | Is there any way to declare these classes in a header file without indirection?
// Forwards declaration of B
class B;
class A
{
public:
// Default parameter referring to B. May return its parameter
const B& func(const B& b = B());
};
class B
{
public:
// B ctors
B() {}
B(const B&) {}
// B has A as a member
A a;
};
Visual C++ 2008 tells me with this:
error C2514: 'B' : class has no constructors
and points to the forward declaration of B ("class B;") and obviously can't see B's constructors below. A can't follow B because B contains A as a member.
If indirection must be used, what's the best way? Perhaps in C++0x B's A could be a unique_ptr member? Or maybe there's a boost class purely to sidestep this issue?
| Instead of a default parameter declare two overloads, one that takes a B by reference and one that takes no parameter. In the one that takes no parameter, call the other with B(), which will work because that method can be defined after B is defined.
...
void func();
void func(const B& b);
};
class B...
void A::func() { func(B()); }
void A::func(const B&) { }
Update:
func() returns a const B&...
That's probably not a good idea. With that definition, something like:
const B& foo = a.func();
foo.bar();
would cause the dreaded "undefined behavior" (i.e., crash) because the B to which you have a reference will be destroyed as soon as the first statement is complete. Returning things other than class members by reference is usually a bad idea.
If you really want to do this, then I think you're stuck with forcing the caller to explicitly pass in B(), that is have no default parameter.
a.func(B()).bar();
(This is the only way to avoid undefined behavior with such a function.)
Of course you could just return a copy instead of a reference, but I presume you have a reason for not doing that.
Depending on what you're doing you may be able to set up better semantics using a smart pointer like shared_ptr instead of references so that you can effectively ignore the lifetimes of the objects. You then have to start being careful of reference cycles instead, however.
I can't tell what you're trying to use this for, but you might want to have a look at some Design Patterns to see if there is an established best-practice for it. You may find that this little problem is a symptom of an unfortunate choice of class structure or containment.
|
1,898,374 | 1,898,404 | Does the JVM create a mutex for every object in order to implement the 'synchronized' keyword? If not, how? | As a C++ programmer becoming more familiar with Java, it's a little odd to me to see language level support for locking on arbitrary objects without any kind of declaration that the object supports such locking. Creating mutexes for every object seems like a heavy cost to be automatically opted into. Besides memory usage, mutexes are an OS limited resource on some platforms. You could spin lock if mutexes aren't available but the performance characteristics of that are significantly different, which I would expect to hurt predictability.
Is the JVM smart enough in all cases to recognize that a particular object will never be the target of the synchronized keyword and thus avoid creating the mutex? The mutexes could be created lazily, but that poses a bootstrapping problem that itself necessitates a mutex, and even if that were worked around I assume there's still going to be some overhead for tracking whether a mutex has already been created or not. So I assume if such an optimization is possible, it must be done at compile time or startup. In C++ such an optimization would not be possible due to the compilation model (you couldn't know if the lock for an object was going to be used across library boundaries), but I don't know enough about Java's compilation and linking to know if the same limitations apply.
| Speaking as someone who has looked at the way that some JVMs implement locks ...
The normal approach is to start out with a couple of reserved bits in the object's header word. If the object is never locked, or if it is locked but there is no contention it stays that way. If and when contention occurs on a locked object, the JVM inflates the lock into a full-blown mutex data structure, and it stays that way for the lifetime of the object.
EDIT - I just noticed that the OP was talking about OS-supported mutexes. In the examples that I've looked at, the uninflated mutexes were implemented directly using CAS instructions and the like, rather than using pthread library functions, etc.
|
1,898,524 | 1,898,556 | Difference between pointer to a reference and reference to a pointer | What is the difference between pointer to a reference, reference to a pointer and pointer to a pointer in C++?
Where should one be preferred over the other?
| First, a reference to a pointer is like a reference to any other variable:
void fun(int*& ref_to_ptr)
{
ref_to_ptr = 0; // set the "passed" pointer to 0
// if the pointer is not passed by ref,
// then only the copy(parameter) you received is set to 0,
// but the original pointer(outside the function) is not affected.
}
A pointer to reference is illegal in C++, because -unlike a pointer- a reference is just a concept that allows the programmer to make aliases of something else. A pointer is a place in memory that has the address of something else, but a reference is NOT.
Now the last point might not be crystal clear, if you insist on dealing with references as pointers. e.g.:
int x;
int& rx = x; // from now on, rx is just like x.
// Unlike pointers, refs are not real objects in memory.
int* p = &x; // Ok
int* pr = ℞ // OK! but remember that rx is just x!
// i.e. rx is not something that exists alone, it has to refer to something else.
if( p == pr ) // true!
{ ... }
As you can see from the above code, when we use the reference, we are not dealing with something separated from what it refers to. So, the address of a reference is just the address of what it refers to. Thats why there is no such thing called the address of the reference in terms of what you are talking about.
|
1,898,729 | 1,898,979 | Common algorithm for std::list and std::map? | I have a class of interest (call it X).
I have a std::list<X*> (call it L).
I have a function (call it F).
F(L) returns a subset of L (a std::list<X*>) according to an algorithm that examines the internal state of each X in the list.
I'm adding to my application a std::map<int,X*> (call it M), and I need to define F(M) to operate in the same fashion as F(L) - that is to say, F(M) must return a std::list<X*> as well, determined by examining the internal state of each X in the map.
Being a self-described lazy programmer, immediately I see that the algorithm is going to be [logically] the same and that each data type (the std::list and the std::map) are iterable templates. I don't want to maintain the same algorithm twice over, but I'm not sure how to move forward.
One approach would be to take the X*'s from F(M) (that is, the 'values' from the key-value map), throw them into a std::list<X*>, and punt the processing over to F(std::list<X*>), passing the return std::list<X*>; back through. I can't see how this would be the only way.
My question: How can I maintain the core algorithm in one place, but retain the ability to iterate over either a sequence or the values of a pair associative container?
Thanks!
| First, all but the condition for both can be done with std::remove_copy_if. Despite the name, remove_copy_if, doesn't remove anything from the original collection. I think people would understand it more easily if it was called something like filtered_copy. It copies elements from one collection to another. For each element, it calls a predicate, and the item gets copied if and only if the predicate returns false for that element.
That leaves you with only one responsibility: to implement the test function that looks at each X *, and says whether it should be left out of the copy you're making. Since you have one piece of logic you want to apply in two different ways, I'd encapsulate the logic in a private function of a class. The two ways it can then be supplied to the outside world as overloaded versions of operator() for the class:
class F {
bool do_test(X const *x) const { return x.internal_stuff; }
public:
bool operator()(X const *x) const { return do_test(x); }
bool operator()(std::pair<int, X const *> const &p) const {
return do_test(p.second);
}
};
Since operator()(X const *) is a pure thunk to do_test(), you might want to get rid of it, but IMO that would probably do more harm than good.
In any case, this leaves your logic entirely in one place (F::do_test). It also gives a simple, consistent syntax for creating a filtered copy of either a list<X *> or a std::map<int, X *>:
std::list<X *> result;
std::remove_copy_if(coll.begin(), coll.end(), std:back_inserter(result), F());
As a final note: std::list is probably the most over-used collection in existence. While it does have its uses, they're really quite rare. std::vector and std::deque are very frequently better.
|
1,898,837 | 1,898,849 | #include <FreeImage.h> not found | I have compiled FreeImage from source and installed it.
When I run sudo make install in installs the following files on my system
/usr/local/include/FreeImage.h
/usr/local/lib/libfreeimage-3.10.0.dylib
/usr/local/lib/libfreeimage.a
However in my C++ program it says error file not found when I do this:
#include <FreeImage.h>
I have tried adding this to my system path file:
sudo vi /etc/paths
#FreeImage
/usr/local/include
/usr/local/lib
But C++ still cannot find my #include inside Xcode or with gcc.
| You don't want those directories in your /etc/paths file. That files lists the directories where the shell searches for executables.
Try:
$ CFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" make
$ sudo make install
You might need to add /usr/local/lib to your DYLD_LIBRARY_PATH to make sure your executable runs:
$ export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH
(Assuming your DYLD_LIBRARY_PATH variable doesn't have /usr/local/lib, and that it's not empty to begin with. If it is empty, you should do export DYLD_LIBRARY_PATH=/usr/local/lib instead.)
Edit: OK, based on your comments, looks like this should work:
export CMAKE_INCLUDE_PATH=/usr/local/include
export CMAKE_LIBRARY_PATH=/usr/local/lib
See What to do if cmake doesn't find the package although it exists on the system? for more.
Since you're using a GUI version of Cmake, you should do this:
Open "property list editor", click "add child". For "New item", enter CMAKE_INCLUDE_PATH, for Type, leave it as "String", for Value, enter /usr/local/include. Then, click "add item" again, and enter CMAKE_LIBRARY_PATH for "New item", leave type as "String", and for "Value", enter /usr/local/lib. Then save (File -> Save as) to a file. I suggest filename a.plist in your Desktop folder. Then open a terminal (Appilcations -> Utilities -> Terminal) and type:
mv ~/Desktop/a.plist ~/.MacOSX/environment.plist
After that, quit Xcode and Cmake gui, and restart. That should work. See this for technical details, and this for more.
|
1,898,920 | 1,898,960 | How might I overload the "new" operator to allocate memory from a secondary memory device? | I am looking for a syntax to allocate memory from a secondary memory device and not from the default heap.
How can i implement it? Using malloc() would by default take it from heap... Surely there must be another way!
| #include <new>
void* operator new(std::size_t size) throw(std::bad_alloc) {
while (true) {
void* result = allocate_from_some_other_source(size);
if (result) return result;
std::new_handler nh = std::set_new_handler(0);
std::set_new_handler(nh); // put it back
// this is clumsy, I know, but there's no portable way to query the current
// new handler without replacing it
// you don't have to use new handlers if you don't want to
if (!nh) throw std::bad_alloc();
nh();
}
}
void operator delete(void* ptr) throw() {
if (ptr) { // if your deallocation function must not receive null pointers
// then you must check first
// checking first regardless always works correctly, if you're unsure
deallocate_from_some_other_source(ptr);
}
}
void* operator new[](std::size_t size) throw(std::bad_alloc) {
return operator new(size); // defer to non-array version
}
void operator delete[](void* ptr) throw() {
operator delete(ptr); // defer to non-array version
}
|
1,899,037 | 1,899,551 | Calling a member function using boost::lambda | I am learning the boost::lambda library and for that I wrote this sample code to convert an vector<A> into vector<int> by extracting the value from A object.
class A
{
public:
A(int n) : m_n(n){}
int get() const {return m_n;}
private:
int m_n;
};
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost::lambda;
std::vector<A> a1;
std::vector<int> a2;
a1.push_back(A(10));
a1.push_back(A(20));
std::for_each(a1.begin(), a1.end(), bind(&std::vector<int>::push_back, var(a2), bind(&A::get, _1)));
return 0;
}
I could get the for_each part to work after several tries. But I still don't look the like of it with those multiple binds. Is there any other way to write this. Preferably I would like to do something like: a2.push_back(bind(&A::get,_1));, but that doesn't compile.
| I don't think what you're trying to do is possible. for_each applies function to each element in the range, but you are trying to call two member functions and you'll have to bind them both. I think your code is the best you can do when using for_each. Lambda documentation looks very complete to me, but there is no example for what you're trying to do. I think it's for a reason, there is a more appropriate algorithm for this. As Kirill said it's transform.
std::transform(a1.begin(), a1.end(), std::back_inserter(a2), bind(&A::get, _1));
|
1,899,056 | 1,899,198 | Get pContext in Try/Catch handler? | When an exception happens, as you know, it passes pContext to the SEH. Is there anyways to access the pContext in a Try/Catch? I guess I could have the exception class grab it when being initiated but that would only work for that class and not for every exception.
| Hard to know what you're looking for...
THE Guide for SEH: http://www.microsoft.com/msj/0197/Exception/Exception.aspx
Have a look to that as well:
http://www.programmingunlimited.net/siteexec/content.cgi?page=mingw-seh
http://msdn.microsoft.com/en-us/library/swezty51(VS.80).aspx
Note: take care depending on the version of your compiler C++ exceptions and SEH exceptions might not be handle all together: http://www.thunderguy.com/semicolon/2002/08/15/visual-c-exception-handling/
|
1,899,091 | 1,899,255 | How to find memory leaks in source code | If it is known that an application leaks memory (when executed), what are the various ways to locate such memory leak bugs in the source code of the application.
I know of certain parsers/tools (which probably do static analysis of the code) which can be used here but are there any other ways/techniques to do that, specific to the language (C/C++)/platform?
| There's valgrind and probably other great tools out there.
But I'll tell you what I do, that works very well for me, given that many times I code in environments where you can't run valgrind:
Be sure to pair each allocation with a deallocation. I always count news or mallocs and search for the delete or free.
If in C++ and using exceptions, try to put them paired on constructors/destructors. If you like risk, or can't put them in Ctor/dtor, be sure no exception can make the program flow not to execute the deallocation.
Use of smart pointers and ptr containers.
One can monitor alloc/dealloc rewriting new or installing a malloc handler. At some point, if the code runs continuously it can be obvious if the memory usage becomes stationary and doesn't grow without bounds which would be the worst case of leak.
Be careful with containers that never shrink such as vectors. There are tricks to shrink them swapping them with an empty container.
|
1,899,105 | 1,899,135 | Difference in behavior when returning a local reference or pointer | #include <iostream.h>
using namespace std;
class A {
public:
virtual char* func()=0;
};
class B :public A {
public:
void show() {
char * a;
a = func();
cout << "The First Character of string is " << *a;
}
char * func();
};
char* B::func() {
cout << "In B" << endl;
char x[] = "String";
return x;
}
int main() {
B b;
b.show();
}
The problem in this is that I am returing a local varibale pointer/reference.
Currently it is char x[]="String", but when I use a pointer char *x="String", the result is "S" but when Array reference the output comes as (i)
| When you do something like:
char *f(){ return "static string"; }
You're returning the address of a string literal, but that string literal is not local to the function. Rather, it is statically allocated, so returning it gives well-defined results (i.e. the string continues to exist after the function exits, so it works).
When you (attempt to) return the address of an array of char like this:
char *f() {
char x[] = "automatically allocated space";
return x;
}
The compiler allocates space for x on the stack, then initializes it from a string literal to which you don't have direct access. What you're returning is the address of the memory in the stack, not the string literal itself -- so as soon as the function exits, that array ceases to exist, and you have no idea what else might be put at that address. Trying to use that address causes undefined behavior, which means anything can happen.
|
1,899,250 | 1,899,260 | Need Help for C++ Code Dissection at /*=NULL*/ | Could you tell me the meaning of /*=NULL*/ below?
CMyCla::CMyCla(CWnd* pParent /*=NULL*/)
: CDialog(CCycleTimes::IDD, pParent)
{
// Some code here
}
And btw, i copied the same line.
Commented successfully as the syte below
// CMyCla::CMyCla(CWnd* pParent /*=NULL*/)
// : CDialog(CCycleTimes::IDD, pParent)
Otherwise, commented failed as the style below.
/*
CMyCla::CMyCla(CWnd* pParent /*=NULL*/)
: CDialog(CCycleTimes::IDD, pParent)
*/
Why did the comment operation fail?
| Most likely in the class declaration the default value for that parameter is specified:
class CMyCla {
public:
CMyCla(CWnd* pParent =NULL);
};
now in the implementation of CMyCla::CMyCla() redefining the default value for the parameter is not allowed, but the author perhaps wanted to remind that there is the default value, so he commented it out.
When you do the following:
/*
CMyCla::CMyCla(CWnd* pParent /*=NULL*/)
: CDialog(CCycleTimes::IDD, pParent)
*/
the first closing comment (*/) end the commented section, so everything after it is now uncommented:
/*<CommentStart>
CMyCla::CMyCla(CWnd* pParent /*=NULL*/<CommentEnd>)<-this is not commented
: CDialog(CCycleTimes::IDD, pParent) <-neither is this
*/<-this closing comment can produce a compiler error
|
1,899,363 | 1,899,433 | Most efficient method to parse small, specific arguments | I have a command line application that needs to support arguments of the following brand:
all: return everything
search: return the first match to search
all*search: return everything matching search
X*search: return the first X matches to search
search#Y: return the Yth match to search
Where search can be either a single keyword or a space separated list of keywords, delimited by single quotes. Keywords are a sequence of one or more letters and digits - nothing else.
A few examples might be:
2*foo
bar#8
all*'foo bar'
This sounds just complex enough that flex/bison come to mind - but the application can expect to have to parse strings like this very frequently, and I feel like (because there's no counting involved) a fully-fledged parser would incur entirely too much overhead.
What would you recommend? A long series of string ops? A few beefy subpattern-capturing regular expressions? Is there actually a plausible argument for a "real" parser?
It might be useful to note that the syntax for this pseudo-grammar is not subject to change, so if the code turns out less-than-wonderfully-maintainable, I won't cry. This is all in C++, if that makes a difference.
Thanks!
| The answer mostly depends on a balance between how much coding you want to do and how much libraries you want to depend on - if your application can depend on other libraries, you can use any of the many regular expression libraries - e.g. POSIX regex which comes with all Linux/Unix flavors.
OR
If you just want those specific syntaxes, I would use the string tokenizer (strtok) - split on '*' and split on '#' - then handle each case.
|
1,899,373 | 1,899,390 | How do compilers know where to find #include <stdio.h>? | I am wondering how compilers on Mac OS X, Windows and Linux know where to find the C header files.
Specifically I am wondering how it knows where to find the #include with the <> brackets.
#include "/Users/Brock/Desktop/Myfile.h" // absolute reference
#include <stdio.h> // system relative reference?
I assume there is a text file on the system that it consults. How does it know where to look for the headers? Is it possible to modify this file, if so where does this file reside on the operating system?
| When the compiler is built, it knows about a few standard locations to look for header file. Some of them are independent of where the compiler is installed (such as /usr/include, /usr/local/include, etc.) and some of the are based on where the compiler is installed (which for gcc, is controlled by the --prefix option when running configure).
Locations like /usr/include are well known and 'knowledge' of that location is built into gcc. Locations like /usr/local/include is not considered completely standard and can be set when gcc is built with the --with-local-prefix option of configure.
That said, you can add new directories for where to search for include files using the compiler -I command line option. When trying to include a file, it will look in the directories specified with the -I flag before the directories I talked about in the first paragraph.
|
1,899,393 | 1,900,171 | Using boost::bind output as an array subscript | How do I get boost::bind to work with array subscripts? Here's what I'm trying to achieve. Please advice.
[servenail: C++Progs]$ g++ -v
Reading specs from /usr/lib/gcc/i386-redhat-linux/3.4.6/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr /share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=i386- redhat-linux
Thread model: posix
gcc version 3.4.6 20060404 (Red Hat 3.4.6-3)
[servenail: C++Progs]$ cat t-array_bind.cpp
#include <map>
#include <string>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <iostream>
using namespace std;
using namespace boost;
using namespace boost::lambda;
class X
{
public:
X(int x0) : m_x(x0)
{
}
void f()
{
cout << "Inside function f(): object state = " << m_x << "\n";
}
private:
int m_x;
};
int main()
{
X x1(10);
X x2(20);
X* array[2] = {&x1, &x2};
map<int,int> m;
m.insert(make_pair(1, 0));
m.insert(make_pair(2, 1));
for_each(m.begin(),
m.end(),
array[bind(&map<int,int>::value_type::second, _1)]->f());
}
[servenail: C++Progs]$ g++ -o t-array_bind t-array_bind.cpp
t-array_bind.cpp: In function `int main()':
t-array_bind.cpp:40: error: no match for 'operator[]' in
'array[boost::lambda::bind(const
Arg1&, const Arg2&) [with Arg1 = int
std::pair::*, Arg2 =
boost::lambda::lambda_functor >](((const boost::lambda::lambda_functor >&)(+boost::lambda::::_1)))]'
Thanks a lot.
| As Charles has explained, boost::bind returns a function object and not an integer. The function object will be evaluated for each member. A little helper struct will solve the problem:
struct get_nth {
template<class T, size_t N>
T& operator()( T (&a)[N], int nIndex ) const {
assert(0<=nIndex && nIndex<N);
return a[nIndex];
}
}
for_each(m.begin(),
m.end(),
boost::bind(
&X::f,
boost::bind(
get_nth(),
array,
bind(&map<int,int>::value_type::second, _1)
)
));
Edit: I've changed the functor to return the nth element of the array.
|
1,899,564 | 1,899,623 | a C++ hash map that preserves the order of insertion | I have the following code:
#include <iostream>
#include "boost/unordered_map.hpp"
using namespace std;
using namespace boost;
int main()
{
typedef unordered_map<int, int> Map;
typedef Map::const_iterator It;
Map m;
m[11] = 0;
m[0] = 1;
m[21] = 2;
for (It it (m.begin()); it!=m.end(); ++it)
cout << it->first << " " << it->second << endl;
return 0;
}
However, I am looking for something that preserves the order so that later I can iterate over the elements in the same order in which they were inserted. On my computer the above code does not preserve the order, and prints the following:
0 1
11 0
21 2
I thought maybe I could use a boost::multi_index_container
typedef multi_index_container<
int,
indexed_by<
hashed_unique<identity<int> >,
sequenced<>
>
> Map;
Can somebody show me how to implement my original code using this container (or any other appropriate container) so that the iterator follows the order of insertion?
| #include <iostream>
#include "boost/unordered_map.hpp"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
using namespace std;
using namespace boost;
using namespace boost::multi_index;
struct key_seq{};
struct key{};
struct Data_t
{
int key_;
int data_;
Data_t (int key_v, int data_v) : key_(key_v), data_(data_v) {}
};
int main()
{
typedef multi_index_container<
Data_t,
indexed_by<
hashed_unique<tag<key>, BOOST_MULTI_INDEX_MEMBER(Data_t,int,key_)>,
sequenced<tag<key_seq> >
>
> Map;
typedef Map::const_iterator It;
typedef index<Map,key>::type Map_hashed_by_key_index_t;
typedef index<Map,key>::type::const_iterator Map_hashed_by_key_iterator_t;
typedef index<Map,key_seq>::type Map_sequenced_by_key_index_t;
typedef index<Map,key_seq>::type::const_iterator Map_sequenced_by_key_iterator_t;
Map m;
m.insert(Data_t(11,0));
m.insert(Data_t(0,1));
m.insert(Data_t(21,1));
{
cout << "Hashed values\n";
Map_hashed_by_key_iterator_t i = get<key>(m).begin();
Map_hashed_by_key_iterator_t end = get<key>(m).end();
for (;i != end; ++i) {
cout << (*i).key_ << " " << (*i).data_ << endl;
}
}
{
cout << "Sequenced values\n";
Map_sequenced_by_key_iterator_t i = get<key_seq>(m).begin();
Map_sequenced_by_key_iterator_t end = get<key_seq>(m).end();
for (;i != end; ++i) {
cout << (*i).key_ << " " << (*i).data_ << endl;
}
}
return 0;
}
|
1,900,010 | 1,900,021 | Default argument in a function [C++] | I tried to do something like this:
int& g(int& number = 0)
{
//maybe do something with number
return number;
}
but it doesn't work. It has to be passed by reference.
Thank you for any help.
P.S.
I think that "Related Questions" appearing once you type Title is a good idea, but I also think that they should be displayed only if they are related to specific language, i.e. it is less than useless for me to looking at topic with similar problem but in Ruby.
| If you really want to do this:
make the reference const, so that a temporary can be bound to it
put the default in the function declaration, not the definition
For example:
// header
const int & g( const int & number = 0 );
// implementation
const int & g( const int & number )
{
//maybe do something with number
return number;
}
PS Post your complaints about how SO works on Meta, not here (for all the good it will do - answering this question indicated they STILL haven't fixed the code-after-list bug)
|
1,900,160 | 1,900,313 | Losing whitespace around escaped symbols in CDATA using Expat XML parser in C++ | I'm using XML to send project information between applications. One of the pieces of information is the project description. So I have:
<ProjectDescription>Test & spaces around&some & amps!</ProjectDescription>
Or: "Test & spaces around&some & amps!" <-- GOOD!
When I then use Expat to parse it, my data handler gets just parts of the entire string at a time.
"Test", then "&", then "spaces around", the next "&", etc, etc. When I then try to reconstruct the original string, all the spacing around the &'s is dropped because the data handler never gets to see them. When I then re-write the XML I get:
<ProjectDescription>Test&spaces around&some&amps!</ProjectDescription>
Or: "Test&spaces around&some&s!" <-- BAD!
Is this a known problem with existing workarounds?
Is there some setting I can give Expat to control its behavior around escaped symbols?
My attempts at Googling an answer have met with dismal failure.
EDIT: In response to a question in the comments:
I have my own handler, which I register with the parser:
parser=XML_ParserCreate(NULL);
XML_SetUserData(parser,&depth);
XML_SetElementHandler(parser,startElement,endElement);
XML_SetCharacterDataHandler(parser,dataHandler);
The handler is declared as follows:
static void dataHandler(void *userData,const XML_Char *s,int l)
And then "s" contains the data in the element. Without any & stuff, it's the entire string between the open and close tags, in the case of "a string with spaces".
| I have just run a test with my own library that uses expat. My handler looks like this, with debug statements to display what is going on:
void CharDataHandler( void * parser,
const XML_Char *s,
int len ) {
std::cerr << "[" << s << "]\n";
std::cerr << len << "\n";
// my own processing here - not important
}
I don't see the behaviour you are talking about. For the input data:
XXX & YYY
I get three events with the char * and length data set as folows:
char * = "XXX & YYY"
length = 4
char * = "&"
length = 1
char * = " YYY"
length = 4
So the spaces are retained. As far as I know I am not using any specal settings. What version & platform of Expat are you using?
|
1,900,665 | 1,900,672 | C++ compiler differences ( VS2008 and g++) | I tried compiling the following code in Linux and VS 2008:
#include <iostream> // this line has a ".h" string attached to the iostream string in the linux version of the code
using namespace std; // this line is commented in the linux version of the code
void main()
{
int a=100;
char arr[a];
arr[0]='a';
cout<<"array is:"<<arr[0];
}
This line works in the g++ version but does not work in the Visual Studio.
It throws the following error:
1>c:\users\bibin\documents\visual studio 2008\projects\add\add\hello.cpp(7) : error C2057: expected constant expression
1>c:\users\bibin\documents\visual studio 2008\projects\add\add\hello.cpp(7) : error C2466: cannot allocate an array of constant size 0
1>c:\users\bibin\documents\visual studio 2008\projects\add\add\hello.cpp(7) : error C2133: 'arr' : unknown size
Is this a valid statement ?? How can two compilers have different interpretation of the same langauge
| This is a C99 feature:
char arr[a]; // VLA: Variable Length Arrays (C99) but not C++!
GCC supports many features from C99, but VC doesn't and I think it won't in the near future because they are concentrating on C++ more and more. Anyway, you could just change the declaration to:
const int a=100; // OK the size is const now!
char arr[a];
|
1,900,756 | 1,901,498 | How do you convert from a nsACString to a LPCWSTR? | I'm making a firefox extension (nsACString is from mozilla) but LoadLibrary expects a LPCWSTR. I googled a few options but nothing worked. Sort of out of my depth with strings so any references would also be appreciated.
| It depends whether your nsACString (which I'll call str) holds ASCII or UTF-8 data:
ASCII
std::vector<WCHAR> wide(str.Length()+1);
std::copy(str.beginReading(), str.endReading(), wide.begin());
// I don't know whether nsACString has a terminating NUL, best to be sure
wide[str.Length()] = 0;
LPCWSTR newstr = &wide[0];
UTF-8
// get length, including nul terminator
int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
str.BeginReading(), str.Length(), 0, 0);
if (len == 0) panic(); // happens if input data is invalid UTF-8
// allocate enough space
std::vector<WCHAR> wide(len);
// convert string
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
str.BeginReading(), str.Length(), &wide[0], len)
LPCWSTR newstr = &wide[0];
This allocates only as much space as is needed - if you want faster code that potentially uses more memory than necessary, you can replace the first two lines with:
int len = str.Length() + 1;
This works because a conversion from UTF-8 to WCHAR never results in more characters than there were bytes of input.
|
1,900,802 | 1,900,815 | Where does the C++ compiler start? | If you have a c++ project with several source files and you hit compile, which file does the compiler start with?
I am asking cause I am having some #include-dependency issues on a library.
Compiler would be: VC2003.
| It should not be order-dependent. The only relevant steps are:
Each compilation unit includes what it depends on, and should be compilable individually. This means, first, that each CPP file includes all the headers it depends on; and second, that each header should in turn include what it needs so that it can compile even if it is the first one to be compiled.
A link step puts all the compiled object code together and builds the final binary.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.