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 |
|---|---|---|---|---|
7,144,392 | 7,145,883 | Pitfalls on using MFC Synchronization Objects | I have employed MFC Synchronization objects in my projects without any issues. But recently I came across an article, which explains MFC synchronization is completely wrong. I'm not sure which version of MFC he's talking about but I seriously believe that MFC has matured in the recent versions. I'm using MFC library wh... | On mutex timeouts, there is a school of design for concurrent software that says you should not use timeouts for normal operation. Your design would then involve mutexes or other locks that do not time out ever, and timeout is effectively a mechanism for dealing with deadlocks: you try to design your system not to exhi... |
7,144,414 | 7,144,464 | c++ this pointer question | here is the thing, I want to (probably not the best thing to do) have the ability to call some class constructor that receives as a parameter a pointer to the class who's calling (ufff!!!). Well in code looks better, here it goes, as I do it in C#.
public class SomeClass
{
SomeOtherClass someOtherClass;
//Constr... |
probably not the best thing to do
It might not be a bad idea. However, every time you use pointers in C++, you must be completely clear about how it will be used: what kind of thing is being pointed to (not just the type of the pointer, but scalar vs. array, etc.), how the pointed-at thing gets there (e.g. via new? A... |
7,144,532 | 7,144,765 | Run userscript within the IE web browser control in a MFC application | I am developing a C++ application using the Internet Explorer webcontrol. I would like to use some userscripts to modify the webpage.
Do you have ideas how I can achieve this?
| You're looking for IHTMLWindow2::execScript().
|
7,144,931 | 7,149,075 | Audio Input Programming | What im playing around with is out of the scope of the usual programming I do so I thought I would ask before I waste more time.
So basically I have a button (usually found on a computers ON/OFF switch) and using my not-so vast knowledge of electronics I have connected it to a standard audio cable (which is of course c... | I ended up figuring this one out for myself. Basically its as easy as listening to the input line then running a method if the amplitude of the audio gets gets to a certain amount. Through testing I also found that the amplitude is measured in negative numbers when the button is clicked down and a positive amplitude is... |
7,144,982 | 7,145,047 | implementation of size in standard containers | This is a purely theoretical question, I know that the standard containers interface are not likely to change now...
I read recently one of Herb Sutter "guru of the week" where he complained about the fact that empty() was implemented as a member function in std::string. I did not agree with all the arguments, because ... | The standard doesn't specify exactly how anything in the library is implemented. It merely specifies the meaning of something. So if empty() is true, then size() must also be 0. That doesn't mean that empty() must actually call std::basic_string::size() and compare it to 0. The spec is simply saying that if empty() ret... |
7,145,168 | 7,145,976 | Coping with several Windows SDK versions on build server | We have a TeamCity build server with a couple of agents set up to build code on check in for several c++ projects. Now, we've run into some problems regarding handling dependencies on Windows SDK since
It's to large to check-in and still be able to work with the source
smoothly.
Several can't be installed at the same ... | If you make sure the versions of the SDK are installed in the same location on each machine that you use (both developer and build machine) then you can add a step to the start of your build scripts which sets the current SDK for use. You can do this either:
Using the registry settings (if you have only one build goin... |
7,145,494 | 7,146,618 | dynamic int * arrays as key for C++ map | I have some dynamic int * arrays that I would like to use as keys for an unordered_map. I'm a bit unclear on how I should declare the key type so it would actually be the value of the entire array.
Also, to deallocate the memory for the arrays, do I use map.clear()?
Example:
unordered_map<??, int> frequency;
while (... | You won't be able to stick int* as key inside a std::map and still be able to retrieve elements 'by value'. The reason for that is a single int* only provides the start of an array, you need the end too to compute anything (equivalently and more C-like, the length). In other words, int* does not an array (dynamic or ot... |
7,145,583 | 7,145,759 | Two point crossover operation | I've been trying to write a code for two point crossover operation in a genetic algorithm. At first two random gene location is selected. After that, two chromosomes swap their genes which are located btw random numbers called genelocation1 and genelocatıon2.
for example First Gene [0.3,0.2,0.4,0,0.1,0.5,0.7]
... | You can't define an array of variable size on the stack.
You could use
int *Temp1=new int[size]
You then must not forget to call
delete[] Temp1;
at the end of your function!
edit:
I didn't test my code below, but the following should do what you want in a more efficient (and more understandable) way:
#include <algori... |
7,145,608 | 7,145,661 | How to trace MFC Serialize calls with Macros | I got a MFC app that is writing a huge hierarichy of objects to disk.
To make sense of what is being written I thought of logging all the calls to archive << via stream insertion and .write method by replacing those with macros
#pragma once
#ifndef LOGMAGIC
#define LOGMAGIC
class LogTab
{
public:
s... | You have to define LogTab::LogIndentCount in any one of the .cpp files as,
#include"LogTab.h"
//...
int LogTab::LogIndentCount = 0;
[As a side note, if it's a multi threaded system which is using this class then you may think of making LogIndentCount synchronized (thread safe)]
|
7,145,914 | 7,145,952 | destructor works before . How? | #include<iostream>
using namespace std;
class test
{
int a;
public:
test()
{
a=0;
}
test operator ++(int)
{ a++;
return *this;
}
void display()
{
cout<<a;
}
~test() {
cout << "DES" << endl;
}
};
int main()
{
test t,t1;
t1 = t++;
t.display();
system("pause");
}
The output that ... | When you are using t++ a temporary object is created. This is the reason you have 3 destructors called for 2 variables. If you use ++t, temporary object would not be created. Which, other than the operator precedence, is the main difference between pre- and post- incrementing.
|
7,145,925 | 7,487,965 | Reason for a floating point exception? | This is part of a macro I am writing in the ROOT framework using C++ and some predefined classes. I get a floating point exception upon including the lines marked below (starting with minv = ...). What is the reason for this error?
Double_t ppx[3000],ppy[3000],ppz[3000],pE[3000];
Double_t m = 0.000511;
Double_t minv,ep... | In the first loop over all tracks, you only fill the arrays if the track charge is positive. In the second loop, you access the arrays no matter whether the charge of the k-th track is positive.
If you want to fill minv (I guess the invariant mass) only for opposite-charged tracks, remove the first if that checks for a... |
7,146,191 | 7,324,156 | EvtSubscribe Pull Vs Push Model | I am trying to use following api from windows.
EVT_HANDLE WINAPI EvtSubscribe(
__in EVT_HANDLE Session,
__in HANDLE SignalEvent,
__in LPCWSTR ChannelPath,
__in LPCWSTR Query,
__in EVT_HANDLE Bookmark,
__in PVOID context,
__in EVT_SUBSCRIBE_CALLBACK Callback,
__in DWORD Flags
);
This api support... | Callback function is called from another thread, so you may have to synchronize, and if you have to synchronize it will be easier with the pull model... And if synchronize it will be easier to close the subscription with Event, as you may wait on two event, the one from EvtSubscribe and the one to close...
I waste some... |
7,146,297 | 7,146,330 | Initializing a vector of a struct in a struct | I know how to get a struct in a struct working but what I can't get to work is vector of a struct in a struct.
Creating a vector of a struct on a normal basis works for example with:
vector<struct> str1(100);
but how do I do that if I have the following code:
struct attribures {
string name;
bool value;
};
st... | Perhaps add a constructor to attributes:
struct attributes{
attributes(const string& name, bool value) : name(name), value(value) {}
string name;
bool value;
};
and then:
object.attrib.push_back(attributes("foo", true));
|
7,146,484 | 7,146,541 | Compile error when trying to register observer to template subject class | I am trying to implement an observer pattern with a template subject class. The observers don't (need to) know the subjects type, so I made an interface for the attach method without this type. This is my implementation:
SubjectInterface.h
#ifndef SUBJECTINTERFACE_H_
#define SUBJECTINTERFACE_H_
#include <list>
#include... | You have a circular include chain, SubjectInterface.h includes Observer.h which in turns includes SubjectInterface.h.
This means that the include guards will prevent Observer from being visible. To fix it instead forward declare Observer.
// SubjectInterface.h
#ifndef SUBJECTINTERFACE_H_
#define SUBJECTINTERFACE_H_
#in... |
7,146,589 | 7,146,692 | Win32 application (VS2010) runs much slow then a console in Eclipse (c++) | I have a project which I created in Eclipse c++. The project invokes a function that does a lot of loops (Thousands) to calculate the result.
When I run it in Eclipse it takes 1 minute (~70 seconds).
I wanted to add a GUI to the project so I opened a WinForm (Win32) project in VisualStudio2010 and moved all files of th... | Basically you answered your own question:
I think the problem is in the compilation in VS2010. I tried to change
some Optimizations properties, but the project couldn't be compiled...
however, it's hard to answer it, since there is a lot of optimization options in both of compilers, it's hard to tell what option ma... |
7,146,719 | 7,146,743 | identifier "string" undefined? | I am receiving the error: identifier "string" undefined.
However, I am including string.h and in my main file, everything is working fine.
CODE:
#pragma once
#include <iostream>
#include <time.h>
#include <string.h>
class difficulty
{
private:
int lives;
string level;
public:
difficulty(void);
~difficu... | <string.h> is the old C header. C++ provides <string>, and then it should be referred to as std::string.
|
7,146,786 | 7,226,710 | Copying a boost::property_map into a boost::vector_property_map | When calling boost::get on a graph, the return type is boost::associative_property_map<Graph, PropertyType>. I'd like to get a copy of this map, and I'd like to store it in a boost::vector_property_map. However, they are not compatible enough to allow simply assigning to the vector map. Looking at the source of propert... | I am sorry, but simply using boost::associative_property_map, you won't be able to retrieve iterators over contained items. You must use an alternate way to iterate over them -- iterate over edges or vertices, i guess, and put them into a boost::vector_property_map.
But if you have to do that, it means you are deconstr... |
7,146,813 | 7,147,021 | When is an integer<->pointer cast actually correct? | The common folklore says that:
The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the majority of cases, may indicate a design error and should be avoided.
Even when such a cast is performed, no assumptions shall be made about the size of integers an... | I sometimes cast pointers to integers when they somehow need to be part of a hashsum. Also I cast them to integers to do some bitfiddling with them on certain implemetnations where it is guaranteed that pointers always have one or two spare bits left, where I can encode AVL or RB Tree information in the left/right poin... |
7,146,827 | 7,417,893 | Magick++ - JPEG compressed TIFF | I have a problem creating a TIFF image with a JPEG compression using Magick++, the C++ API of ImageMagick. When I use the convert tool the following way, it works:
convert 1.jpg -compress JPEG 1.tiff
When I want to do the same in C++, it looks like this:
Image img("1.jpg");
img.compressType(JPEGCompression);
img.write... | According to ImageMagick Image Formats you need the jpegsrc.v8c.tar.gz for jpeg suppport. You have to link with libjpeg and libtiff to get it working. You can create all necessary linker flags using this command:
Magick++-config --cppflags --cxxflags --ldflags --libs
For me the following code is working:
#include <Mag... |
7,146,890 | 7,146,922 | How can an object know if it has been allocated on the stack or the heap? |
Possible Duplicate:
How can I tell if an object is statically or dynamically allocated on the constructor?
struct Foo {
Foo ();
};
int main ()
{
Foo foo; // Case A
Foo * p_foo = new Foo (); // Case B
}
Foo :: Foo ()
{
if (allocated_on_stack) {
// Case A
}
if (allo... | The short answer to the question is no.
There are theoretical solutions, for instance you could replace new (on class or global level) and keep track of all new allocated pointers and compare to this list to your this pointer in the constructor.
struct Foo {
Foo ()
{
//Check if `this` is in s_instances
... |
7,147,008 | 7,147,037 | The usage of anonymous enums | What is the purpose of anonymous enum declarations such as:
enum { color = 1 };
Why not just declare int color = 1?
| Enums don't take up any space and are immutable.
If you used const int color = 1; then you would solve the mutability issue but if someone took the address of color (const int* p = &color;) then space for it would have to be allocated. This may not be a big deal but unless you explicitly want people to be able to take... |
7,147,343 | 7,147,403 | Initialize a iterator with a pointer in C++ | I am having problems building a library in VC9, but which was previously successfully built in VC6.
Here is a part of the code:
size_t pos2find;
pos2find = J;
std::vector<size_t>::iterator it(&pos2find);
And here is the error:
error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_it... | An iterator into a vector isn't guarantied to be a raw pointer. In VS6 vector<T>::iterator happened to be a T* so you could initialize the iterator with a T*.
In later versions of VS the implementation of vector<T>::iterator changed to be a class type (as it's entitled to be) so code that made bad assumptions now fail... |
7,147,347 | 7,148,428 | g++ function matching and OpenCV 2.3.0 | Trying to compile the following OpenCV code:
#include <opencv/cv.h>
int main(int argc,char *argv[])
{
cv::Range img_rowrange, img_colrange, patch_rowrange, patch_colrange;
img_rowrange.start=3;
img_rowrange.end=6;
img_colrange.start=2;
img_colrange.end=5;
patch_rowrange.start=0;
patch_rowrange.end=3... | On the offending line, the statement img(img_rowrange,img_colrange) creates a new cv::Mat. The compiler does not let you do it while passing it as argument because as you are not assigning it to a variable, you will never be able to retrieve the data.
So try to do something like this:
cv::Mat img_dst = img(img_rowrange... |
7,147,456 | 7,148,535 | IntelliSense: a value of type "IDeviceServer *" cannot be assigned to an entity of type "IDeviceServer *" | I can't understand this error, really. Please help me with it. The code is :
m_pIServer = new IDeviceServer(this);
and declarations is :
class IDeviceServer : public IOPCServer
{
public:
IDeviceServer( LPUNKNOWN );
...
IDeviceServer *m_pIServer;
What means : a value of type "IDeviceServer *" cannot be ... | Usually occurs when you have redefined the class in a generic class/method and pass in an object of the old class.
|
7,147,457 | 7,147,504 | Cant create std::string from one of two sources with same types | Why last line doesnt work?
ostringstream stream;
int f = 12345;
stream << f;
string st = stream.str();
cout << typeid(st.rbegin()).name() << endl;
cout << typeid(stream.str().rbegin()).name() << endl;
cout << string(st.rbegin(), st.rend()) << std::endl;
cout << string(stream.str().rbegin(), stream.str().rend()) << endl... | Calling the ostringstream::str() method creates a new string object, therefore you're using iterators from two different objects.
To solve the issue, store the string in a temporary variable:
string temp = stream.str();
cout << string(temp.rbegin(), temp.rend()) << endl;
Which is what you were doing with the st variab... |
7,147,584 | 8,245,123 | Boost serialization: How does pointer tracking work? | How does pointer tracking work in boost serialization? I am using it to serialize messages between system components, and I have the impression that I get a lot of incorrectly shared objects. Is it possible that if I use shared pointers to the objects I want to serialize and a new object happens to have the same addres... | Short answer: yes, this happens.
The reason is (as one can conclude from the other answers and comments) that this is a slight abuse of what the serialization library is meant to do. Thus, if one uses boost serialization to log objects over the course of a day (e.g. not all objects are in memory at the start of the ser... |
7,148,036 | 7,148,151 | What is LD_LIBRARY_PATH and how to use it? | I take part in developing a Java project, which uses some C++ components, thus I need Jacob.dll. (on Windows 7)
I keep getting java.lang.UnsatisfiedLinkError: no JacobDB in java.library.path no matter where I put Jacob.dll....
I looked for possible decisions and the one that I haven't tried so far is setting the LD_LIB... | Typically you must set java.library.path on the JVM's command line:
java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass
|
7,148,127 | 7,148,544 | What happens if I imbue basic_stream<char> with locale with codecvt_utf16<char> facet? | Is it specified what will happen if I imbue basic_stream<char> with locale with codecvt_utf16<char> facet?
Basically, I use typedef wchar_t tchar; and typedef char tchar; to alter interfaces for (what I call) Unicode and non-Unicode builds of my library. I want to make the source simpler by always imbuing my file strea... | Per C++0x, codecvt_utf*<> can be instantiated with wide characters only. What happens if you use char is not specified, the only way to know is to try.
Bear in mind that codecvt_utf16 converts to/from external UTF-16 representation. That is, your file is supposed to be encoded in UTF-16. You might want to consider usin... |
7,148,220 | 7,149,112 | Mongoose statically linking with libssl? | I want to compile moongose with static library of libssl .
I have given .a file with -L option.
But still it is loading .so file.
why ?
how can I force it to use static lib ?
| Run compilation under strace, to look where .a file is being searched and why .so is loaded instead.
EDIT
By default moongose loads SSL dynamically. To change this compile it with NO_SSL_DL macro. Add -DNO_SSL_DL to compilation command line. See this link.
|
7,148,259 | 7,148,301 | Unable to start program ATL Project C++ | I am trying to create a BHO with the ATL Project in Visual Studio 2010. I have been following this article:
http://msdn.microsoft.com/en-us/library/bb250489(v=vs.85).aspx
The project builds successfully however I get an error popup with an ambiguous "Unable to start program 'C:\ .... MyProject.dll'"
My BHO just has the... | You cannot run Dll directly. Set "Executable for Debug Session" as described in the article:
"Start the debugger by pressing F5. When the Executable for Debug Session dialog box appears, select the "Default Web Browser" and click OK. If Internet Explorer is not your default browser, you can browse for the executable. "... |
7,148,341 | 7,159,302 | Weird crash when debugging COM object destructor | My application is a mix of C# and C++ code. Startup module written in C# loads during initialization phase C++ module through COM (Component Object Model) mechanism. All was functioning correctly until I decided to add to C# part a wcf service. All wcf service calls are routed to C++ code using COM. After adding some n... | Resolved by following code:
public void Dispose()
{
Marshal.Release(internal_interface_ptr);
internal_interface_ptr = IntPtr.Zero;
Marshal.ReleaseComObject(internal_interface);
Marshal.ReleaseComObject(internal_interface);
internal_interface = null;
}
Beside this one other reference was hanging in... |
7,148,503 | 7,148,542 | How do I create a custom animation in windows using the windows api? | I am using C++, on windows using only the windows api.
What I'm trying to create is a circle loading animation type of thing. Similar to the animation thats displayed on the left side of a tab, in IE when you try to load a page.
In fact I'm curious how programmers create animations like those at all.
If anyone could ex... | For something like that, you would typically create a series of icons, set a timer to cycle through them at the desired rate, then kill the timer when the animation was no longer needed.
|
7,148,624 | 7,148,715 | c++ hash function for an int array | I need to specialize the hash function for unordered_map so I can use int arrays as keys. The array values are usually 0 or 1, e.g. int array = {0, 1, 0, 1}, but technically not bounded.
Can someone recommend a good hash function in this case? Alternatively, I can always convert the int array into a string and avoi... | C++ TR1 contains a hash template function.
If you don't have that yet, you can use Boost Hash.
Idea for a handy helper:
#include <boost/functional/hash.hpp>
template <typename T, int N>
static std::size_t hasharray(const T (&arr)[N])
{
return boost::hash_range(arr, arr+N);
}
This would be (roughly?) equivale... |
7,148,877 | 7,148,915 | C++ type id at compile time | I want to generate a hash for a class based on its derived type at compile time. Today I generate it like:
template<class Type>
class TypeBase
{
public:
static const unsigned s_kID;
};
template<class Type>
const unsigned TypeBase<Type>::s_kID = hash(typeid(Type));
but this generates (pretty unnecessarily) run ti... | Given everything else that happens at process startup, and how simple and elegant your existing code is, assuming you don't hash a gazillion types, I'd leave your existing solution exactly as it is.
|
7,148,907 | 7,149,994 | Saving QPixmap as JPEG results in vertical lines | A user installed our application to a server PC, shared the install directory as network drive Z: and now opens the app from different client PCs all over his shop. Everything works fine except for a naggling bug on one of the PCs:
On the Problem PC, the app can load .jpg files for inventory items just fine and show th... | Here are a few things to try to isolate the problem:
Copy qjpeg4.dll to the client's working directory
Is the image corrupted when saving as PNG or GIF?
Convert your data to a QImage and work from that.
Consider the byte format (I usually use ARGB32 because it is int-aligned)
To test where the problem occurs, you migh... |
7,149,314 | 7,149,613 | How actually MPI_Waitall works | Does this example contradict the manual? The manual states that both the array of requests and the array of statuses must be of the same size. To be more precise, both arrays should be at least as long as it indicated by the count argument. Yet in the below example status array size is 2, not 4. Also, the example contr... | Yes, this example contradicts the manual. If you compare the example with the Fortran version, you'll see that the Fortran version is correct in that the status array is large enough (strangely enough, it's a 2D array but thanks to implicit interfaces and storage association it can be seen as a 1D array of size MPI_STA... |
7,149,483 | 7,150,334 | how to organize waiting for data from main thread in consumer thread | Main thread reads data from sockets and stores it in queue. Second thread write this data to disk file. But if second writes faster than first reads data, then how to organize waiting.
I wanna do it with semaphore, but how i can increase semaphore counter then next data chunk reads into queue. How to decreasde it in s... | Sounds like a 'classic' producer-consumer queue. You need a thread-safe queue and a semaphore, initialized to 0, to count objects in it. If you have no thread-safe queue, another semaphore initialized to 1, (or a mutex), will do to protect the queue from multiple access.
Essentially, in the producer, malloc a buffer ... |
7,149,771 | 8,452,776 | Mongodb c++ driver: string encoding | During working on one c++ project we decided to use MongoDB database for storing some data of our application. I have spent a week linking and compiling c++ driver, and its works now. But it is one trouble: strings like
bob.append("name", "some text with cyrilic symbols абвгд");
are added incorrectly and after extract... | Your example, and the example code in the C++ tutorial on mongodb.org work fine for me on Ubuntu 11.10. My locale is en_US.UTF-8, and I the source files I create are UTF-8.
MongoDB stores data in BSON, and BSON strings are UTF-8, and UTF-8 can handle any Unicode character (including Cyrillic). I think the C++ API assum... |
7,149,801 | 7,149,958 | map::const_iterator to map in c++ | I have a Map::const_iterator object in C++ and i am trying to abstract the entire map object from it without explicitly creating a map with Map::const_iterator->first and Map::const_iterator->second.
this doesn't seem to work : (*Map::const_iterator).as_map()
please advice.
| I'm afraid I understood the question totally wrong. How about using it->second?
typedef .... mymap_t;
typedef std::map<std::string, mymap_t> supermap_t;
supermap_t supermap;
for (supermap_t::const_iterator it = supermap.begin();
it != supermap.end();
++it)
{
const mymap& the_sub_map = i... |
7,149,922 | 7,149,954 | calling a global function with a class method with the same declaration | I would like to wrap a C library within a C++ class. For my C++ class I also would like to have the same declaration used by these C function: is it possible to do that?
If for example I have the case below how would it be possible to distinguish the C-function from the C++ one? I would like to call the C one off cours... | Use the scope resolution operator :::
int my_foo( int val ){
// Call the global function 'my_foo'
return ::my_foo(val);
}
|
7,150,097 | 7,150,182 | Is returning a C++ std::string object safe from memory leaks? | I'm fairly novice with C++'s strings so the following pattern may be a little fugly. I'm reviewing some code I've written before beginning integration testing with a larger system. What I'd like to know is if it is safe, or if it would be prone to leaking memory?
string somefunc( void ) {
string returnString;
... | Yes, returning a string this way (by value) is safe,albeit I would prefer assigning it this way:
string myString = somefunc();
This is easier to read, and is also more efficient (saving the construction of an empty string, which would then be overwritten by the next call to assign).
std::string manages its own memory,... |
7,150,395 | 7,152,246 | What does `std::kill_dependency` do, and why would I want to use it? | I've been reading about the new C++11 memory model and I've come upon the std::kill_dependency function (§29.3/14-15). I'm struggling to understand why I would ever want to use it.
I found an example in the N2664 proposal but it didn't help much.
It starts by showing code without std::kill_dependency. Here, the first l... | The purpose of memory_order_consume is to ensure the compiler does not do certain unfortunate optimizations that may break lockless algorithms. For example, consider this code:
int t;
volatile int a, b;
t = *x;
a = t;
b = t;
A conforming compiler may transform this into:
a = *x;
b = *x;
Thus, a may not equal b. It m... |
7,150,409 | 7,150,628 | libstdc++ GLIBCXX version errors | when I compile a c++ program in my computer using g++ and transfer the executable to run it on my university server, I get
./main: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.9' not found (required by ./main)
./main: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.14' not found (required by ./main)
./main: /usr/lib/li... | It seems you are using the standard library as a shared library (default behaviour) when linking your program at home.
So rather than really "linking" the library, your linker just resolves some symbols and does another operation, while delaying the actual loading of the library to run-time.
When you execute your progr... |
7,150,440 | 7,150,568 | Boost-asio listening to multiple IP Addresses on a single (TCP) acceptor | A boost TCP acceptor can be wired up by using an endpoint constructor that only takes a port number as it's argument, in which case it will listen to all IP addresses/NIC's.
Is it possible to get the acceptor to listen to select IP addresses ? Or will I have to create an acceptor for each IP address I am interested in ... | there's unbound listening and bound one. unbound means you listen to all NICs, bound - to specific one. There's no possibility to select some of NICs, I think because the same can be achived by dedicated acceptors for each of them
|
7,150,475 | 7,150,508 | container of unrelated T in c++ | If I have the following hypothetical class:
namespace System
{
template <class T>
class Container
{
public:
Container() { }
~Container() { }
}
}
If I instantiate two Containers with different T's, say:
Container<int> a;
Container<string> b;
I would like to create vector with pointe... | While it is possible to cast to void * and back, the problem is knowing which type you're popping. After all, you give the example:
Container<string> b = *reinterpret_cast<Container<string>*>(_collection.pop());
Container<int> a = *reinterpret_cast<Container<int>*>(_collection.pop());
However, if you were to accidenta... |
7,150,559 | 7,150,909 | How to fill combobox in a Visual Studio C++ Win32 project | How can I fill a combobox in a Visual Studio C++ Win32 project. And how can check that which word was selected by the user.
I mean I want a comboxbox for example filled with these: One, Two, Three. And I want to do different events depends on which one was chosen by the user.
Edit: The windows was created as a dialogbo... | In the WM_INITDIALOG handler for the dialog, you can initialize the combo box with the strings you wish to select with the CB_ADDSTRING message:
SendMessage(hCombo, CB_ADDSTRING, 0, (LPARAM) L"one");
Now you can respond to the CBN_SELENDOK message to respond to user changes to the dropdown.
|
7,150,687 | 7,150,710 | functor in header file | I have the following functor and I had included it in my main program
template<class T> struct Comp: public binary_function<T, T, int>
{
int operator()(const T& a, const T& b) const
{
return (a>b) ? 1: (a<b) ? -1 :0;
}
};
It wasn't giving any error when it was in the .cpp, but now when I moved it to my .h, it gi... | The original error is probably with binary_function: missing the include or not considering that it is in namespace std.
#include <functional>
and
std::binary_function<T, T, int>
|
7,150,982 | 7,151,041 | "Multiplicity of implementation" - how to deal with it? And what's the 'name' of such thing? | My question is a bit about programming techniques or, maybe, design patterns. Suppose several classes derived from base which contains a pure virtual method that should do some interactions beetwen them.
For instance, Rectangle, Ellipse, Triangle and Line - all derived from a Shape. And this abstract class, Shape, cont... | This is the school book example of double dispatch, the wikipedia article gives a good description of the problem and the solution:
http://en.wikipedia.org/wiki/Double_dispatch
If I remember correctly there's a very elegant solution to the problem in the book "Modern C++ Design" by Andrei Alexandescu
http://www.amazon.... |
7,151,298 | 7,151,432 | Why do I get these warnings in Visual C++ 2008 when building a struct? | I have this code
typedef struct
{
const char* fooString;
const bool fooBool;
}fooStruct;
And this initializer:
static const fooStruct foo[] =
{
{"file1", true},
{"file2", false},
....
};
With this code I have 3 warnings in VS2008:
error C2220: warning treated as error - no 'object' file generated... | The C4610 warning is incorrect. This is a known bug in Visual C++. See the Microsoft Connect bug "Improper issuance of C4610."
Adam Rosenfield explains why the other two warnings (C4510 and C4512) are emitted.
|
7,151,316 | 7,152,411 | Using objects of an app from shared object | I'm a little confused right now. Yesterday I had undefined symbols even if I used -rdynamic with g++. But now I don't have any error and that is even more disturbing.
To explain a bit my case, I want to do some sort of plugin like shared object. I haven't decided yet which is the best way to do.
A) My shared objects a... | #include "main.hpp"
#include <iostream>
class MyObject {
public:
MyObject(){
std::cout << "In two -> " << S::shared << "\n";
}
};
MyObject* t;
__attribute__((constructor))
void init_two()
{
t = new MyObject();
}
__attribute__((destructor))
void unin... |
7,151,383 | 7,151,434 | Is there a way to disable constructor synthesizing on a class? | Suppose I have a class that I want to make sure my compiler (GCC in this case) doesn't synthesize any constructors or assignment methods for. I've found one way to do this which is to just include a const int member in the class, but this doesn't rub me to well. Is there an attribute or something which signifies this.
| If you define (or only declare) it yourself, then the compiler will not define it for you.
struct A
{
A (); /*declaration is enough to prevent the compiler from
generating default constructor!*/
};
While the declaration is enough to prevent the compiler from generating default constructor, it is nec... |
7,151,672 | 7,151,836 | Best container to use for searching and sorting | I have a pure virtual class for storing log data. This class has two pieces of information: std::string id (unique) and int64_t time (duplicates allowed) with getId() and getTime() functions. As the log entries are created, they will go into a container and on application termination, the log messages are written to fi... | Since you're only going to need the entries sorted on time once, when the program exits, I think your proposed solution is good.
If you were going to need the entries sorted on both time and id several times boost::multi_index would be a good candidate.
|
7,151,692 | 7,151,741 | Qt 4.7 QRegExp Email Address Validation | I have a good regular expression pattern for validating email addresses. I've used it in php and I've used it in C#, not come across any problems (none yet). I am hwoever having considerable trouble migrating the pattern and using it with qt's QRegExp.
Can anyone help me?
// C# version
public bool isEmailAddress(stri... | C#'s raw string made it a bit easier to write but since you're dealing with C++, you need to escape the backslashes:
QString strPatt = "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b";
|
7,151,790 | 7,151,803 | Does C++ allow multiple levels of virtualness? | I have a base class called Object. PhysicsObject inherits from Object. Ball inherits from PhysicsObject, and SoftBall inherits from Ball. Something like this:
Object
|
PhysicsObject
|
Ball
|
SoftBall
I have a method called foo() that is declared virtual in Object (given an implementation, so not pure virtual), then... |
If I have an Object* that points to a SoftBall, will SoftBall's version of foo() be called? If not, is there any way to achieve this effect? Basically, does this aspect of polymorphism still work over more than one level of inheritance?
Yes
C++ defines methods as virtual if the corresponding overload is virtual in th... |
7,152,096 | 7,152,664 | C++ OStream Inheritance and Manipulators | I have a class that inherits from ostream but the manipulators fail to compile. For instance:
QLogger &logger = QLogger::getInstance();
logger << hex << 10 << endl;
Complains about logger << hex. If I cast logger to an ostream it will work but that is pretty ham-handed.
How can I extend my class so that it behaves as... | If you implement a member function, then inherited overloads of that same function aren't considered in overload resolution. If you change your custom operator<< overloads to be friend global functions rather than members, this should work fine. The cast forces the compile to choose operator<<() from those defined in o... |
7,152,120 | 7,172,898 | log4cxx config file syntax | I'm just discovering log4cxx logging framework.
It seems there are two different syntaxes for writing config file:
xml manner
key-value manner
Is there a difference or a best practice in this two approaches?
| In log4j, Ceki Gulcu (the author) suggests XML configuration over text file, and it takes precedence in default initialization, too (log4j.xml over log4j.txt). You can achieve slightly more with XML configuration than with the text file (I think you cannot manipulate logger additivity and set log4j debug mode with text... |
7,152,221 | 7,152,834 | stepping into msvcr100d.dll has stopped working after VS 2010 SP1 | It appears that I can no longer step into run time library calls. This used to work before SP1, now it only prints, e.g.:
'thread_test.exe': Loaded 'C:\Windows\SysWOW64\msvcp100d.dll', Symbols loaded (source information stripped).
'thread_test.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Symbols loaded (source inf... | Fixed as suggested by http://qualapps.blogspot.com/2007/04/symbols-for-mfc-source-code.html:
Add directory "C:\Windows\Symbols\dll" to the beginning of the symbols list.
Clear symbols cache directory.
|
7,152,250 | 7,154,481 | Fastest way to erase part of file in C++ | I wonder which is the fastest way to erase part of a file in c++.
I know the way of write a second file and skip the part you want. But i think is slow when you work with big files.
What about database system, how they remove records so fast?
| Database systems typically just mark deleted records as deleted, without physically recovering the unused space. They may later reuse the space occupied by deleted records. That's why they can delete parts of a database quickly.
The ability to quickly delete a portion of a file depends on the portion of the file you ... |
7,152,337 | 7,152,653 | Unhandled Exception when using libcurl | I just finished my struggle with libcurl and finally when everything compiled just great I got an error when sending an email. I copied the code from an example and just changed to my server port/login/password.
Here's the error screenshot:
!http://wstaw.org/m/2011/08/22/error.png
And here's the code I'm using: http:... | Your payload_source function is ignoring the size and nmemb parameters passed in.
curl prepares a small buffer for you to write data into - the size of this buffer is given by size * nmemb. You cannot insert any more than size * nmemb bytes; you have to wait for the next call. So if your strlen(data) turns out somethin... |
7,152,427 | 7,152,589 | How can I use std::copy to read directly from a file stream to a container? | I ran across a cool STL example that uses istream_iterators to copy from std input (cin) to a vector.
vector<string> col1;
copy(istream_iterator<string>(cin), istream_iterator<string>(),
back_inserter(col));
How would I do something similar to read from a file-stream directly into a container? Let's just say its ... | Replace cin with file stream object after opening the file successfully:
ifstream file("file.txt");
copy(istream_iterator<string>(file), istream_iterator<string>(),
back_inserter(col));
In fact, you can replace cin with any C++ standard input stream.
std::stringstream... |
7,152,548 | 7,152,806 | Formatted and unformatted input and output and streams | I had been reading a few articles on some sites about Formatted and Unformatted I/O, however i have my mind more messed up now.
I know this is a very basic question, but i would request anyone can give a link [ to some site or previously answered question on Stackoverflow ] which explains, the idea of streams in C and ... | Formatted IO means that your output is determined by a "format string", that means you provide a string with certain placeholders, and you additionally give arguments that should be used to fill these placeholders:
const char *daughter_name = "Lisa";
int daughter_age = 5;
printf("My daughter %s is %d years old\n", daug... |
7,152,896 | 7,152,923 | File Streams & Piping Data | I can write an app that would copy all input from cin into a container (let's say a set), and then print the container contents back to stdout. In the case of a set, they'd be sorted.
If I did that and compiled it as say, mysort, I could go into Unix and use the program as part of a pipe.
cat myfile.txt | mysort
and ... |
how would I handle the input to my analyzer program
(myanalyzer)?
By simply reading from stdin and writing to stdout you will make your program work with anything that pipes data into it / from it.
You just have to watch out for buffering when writing out.
EDIT
Given hugeprog is running and constantly producing da... |
7,152,984 | 7,153,093 | How to pass a dymamic array of strings pointers from C++ to a C function |
Possible Duplicate:
std::vector<std::string> to char* array
I have to call a c function that accepts an array of string pointers. Example
void cFunction(char* cities[], int count)
{
for(int i = 0; i < count; ++i )
{
printf("%s\n", cities[i]);
}
}
Assume that function is in some third party libabry; i... | There's going to be some awkwardness no matter how you slice it. If the C API truly requires modifiable arrays, then that's what you'll need to provide -- you'll have to copy your strings into. If it doesn't modify the strings, then you can use a std::vector of const char*, where the string data is still owned by the... |
7,153,171 | 7,153,260 | Reading a python UUID byte string in C++? | I have a string of 16 bytes in python created from the uuid.bytes method, something like:
'I\x9e|T\r\xad@\x80\x986m\x00\x1c\x07z0'
for example, that I am passing to a C++ file.
Is there a way for me to read that from the C++ side and reconstruct the UUID? I was going to read it into a 16-char array since a char = 1... | Something like this (untested)
char to_hex(int x)
{
return x < 10 ? x + '0' : (x - 10) + 'A';
}
char bytes[16];
...
std::string uuid;
for (int i = 0; i < 16; ++i)
{
uuid += to_hex((bytes[i] >> 4) & 0x0F);
uuid += to_hex(bytes[i] & 0x0F);
}
|
7,153,521 | 7,186,800 | Pass multi - dimensional array from managed code to unmanaged code | I would like to do the following:
Create three dimesinal array in c# code like this:
var myArray = new short[x,y,z];
UnanagedFunction(myArray);
Pass it to unmanaged code (c++) like this:
void UnmanagedFunction(short*** myArray)
{
short first = myArray[0][0][0];
}
UPDATED
When I try the following code I have run... | IntPtr Array3DToIntPtr(short[, ,] Val)
{
IntPtr ret = Marshal.AllocHGlobal((Val.GetLength(0) + Val.GetLength(1) + Val.GetLength(2)) * sizeof(short));
int offset = 0;
for (int i = 0; i < Val.GetLength(0); i++)
{
for (int j = 0; j < Val.GetLength(1... |
7,153,532 | 7,153,668 | C++ how to mix a map with a circular buffer? | I wonder is it possible to have a map that would work like boost circular buffer. Meaning it would have limited size and when it would get to its limited size it will start overwriting first inserted elements. Also I want to be capable to search thru such buffer and find or create with [name]. Is It possible to create ... | Well, I don't think that structure is present out of the box in boost (may exist elsewhere, though), so you should create it. I wouldn't recommend using operator[](), though, at least as it is implemented in std::map, because this may make difficult to track elements added to the map (for exapmle, using operator[]() wi... |
7,153,655 | 7,153,757 | C++ Stack datastructure. What's wrong with this piece of code? | so I'm currently trying to migrate my Java experience to C++ by implementing various Data Structures for the sake of having them implemented at least once.
Would you mind giving me some advise? The problem I am having is mainly concentrated around the pointers in push(int value) and especially pop(). As push seems to b... | For starters, you should be post incrementing the index on the array, so change:
elementsInArray++;
stackArray[elementsInArray] = aValue;
to:
stackArray[elementsInArray++] = aValue;
or:
stackArray[elementsInArray] = aValue;
elementsInArray++;
Second, when you create the new temp array you are doing it inside the if ... |
7,153,710 | 7,153,810 | Is this C++0x optimization legal? | Is it legal for a C++0x compiler to optimize
int func(int&& a){
a = 3;
return a;
}
to
int func(int&& a){
return 3;
}
?
(or for another POD)
| Not like that per se, because the function must modify the variable a to be equivalent. That said, after inlining and a bit of trivial optimization the result will be the same:
int x = func(5);
// pseudo-inlined:
int __temp = 5; // the temporary created by binding 5 to int&&
__temp = 3; // a = 3;
int x = __temp; // re... |
7,153,935 | 7,154,226 | How to convert UTF-8 std::string to UTF-16 std::wstring? | If I have a UTF-8 std::string how do I convert it to a UTF-16 std::wstring? Actually, I want to compare two Persian words.
| Here's some code. Only lightly tested and there's probably a few improvements. Call this function to convert a UTF-8 string to a UTF-16 wstring. If it thinks the input string is not UTF-8 then it will throw an exception, otherwise it returns the equivalent UTF-16 wstring.
std::wstring utf8_to_utf16(const std::string& u... |
7,154,323 | 7,154,381 | C++ transfer ownership of a struct to a function | Is it possible to transfer the ownership of a local variable in C++ (or C++0x) to a function, leaving it undefined after the return, so optimizations can be done?
struct A {
int a[100000];
};
int func(A& s){
//s should now be "owned" by func and be undefined in the calling function
s.a[2] += 4;
return ... | No, it's not possible, either Standard or through an extension, and that's because there is no optimization value. Compilers can trivially prove that there are no more references to local variables in such situations. Failing all else, you could trivially mimic the effect by doing
int main() {
{
A s;
... |
7,154,402 | 7,154,675 | How to select the autoconf build directory? | Is there a way to set where autoconf generates the object files. I would like to have autoconf create all object files in a src/build/ instead of src/
I've tried setting VPATH but that doesn't seem to do anything.
VPATH = build
| You do this by running configure from the directory where you want the object files. For instance, if configure and all your code is in a directory named src, then starting from that directory, these commands should do what you want:
$ mkdir build
$ cd build
$ ../configure
$ make
If you're not using Automake, you hav... |
7,154,425 | 7,154,488 | delete a variable out of scope | int* func()
{
int* i=new int[1];
//do something
return i;
}
void funcc()
{
int* tmp=func();
//delete allocated memory after use
delete tmp;
}
should delete working as described in the second function be a correct use ?
I think I didn't allocate memory to it by new ? new was used in the first, to be... | As others have stated, you should use delete[] to delete arrays, not delete.
But, if you're asking whether it's okay to delete tmp because the memory it points to wasn't allocated with new, then your premise is incorrect.
It was allocated with new. The address of the memory that you allocate within the function for i i... |
7,154,548 | 7,154,721 | Receiving multiple messages Winsock2 C++ | I am trying to make a program using Winsock2 where I can send a message from client to server. I can do this, but the problem is I can only send one message and then I have to restart the server to receive the next message. Here is the code for the server. The part I am really confused about is I have the recv() functi... | You did not show your client sending code, but offhand, your server reading code is not taking into account that sends and receives are NOT 1-to-1 in TCP/IP programming. If a client sends 2 messages, the server may receive both messages, or even portions of them, in the same read operation! You ae telling your server... |
7,154,574 | 7,155,431 | BitBlt performance with Aero enabled | I'd like to get more performance out of BitBlt for capturing the screen. When Aero remains enabled, capturing only a 400x400 pixel area of the screen reduces capture time from an average of 50ms (full 1920x1200) to about 33ms (for 400x400) on my machine. This is a disappointingly low improvement.
Is my only option dis... | A screen capture in Aero mode is very expensive because it requires synchronization with the DWM (think about waiting for everyone not blink their eyes to take a group photo), and locking the entire GPU pipe on Vista. On Windows 7 GDI performance is improved by accelerate common GDI operations and reduce GDI locking)
T... |
7,154,654 | 7,154,700 | Why doesn't Java have initializer lists like in C++? | In C++, you can use an initializer list to initialize the class's fields before the constructor begins running. For example:
Foo::Foo(string s, double d, int n) : name(s), weight(d), age(n) {
// Empty; already handled!
}
I am curious why Java does not have a similar feature. According to Core Java: Volume 1:
C+... | In C++, initializer lists are necessary because of a few language features that are either not present in Java or work differently in Java:
const: In C++, you can define a fields that are marked const that cannot be assigned to and must be initialized in the initializer list. Java does have final fields, but you can... |
7,154,728 | 7,155,096 | Is it possible to call functions from a C-library in php from a linux server? | Sorry this is a total newb question but there is this really great C-library available and I would like to call functions from it using php. However I have a linux server. Here are the specs:
Apache version 2.2.17
PHP version 5.2.17
MySQL version 5.1.56-community-log
Architecture x86_64
Operating sys... | With those specs. you basically have two options.
Create a wrapper library which acts as a PHP extension which enables you to call your C-functions directly from PHP, for example mylib_awesome_func('hello');
Create a command line utility which acts as an interface to your C library and then call this tool with exec() ... |
7,154,860 | 7,154,891 | Two-dimentional grid of objects that can extend in any direction C++ | What is the best method to create a two-dimensional grid of objects that can extend dynamically in any direction, without allocating memory in the empty parts of concave shapes?
I was thinking of having the class contain data members that pointed toward the adjacent objects (one for North, East, South, and West), but... | Just throwing an idea out here:
Take a key/value container, say std::map, or a self-balancing binary-search tree or similar.
Use a 64 bit integer as the key. Use the high 32 bits as an X coordinate, the low 32 bits as a Y coordinate. Thus to find point (x, y) you look up (((uint64_t)x) << 32) | y.
|
7,154,904 | 7,154,942 | Byte Count for a Struct not representing correct amount. | I am writing a bitmap loader and the byte count is not working correctly. I am currently using Xcode running a 64 bit unix executable.
The code:
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
typedef struct {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfRes... | This might be because of structure alignment. Here take a look http://peeterjoot.wordpress.com/2009/11/11/c-structure-alignment-padding/
You can force the compiler not to align the structure by adding the attribute __attribute__((__packed__)) but as far as I know it only works in gcc.
Here:
struct BITMAPFILEHEADER_S{
... |
7,155,330 | 7,155,351 | Is memory released when a destructor is called or when `delete` is called? | Assume you have an object of class Fool.
class Fool
{
int a,b,c;
double* array ;
//...
~Fool()
{
// destroys the array..
delete[] array ;
}
};
Fool *fool = new Fool() ;
Now, I know you shouldn't, but some fool calls the destructor on fool anyway. fool->~Fool();.
Does that mea... | If you write
fool->~Fool();
You end the object's lifetime, which invokes the destructor and reclaims the inner array array. The memory holding the object is not freed, however, which means that if you want to bring the object back to life using placement new:
new (fool) Fool;
you can do so.
According to the spec, ... |
7,155,652 | 7,155,673 | Where is type_info object stored? | I read from "Inside The C++ Object Model" that the type_info object is often stored at the first slot of the virtual table. However, I iterated the members in the virtual table:
class Base {
public:
virtual void f() { cout << "Base::f" << endl; }
virtual void g() { cout << "Base::g" << endl; }
virtual void ... | There is no cross-compiler way to get at the type_info from the address of an object. Nor would you expect there to be; the way to get a type_info is using a specific C++ keyword: typeid.
|
7,155,698 | 7,155,741 | Windows API: Undefined reference to DisconnectEx | I'm developing an application that uses windows sockets. My socket class has a method named Disconnect that uses DisconnectEx, but i get the following error at linking time:
undefined reference to `DisconnectEx@16'
I'm using MinGW and i'm linking my application with the following libs:
-lws2_32 -lwsock32 -lmswsock
On... | What you apparently missed is this note in the MSDN documentation for the DisconnectEx() function:
Note: The function pointer for the DisconnectEx function must be
obtained at run time by making a call to the WSAIoctl function with
the SIO_GET_EXTENSION_FUNCTION_POINTER opcode specified. The input
buffer passed ... |
7,155,991 | 7,156,014 | Pointer - returning Local reference in C++ | I'm not sure if this question has been asked before ( searched through SOF and couldn't find an answer)
I wrote a LinkedList class and a function to reverse it.The function as follows,
struct LinkedList::element* LinkedList::recurrsiveReverseList(element* head){
element* tempList;
if(head->next == NULL){... | The scope of tempList terminates when you exit the function but tempList is a pointer to a block of memory whose scope does not terminate there because it's been undoubtedly allocated by new. Memory allocated in such a way is valid right up until the point you delete it, regardless of how many functions you go in to or... |
7,156,042 | 7,156,073 | Number of instructions not comming correctly and moving out of int range | I am a novice to programming and computing.
I am running a C++ based program that is taking approx 6 hours on this machine. I use the timing utility of the framework I work in.
I tried calculating the total number of iterations of my nested loop via a simple program:
{
int k=0;
for (int i = 0; i < 196779; i++)
for (in... |
Mathematically I would expect it to agree with the value 1.9360889031 × 10^10
1.9360889031 × 10^10 (19,360,889,031) is larger than 2,147,483,647, the maximum value representable by an int (at least on your compiler).
The output goes into negative values after a while as it exceeds the int range, but it shouldn't.
Y... |
7,156,127 | 7,156,149 | C++ how to turn all `\` into `/` inside of string? | So I try std::replace(diff_path.begin(), diff_path.end(), "\\", "/"); but it seems not to compile on my visual studio. What to do - how to turn all \ into / inside of string?
Error 3 error C2446: '==' : no conversion from 'const char *' to 'int' c:\program files (x86)\microsoft visual studio 10.0\vc\include\algori... | You need to use character literals, not string literals:
std::replace(diff_path.begin(), diff_path.end(), '\\', '/');
^~~~ ^~~
The value_type of a std::string is char (each element in a string is a single character).
|
7,156,203 | 7,156,259 | Using one of the parameter's getter to set the value of another parameter in a C++ function? | In a C++ function, can I use one of the parameter's getter to set the default value of the other parameter following it? For example if I have the followig class Foo,
class Foo{
public:
setID();
getID();
private:
string id;
}
Can I write a function fooManipulator like this,
int fooManipulator(... | No, as has been stated, the order of evaluation of arguments to a function is unspecified.
However, you can achieve the effect easily with an overload like this:
int fooManipulator(Foo bar)
{
return fooManipulator(bar, bar.getId());
}
|
7,156,810 | 7,156,845 | Apple Mach-O Linker (Id) Error : While calling c++ file from .m file | I have some cpp file where my functions are written. I want to call that functions in my iPhone app? How can i call c++ methods in my .m file???
Here is my .cpp file
int add(int a, int b)
{
return a+b;
}
Now in my viewDidLoad event i am using following code just to fetch the result and display in a Label.
NSNumber... | If you want to use C++ file in your Objective-C file, change the file extension from .m to .mm.
|
7,156,842 | 7,156,888 | Resizable char buffer container type for C++ | I'm using libcurl (HTTP transfer library) with C++ and trying to download files from remote HTTP servers. As file is downloaded, my callback function is called multiple times (e.g. every 10 kb) to send me buffer data.
Basically I need something like "string bufer", a data structure to append char buffer to existing str... | I'd go for stringstream. Just insert into it as you recieve the data, and when you're done you can extract a full std::string from it. I don't see why you'd want to seek into an array? Anyway, if you know the block size, you can calculate where in the string the corresponding block went.
|
7,156,880 | 7,190,169 | Dijkstra Shortest Path with VertexList = ListS in boost graph | I am quite new to Boost graph. I am trying to adapt an example for finding Dijkstra Shortest Path algorithm which used VertexList = vecS. I changed the vertex container to ListS. I learned that we have to provide our own vertex_index for the algorithm to work if we use listS.
int main(int, char *[])
{
typedef float W... | BGL actually has an example of using dijkstra_shortest_paths with listS/listS, but it's not linked to from the HTML documentation: http://www.boost.org/doc/libs/release/libs/graph/example/dijkstra-example-listS.cpp
What the error message is trying to tell you (error: no match for ‘operator=’ in ‘index.boost::adj_list_v... |
7,156,908 | 7,187,059 | Where can I find an official reference listing the operation of SSE intrinsic functions? | Is there an official reference listing the operation of the SSE intrinsic functions for GCC, i.e. the functions in the <*mmintrin.h> header files?
| As well as Intel's vol.2 PDF manual, there is also an online intrinsics guide.
The Intel® Intrinsics Guide contains reference information for Intel intrinsics, which provide access to Intel instructions such as Intel® Streaming SIMD Extensions (Intel® SSE), Intel® Advanced Vector Extensions (Intel® AVX), and Intel® Ad... |
7,156,925 | 7,157,212 | How to find out a TCP server's status from the client side (In a redundant server case)? | I have a situation here. I have a redundant TCP server setup which takes an input and then throws lots of packets forever. While reading them, I am also trying to keep up with the server's state from TCP client by doing a send on the socket.
But my servers are redundant sharing a Virtual IP. So if server1 goes down... | Okay, piecing things together, I am starting to get a picture here.
The OP is using some kind of failover in which the remote server doesn't actually keep track of the state
The reason you're not getting EPIPE from the send is that things happen this way:
You send data. send unblocks and segments start travelling
Th... |
7,157,079 | 7,157,919 | How to Use Timer in MFC Dialog based Application? | I am developing MFC Dialog based application in Visual Studio 2008. I want to use timer that start on start of the application and continue to run and calls a function that performs my task? How can I do this?
Thanks
| Just use SetTimer method, and pass two arguments: Timer ID (any number), and the timeout in milliseconds. Then write up OnTimer implementation, and an entry ON_WM_TIMER inside BEGIN_MESSAGE_MAP...END_MESSAGE_MAP.
CWnd::SetTimer takes 3 parameters, but only 2 are required. Pass third argument as NULL.
CWnd::OnTimer
|
7,157,086 | 7,157,233 | how to write Android.mk files for multi-libs native c project? | I have a seGraphics lib ,it deps agg lib and freetype lib.All of them are source files
I want to generate one seGraphics.a file.
Should i write a Android.mk file for each? How to write it?
TIA!
Here is my wrong try:
#Android.mk for seGraphics
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
include $(LOCAL_PATH)/../... | I have found it best to build each lib independently (i.e. freetype and agg). Then build seGraphics by linking against both freetype and agg using the following: LD_FLAGS += -lfreetype -lagg.
|
7,157,210 | 7,159,377 | boost::bind doesn't work with boost::tuple::get<N>() | I am trying to use boost::bind and STL with boost::tuple, but each time I try to compile I get the following error.
error: call of overloaded ‘bind(<unresolved overloaded function type>,
boost::arg<1>&)’ is ambiguous
Do you know what I am doing wrong here and why is only for the boost::arg<1>?
Thanks
AFG
... | The get function has more than one template parameter: in addition to the index, it is also parameterized on the content of the tuple (the head and the tail of the cons).
Consequently, get<0> is not an instantiation of the template; you need to provide the additional arguments:
typedef eth_array::head_type head;
typede... |
7,157,268 | 7,157,730 | visual c++ run java class as process | Something like NativeJ which is able to run Java application as myjava.exe in the task manager instead of displaying as java.exe. Please advice how do I code it from scratch in Visual studio 2010.
| You can use the Java invocation API.
|
7,157,308 | 7,157,369 | Was the Visual C++ STL human-generated or code-generated? | I freak out whenever I open up any STL-related code from Visual Studio's implementation while debugging my code:
// From <xtree>
if (_Where == begin())
{ // insert at beginning if before first element
if (_DEBUG_LT_PRED(this->comp,
this->_Kfn(_Val), _Key(_Where._Mynode())))
return (_Insert(tr... | Two things:
The indentation is actually fine, although nowadays unusual (and I personally hate it): they use an indentation of four, which is achieved via spaces, but use tabs for all multiples of eight. This used to be the standard almost everywhere (notably it’s still the default setting in several editors such as V... |
7,157,653 | 7,158,423 | Compile an exe file inside c++ | I want to create a c++ program in which
I can read an external file (that can be exe,dll,apk...etc...etc). That is read the file convert them into bytes and store them in an array
Next,I want to compile the bytes inside the array
Now this is the tricky part i want to compile the bytes into an array just to check that ... | To test whether an executable can be loaded (not quite the same as execution):
it will succeed unless
there is a lack of permissions
the file is not accessable
one of the dependencies are not accessable (dependency libraries, e.g.)
Note that on UNIX, the same can be achieved using dlopen
.
// A simple program that ... |
7,157,691 | 7,158,191 | Ambiguous call of overloaded constructor due to super class (pass by value) | I wrote a little C++ wrapper around some parts of GSL and encounter the following puzzle (for me). The code (reduced to its essentials) is as follows:
#include <stdlib.h>
struct gsl_vector_view {};
class Vector : protected gsl_vector_view {
public:
Vector ( const Vector& original );... | Overload resolution is done before access checking, that is why even the protected base class' members are considered.
Overload resolution is described in chapter 13.3 of the standard. My interpretation is that binding const AutoVector ov to Vector ( const Vector& original ); is user defined conversion, a derived-to-ba... |
7,158,039 | 7,184,305 | OpenCV (CvHaarClassifierCascade*) cvLoad doesn't load, unable to load xml file | I'm trying face detection using OpenCv 2.3. My trying to load "haarcascade_frontalface_alt_tree.xml" on my project, I'm constantly unable to load the xml file.
CvHaarClassifierCascade * pCascade = 0; // the face detector
const char* file ="C:\OpenCV2.3\opencv\data\haarcascades\haarcascade_frontalface_alt_tree.x... | To narrow down the issue, before calling cvLoad you should check to see if the file exists. Here's one way:
struct stat buf;
int statResult = stat(file,&buf);
if (statResult || buf.st_ino < 0) {
cout << "File not found: " << file << endl;
exit(-2);
}
You'll need to #include <sys/stat.h>
On my system (OS X 10.... |
7,158,275 | 7,168,447 | Right-to-left reading order: why isn't this calculated automatically? | In Visual Studio you need to set the extended window style to get a reading-order of right to left (WS_EX_LAYOUTRTL). Why is this required since if I'm using UNICODE and displaying Arabic characters the only possible way to display it is right-to-left? I'm surprised the system doesn't simply render it the correct way a... | Windows' support for RTL is more complex than just the text: WS_EX_LAYOUTRTL is actually about controling the layout of other elements in the window - from MSDN:
The window layout applies to text but also affects the other GDI elements of the window, including bitmaps, icons, the location of the origin, buttons, casca... |
7,158,494 | 7,158,660 | switch case statement not working right? | So i'm making a menu in a simple console app.
My code is pretty much: (LINKS TO ACTUAL CODE AT THE BOTTOM!)
int input;
bool LOOPING = true;
while(LOOPING)
{
cout << "Select an option:\n";
cout << "1 - option 1\n";
cout << "2 - option 2\n";
cout << "3 - option 3\n";
cout << "4 - option 4\n>";
cin >> input;
switch(inpu... | Your code is looping infinitely because you never set LOOPING to false. In the real code you only set it to false when the user chooses to exit, which will never happen because the user is not able to enter input anymore after he inputs a non-number for the first time.
The reason that it doesn't keep asking you for inp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.