question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,582,161 | 2,582,187 | Function pointer as parameter | I try to call a function which passed as function pointer with no argument, but I can't make it work.
void *disconnectFunc;
void D::setDisconnectFunc(void (*func)){
disconnectFunc = func;
}
void D::disconnected(){
*disconnectFunc;
connected = false;
}
| The correct way to do this is:
typedef void (*callback_function)(void); // type for conciseness
callback_function disconnectFunc; // variable to store function pointer type
void D::setDisconnectFunc(callback_function pFunc)
{
disconnectFunc = pFunc; // store
}
void D::disconnected()
{
disconnectFunc(); // ca... |
2,582,282 | 2,582,287 | How can I catch runtime error in C++ | By referring to C++ catching all exceptions
try {
int i = 0;
int j = 0/i; /* Division by 0 */
int *k = 0;
std::cout << *k << std::endl; /* De-reference invalid memory location. */
}
catch (...) {
std::cout << "Opps!" << std::endl;
}
The above run-time error are unable to be detected. Or, am I hav... | If you dereference a pointer that doesn't point to an object, you don't get an exception, you get undefined behavior. Anything can happen.
Usually, if you dereference a null pointer, as you do in your example, the program will crash.
|
2,582,367 | 2,582,387 | c++ opengl: how to find normalized vectors for a quad? | can anyone assist me in finding the proper formula for quad normalization ?
using c++ with opengl.
thank you!
| Assuming that you want the normal vector for a quad, this pseudo-code works
Vector3d vertex[4] = { ... }
Vector3d normal(0,0,0) ;
for (int i=0; i<4; i++)
{
normal += cross (vertex[i], vertex[(i+1)%4]) ; // cross product
}
normalize (normal) ;
// normal is the unit normal to the quad
This gives you the formula n=A... |
2,582,415 | 2,582,422 | How do you search a document for a string in c++? | Here's my code so far:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int count = 0;
string fileName;
string keyWord;
string word;
cout << "Please make sure the document is in the same file as the program, thank you!"
<< endl << "Please input do... | while(infile >> word)
{
if(word == keyWord)
{
cout << word << endl;
count++;
}
}
This would do the job. Please read about streams more.
|
2,582,417 | 2,583,036 | Comparing floats in their bit representations | Say I want a function that takes two floats (x and y), and I want to compare them using not their float representation but rather their bitwise representation as a 32-bit unsigned int. That is, a number like -495.5 has bit representation 0b11000011111001011100000000000000 or 0xC3E5C000 as a float, and I have an unsigne... | You must do a signed compare unless you ensure that all the original values were positive. You must use an integer type that is the same size as the original floating point type. Each chip may have a different internal format, so comparing values from different chips as integers is most likely to give misleading resu... |
2,582,523 | 2,582,537 | Suppress the HTTP_X_FORWARDED_FOR http header, c# .net C++ | I'm writing an application in C# that uses proxies. The proxies are sending the HTTP_X_FORWARDED_FOR during HTTP requests, and this is unwanted behavior.
I am extending the Interop.SHDocVw axWebBrowser (aka Internet Explorer) control right now, but can take another approach if needed for this problem.
Is there some wa... | The proxy server, between your C# client and web site, is adding that HTTP_X_FORWARDED_FOR header.
So, You cannot suppress that on C# client.
But if you have control on proxy server, there should be a setting to turn it off.
For example in squid, following could work.
header_access X_Forwarded_For deny all
Or
You may... |
2,582,524 | 2,582,554 | "Unable to open file", when the program tries to open file in /proc | I try to read file /proc/'pid'/status, using c program. The code is as follows, and even I use sudo to run it, the prompt still keeps throwing "Unable to open file". Please let me know if you have any ideas on how to fix this. thanks
Richard
...
int main (int argc, char* argv[]) {
string line;
char* fileLoc... | Avoid using C strings in C++. You forgot to allocate this one. A stringstream will allocate for you and has sprintf functionality.
int main (int argc, char* argv[]) {
string line;
ostringstream fileLoc;
if(argc != 2)
{
cout << "a.out file_path" << endl;
fileLoc << "/proc/net/dev";
} else {... |
2,582,529 | 2,582,533 | How can I use an array as map value? | I'm trying to create a map, where the key is an int, and the value is an array as follows:
int red[3] = {1,0,0};
int green[3] = {0,1,0};
int blue[3] = {0,0,1};
std::map<int, int[3]> colours;
colours.insert(std::pair<int,int[3]>(GLUT_LEFT_BUTTON,red)); // THIS IS LINE 24!
colours.insert(std::pair<int,int[3]>(GLU... | You can't copy arrays by value like that.
Here are several solutions, but I recommend #4 for your needs:
Use an std::vector instead of an array.
Use a map of pointers to arrays of 3 elements:
int red[3] = {1,0,0};
int green[3] = {0,1,0};
int blue[3] = {0,0,1};
std::map<int,int(*)[3]> colours;
colours.insert(std::p... |
2,582,637 | 2,582,646 | Matrix multiplication using pairs | I am looking into alternate ways to do a Matrix Multiplication. Instead of storing my matrix as a two-dimensional array, I am using a vector such as
vector<pair<pair<int,int >,int > >
to store my matrix. The pair within my pair (pair) stores my indices (i,j) and the other int stores the value for the given (i,j) pai... | So far you can store one value at one location. If you want to store several nonzero entries in the matrix, you will need more pairs of pairs in a larger structure.
map<pair<int, int>, int> would be the next logical step. Now you can iterate over rows because the first coordinate is more significant in the map's sortin... |
2,582,656 | 2,582,660 | C++ dynamic array sizing problem | The basic pseudo code looks like this:
void myFunction()
{
int size = 10;
int * MyArray;
MyArray = new int[size];
cout << size << endl;
cout << sizeof(MyArray) << endl;
}
The first cout returns 10, as expected, while the second cout returns 4.
Anyone have an explanation?
| MyArray is only a pointer, which on your system, has a size of four bytes.
When you dynamically create an array, you need to keep track of the size yourself.
If you created an automatic array or static array,
int MyArray[10];
then sizeof(MyArray) would be 40. As soon as the array decays to a pointer, though, e.g. whe... |
2,582,743 | 2,582,779 | autoreferencing this class to use in another for C++ | in java we can do this:
public class A{
public static void main(String...str){
B b = new B();
b.doSomething(this); //How I do this in c++ ? the this self reference
}
}
public class B{
public void doSomething(A a){
//Importat stuff happen here
}
}
How can I do the same but... | First, in a static method there is no this parameter. Anyway, assuming that main() is not static here is how you can do it in C++
class A {
public:
void f() {
B* b = new B();
b->doSomething(this);
}
void g() {
// ...
};
};
class B {
public:
void doSomething(A* a) {
// You ... |
2,582,797 | 2,582,942 | Why pass by const reference instead of by value? | From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified. I don't understand, however, why one would ch... | There are two main considerations. One is the expense of copying the passed object and the second is the assumptions that the compiler can make when the object is a a local object.
E.g. In the first form, in the body of f it cannot be assumed that a and b don't reference the same object; so the value of a must be re-re... |
2,582,892 | 2,583,480 | Implement a server that receives and processes client request(cassandra as backend), Python or C++? | I am planning to build an inverted index searching system with cassandra as its storage backend. But I need some guidances to build a highly efficient searching daemon server. I know a web server written in Python called tornado, my questions are:
Is Python a good choice for developing such kind of apps?
Is Nginx(or S... | Python is unlikely to allow you to write the most efficient server possible. However, it may just be that it will be fast enough, because for most applications it is.
Therefore, one path you could take is starting with Python. It's a great language for prototyping, much better than C++ for the stage in which you're not... |
2,583,020 | 2,583,029 | Library as dependency for another library | I have a big project compiled into libProject.so-file (shared library), I made some modules (shared libraries too) which use code from all libProject. Can I set libProject as dependence for moduleProject.so file? (gcc)
| Sure, just link with it like any other library
gcc -L/path/to/lib -lProject -o moduleProject.so
|
2,583,072 | 2,583,076 | ReSharper/StyleCop-like Visual Studio addon for C/C++ | Is there any ReSharper/StyleCop-like Visual Studio addon for C/C++?
I'm using ReSharper and StyleCop addons every day. Just recently started a new project which involves C/C++ programming. I miss some features from these addons like code formatting, hints/tips to use cleaner and better code, documentation/uniform code ... | Visual Assist X is pretty much the de-facto for C++ programming in Visual Studio.
|
2,583,177 | 2,591,994 | Embed WTL App in ATL ActiveX control | Is there a way to somehow Embed a WTL destop application in ATL ActiveX (ie extension)?
What I'm trying to achieve is to create an ActiveX control with office files Viewer.
As a base I have a desktop WTL application (written some time ago) which uses OOo v3 API to display documents.
I have created an ActiveX project... | Yes, you can.
Steps with VS wizard:
Create ATL project
Add ATL Control, based on some control (button, for example). In this case you'll have message map with some handlers.
Then replace CContainedWindow member to your own window and that's all.
ATL Samples page, I didn't check it, but hope it helps.
|
2,583,352 | 2,583,374 | Dynamic Object Not Creating for Privately Inherited Class | What is the reason for the following code that does not let me to create object.
class base
{
public:
void foo()
{ cout << "base::foo()"; }
};
class derived : private base
{
public:
void foo()
{ cout << "deived::foo()"; }
};
void main()
{
base *d = new derived();
d->foo... | The problem is that you are using private inheritance; this means that inheritance can only be seen inside your class (in this case, derived). You cannot point a base* to a derived instance outside your class (in this case, in main()) because the inheritance (and hence, the conversion) cannot be accessed.
This is exact... |
2,583,501 | 2,590,448 | How to call java from C++ | I need to run this line from my c++ program:
java -jar test.jar text1 text2
the java app will give a float value and give it to the c++ program.
How can I do this? I never call a java stuff before from my ms visual studio C++ file.
| When I run the java command directly on my command prompt, it works. but when I run the command from the c++ file, the error says "The system cannot execute the specified program" .
here's my code, im using ms visual studio 2005 :
#include "stdafx.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
flo... |
2,583,749 | 2,583,805 | C++ template type deduction problem | motivation: I would like to create a utility class so that instead of having to write:
if( someVal == val1 || someVal == val2 || someVal == val3 )
I could instead write:
if( is(someVal).in(val1, val2, val3) )
which is much closer to the mathematical 'a is an element of (b,c,d)' and also would save on a lot of typi... | If you want to keep this syntax, you can use a helper function like :
template<class T>
class is_op {
private:
T t_;
public:
is_op(T t) : t_(t) { }
bool in(const T& v1, const T& v2) {
return t_ == v1 || t_ == v2;
}
bool in(const T& v1, const T& v2, const T& v3) {
return t_ == v1 ... |
2,583,770 | 2,583,830 | Making a shared library from existing object files | I have a project in my IDE. I need to make a shared library of it to use in extensions. I don't want to make a copy of this project with shared-library settings. Is there any way to build a shared library using the object files (.o) from my already existing project? As I understand, I can write a makefile for this.
| I assume you're on some sort of Unix and are probably using the GNU toolchain. In that case, to create a proper shared library, you'd need to compile your code using the position-independent code flags (-fpic or -fPIC) before you can create a shared library. Unless your .o files are already compiled with those flags, c... |
2,583,853 | 2,584,018 | Unformatted output in operator << | I have a class that contains decoded video frames. I would like my decoder to use an output_iterator to write those frames to different targets. In order to support writing directly to a file, I want to overload operator << for my decoded frame class (for use with ostream_iterator). The problem is, that operator << is ... | std::basic_ostream is indeed mainly to be used for formatted output. (I say "mainly" because it does have a method for unformatted output. But that's not accessible through output iterators.) For unformatted output, use a stream buffer iterator.
|
2,584,213 | 2,584,240 | How to default-initialize local variables of built-in types in C++? | How do I default-initialize a local variable of primitive type in C++? For example if a have a typedef:
typedef unsigned char boolean;//that's Microsoft RPC runtime typedef
I'd like to change the following line:
boolean variable = 0; //initialize to some value to ensure reproduceable behavior
retrieveValue( &variable ... | You can emulate that behaviour by the following:
boolean x = boolean();
or, more general,
T x = T();
This will default-initialize x if such a default-initialization exists. However, just writing T x will never do the trick for local variables, no matter what you do.
You can also use placement-new to invoke a “constru... |
2,584,220 | 2,584,233 | Boost.MultiIndex: Are there way to share object between two processes? | I have a Boost.MultiIndex big array about 10Gb. In order to reduce the reading I thought there should be a way to keep the data in the memory and another client programs will be able to read and analyse it.
What is the proper way to organize it?
The array looks like:
struct particleID
{
int ID... | Have you looked at Boost.Interprocess?
|
2,584,595 | 8,719,066 | Building a python module and linking it against a MacOSX framework | I'm trying to build a Python extension on MacOSX 10.6 and to link it against several frameworks (i386 only). I made a setup.py file, using distutils and the Extension object.
I order to link against my frameworks, my LDFLAGS env var should look like :
LDFLAGS = -lc -arch i386 -framework fwk1 -framework fwk2
As I did n... | This has nothing to do with the undefined dynamic_lookup but all with distutils. It appends the extra_link_flags to the link flags it chooses for python building. Instead it should prepend it because the -framework listings must come before the objects that use them on the cmdline (AFAIK this is due how gcc gathers sym... |
2,584,856 | 2,585,213 | Splitting Code into Headers/Source files | I took the following code from the examples page on Asio
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
... | Splitting this could look like this:
// in the header-file
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service);
tcp::socket& socket();
void start();
private:
tcp_co... |
2,584,937 | 2,584,967 | Checking the sizeof an integer type in the preprocessor | How can I check the size of an unsigned in the preprocessor under g++? sizeof is out of the question since it is not defined when during preprocessing.
| This may not be the most elegant method, but one thing that you may be able to leverage is UINT_MAX defined in "limits.h". That is, ...
if UINT_MAX == 65535, then you would know that sizeof (unsigned) = 2
if UINT_MAX == 4294967295, then you would know that sizeof (unsigned) = 4.
and so on.
As I said, not elegant, but ... |
2,585,006 | 2,585,614 | Using the sftp protocol with libcurl -- How do I list the contents of a directory? | I have a little doubt. I need to get a list of the files inside a specific directory on a SFTP server. I will use CUROPT_DIRLISTONLY in order to get just the names, but I'm not sure how to get them. This is the peace of code I have by now:
string baseUrl(serverAddr + "/" + __destDir);
curl_easy_setopt(anEasyHandl... | You need to create a "callback function" with the following signature:
size_t function( void *ptr, size_t size, size_t nmemb, void *stream);
You then call curl_easy_setopt to set the callback function as your CURLOPT_WRITEFUNCTION. Your function will be called for each chunk of data recieved from the remote server, wh... |
2,585,021 | 2,585,063 | Problems with passing an anonymous temporary function-object to a templatized constructor | I am trying to attach a function-object to be called on destruction of a templatized class. However, I can not seem to be able to pass the function-object as a temporary. The warning I get is (if the comment the line xi.data = 5;):
warning C4930: 'X<T> xi2(writer (__cdecl *)(void))':
prototyped function not ca... | Looks like a "most vexing parse" issue. Try
X<int> xi2 = X<int>(writer());
or
X<int> xi2((writer()));
|
2,585,280 | 2,585,328 | Cross platform millisecond timer lasting more than 49 days? | I'm going to be developing a small dedicated server in C/C++ that will require uptime of forever. I've been looking into some time functions as millisecond timing is required for calculations. I have 2 problems that I'm facing:
Using a 32bit integer to store the number of milliseconds since the operation began will ... |
Use a 64bit integer, presuming that gives you enough time
You are correct; there is no standard. One possibility would be to use the Boost DateTime library, alternately find another or roll your own.
Good Luck!
|
2,585,621 | 2,590,422 | how to cout a vector of structs (that's a class member, using extraction operator) | i'm trying to simply cout the elements of a vector using an overloaded extraction operator. the vector contians Point, which is just a struct containing two doubles.
the vector is a private member of a class called Polygon, so heres my Point.h
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <string>
#inclu... | ok, i got the loop working like this.....
ostream & operator << (ostream &outStream, const Polygon::Polygon &vertStr)
{
for (int i = 0; i < vertStr.sizeOfVect(); i++)
{
outStream << vertStr.vertices.at(i) << endl;
}
return outStream;
}
then just
cout << mainPoly << endl;
in the driver
i'm sure i tried that o... |
2,585,799 | 2,585,847 | Object oriented design suggestion | Here is my code:
class Soldier {
public:
Soldier(const string &name, const Gun &gun);
string getName();
private:
Gun gun;
string name;
};
class Gun {
public:
void fire();
void load(int bullets);
int getBullets();
private:
int bullets;
}
I need to call all the member functions of Gun over a Sol... | I would say go with your second option:
soldier.loadGun(15); // calls Gun.load()
soldier.fire(); // calls Gun.fire()
Initially it's more work, but as the system gets more complex, you may find that a soldier will want to do other things before and after firing their gun (maybe check if they have enough ammo and then ... |
2,585,943 | 2,586,315 | Qt variable re-assignment | I have two examples I have a question about. Let me explain via some code:
Question 1:
QStringList qsl(); // Create a list and store something in it
qsl << "foo";
QString test = "this is a test";
qsl = test.split(" ", QString::SkipEmptyParts); // Memory Leak?
What happens when I re-assign the qsl variable what happe... | Assigning to a QStringList variable works the same as assigning to any other variable in C++. For objects, the assignment operator of the object on the left is called to copy the content of the object on the right into the object on the left. Usually this does just a memberwise assignment:
struct A {
int x;
QString... |
2,585,951 | 7,589,763 | Getting SIGILL in float to fixed conversion | I'm receiving a SIGILL after running the following code. I can't really figure what's wrong with it.
The target platform is ARM, and I'm trying to port a known library (in which this code is contained)
void convertFloatToFixed(float nX, float nY, unsigned int &nFixed) {
short sx = (short) (nX * 32);
short sy =... | Some ARM processors have hardware floating-point, and some don't, so it's possible that this function is being compiled for hardware floating-point but your platform lacks a floating-point unit, so the floating-point instructions cause the processor to report an illegal instruction. If this is the first floating-point ... |
2,586,662 | 2,587,242 | Still failing a function, not sure why...ideas on test cases to run? | I've been trying to get this Sudoku game working, and I am still failing some of the individual functions. All together the game works, but when I run it through an "autograder", some test cases fail..
Currently I am stuck on the following function, placeValue, failing. I do have the output that I get vs. what the corr... | If it's printing invalid row after every input, we have to conclude that your code is doing what it says: It thinks that every row is outside the range A-I. Most likely some input got your cin into a frozen state and the cin >> row is actually either sticking a 0 or nothing at all into row, and thus it's constantly fai... |
2,586,681 | 2,586,712 | C++ CIN cin skips randomly | I have this program, but cin in randomly skips.. I mean sometimes it does, and sometimes it doesn't. Any ideas how to fix this?
int main(){
/** get course name, number of students, and assignment name **/
string course_name;
int numb_students;
string assignment_name;
Assig... | I would guess that some of your inputs have spaces in them, which the >> operator treats as the end of a particular input item. The iostreams >> operator is really not designed for interactive input, particularly for strings - you should consider using getline() instead.
Also, you are needlessly using dynamic allocatio... |
2,587,135 | 2,592,087 | Using the C Cluster library in Visual C++ | Right so i'm trying to use a C library in C++, never actually done this before i thought it would be a case of declaring the header includes under a extern "C" and setting the compile as flag to "default" but i'm still getting linker errors and think that the header file might have to be complied as a DLL. I have no i... | A header file only contains function declarations. You also need the implementation of those functions, which will be contained in the .c files, if the library is distributed as source, or in the .LIB and/or .DLL file if the library is a binary distribution. In either case. the .h files alone are not sufficient.
|
2,587,235 | 2,587,304 | Choosing between instance methods and free functions? | Adding functionality to a class can be done by adding a method or by defining a function that takes an object as its first parameter. Most programmers that I know would choose for the solution of adding an instance method.
However, I sometimes prefer to create a separate function. For example, in the example code below... | GoTW #84 explored this question with respect to std::string. He tended toward rather the opposite idea: most functions should be global unless they really need to be members.
I'd say most modern C++ tends toward the same idea. If you look through Boost, for example, quite a bit is done with free functions.
|
2,587,349 | 2,587,458 | initializing char and char pointers | What's the difference between these:
This one works:
char* pEmpty = new char;
*pEmpty = 'x';
However if I try doing:
char* pEmpty = NULL;
*pEmpty = 'x'; // <---- doesn't work!
and:
char* pEmpty = "x"; // putting in double quotes works! why??
EDIT: Thank you for all the comments:
I corrected it. it was supposed to b... | The difference is that string literals are stored in a memory location that may be accessed by the program at runtime, while character literals are just values. C++ is designed so that character literals, such as the one you have in the example, may be inlined as part of the machine code and never really stored in a me... |
2,587,423 | 2,587,720 | Emulating a web browser | we are tasked with basically emulating a browser to fetch webpages, looking to automate tests on different web pages. This will be used for (ideally) console-ish applications that run in the background and generate reports.
We tried going with .NET and the WatiN library, but it was built on a Marshalled IE, and so it ... | You might try one of these:
http://code.google.com/p/spynner/
http://code.google.com/p/pywebkitgtk/
|
2,587,445 | 2,588,103 | are C functions declared in <c____> headers guaranteed to be in the global namespace as well as std? | So this is something that I've always wondered but was never quite sure about. So it is strictly a matter of curiosity, not a real problem.
As far as I understand, whenyou do something like #include <cstdlib> everything (except macros of course) are declared in the std:: namespace. Every implementation that I've ever s... | Here's a nice synopsis of the situation (with some relaity vs. what the standard says) from Stephan T. Lavavej of the MSVC team (http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx#8904359):
> also, <cstddef>, <cstdlib>, and std::size_t etc should be used!
I used to be very careful about that. C++98 ha... |
2,587,541 | 2,587,564 | Does C++ have a static polymorphism implementation of interface that does not use vtable? | Does C++ have a proper implementation of interface that does not use vtable?
for example
class BaseInterface{
public:
virtual void func() const = 0;
}
class BaseInterfaceImpl:public BaseInterface{
public:
void func(){ std::cout<<"called."<<endl; }
}
BaseInterface* obj = new BaseInterfaceImpl();
obj->func();
the call... | Yes. It goes by the moniker CRTP. Have a gander.
|
2,587,558 | 2,587,614 | Return pointer to nested inner class from generic outer class | I'm new to C++, so bear with me. I have a generic class called A. A has a nested class called B. A contains a method called getB(), which is supposed to return a new instance of B. However, I can't get my code to compile. Here's what it looks like:#include
A.h
template <class E>
class A {
public:
class B {
... | The compiler isn't smart enough to figure that "B" is a type when "A" is templated. Try using typename.
template <class E>
typename A<E>::B * A<E>::getB() {
return new B();
}
|
2,587,613 | 2,587,665 | What is the Effect of Declaring 'extern "C"' in the Header to a C++ Shared Library? | Based on this question I understand the purpose of the construct in linking C libraries with C++ code. Now suppose the following:
I have a '.so' shared library compiled with a C++ compiler. The header has a 'typedef stuct' and a number of function declarations. If the header includes the extern "C" declaration...
#ifde... | This is important so that the compiler doesn't name mangle. C++ uses name mangling to differentiate functions with operator overloads.
Run "/usr/bin/nm" against a binary to see what C++ does with your function names:
_ZSt8_DestroyIN9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEEiEvT_S7_SaIT0_E
extern "C" prevents ... |
2,587,625 | 2,587,724 | Warning that callers of a function must handle | I am looking for a way to set a warning that the caller will have to respond to. In a sense I would like to use a late exception mechaninism that occurs after the function already finished executing and returned the wanted value.
SomeObject Foo(int input)
{
SomeObject result;
// do something. oh, we need to... | You have to make a more concrete decision, I think. It's very unorthodox to (somehow) warn the user of a function while giving them a result.
For example, you could return a std::pair<SomeObject, std::string>, where the warning is in the string, if any. But it'll be very easy for people to ignore that.
An exception isn... |
2,587,708 | 2,587,744 | Am I deleting this properly? | I have some struct:
struct A
{
const char* name_;
A* left_;
A* right_;
A(const char* name):name_(name),
left_(nullptr),
right_(nullptr){}
A(const A&);
//A(const A*);//ToDo
A& operator=(const A&);
~A()
{
/*ToDo*/
};
};
/*Just to compile*/
A& A::operator=(const A& pattern)
{
//check for self-ass... | void* p = new char[sizeof(A)];
A* tmp = new (p) A("tmp");
tmp->~A();
delete tmp;//I WONDER IF HERE I SHOULD USE DIFFERENT delete[]?
No. You have already called the destructor so it is not correct to call delete which will cause another destructor call. You only need to free the memory. e.g.
delete[] static_cast<char*>... |
2,588,354 | 2,588,396 | Why does this crash? | I've been banging my head...I can't pretend to be a C++ guy...
TCHAR * pszUserName = userName.GetBuffer();
SID sid;
SecureZeroMemory(&sid, sizeof(sid));
SID_NAME_USE sidNameUse;
DWORD cbSid = sizeof(sid);
pLog->Log(_T("Getting the SID for user [%s]"), 1, userName);
if (!LookupAccountName(NULL, (LPSTR)pszUserName,... | Parameter 6 (cchReferencedDomainName) should point to a DWORD. When the documentation says, "if the ReferencedDomainName parameter is NULL, this parameter must be zero," I believe they mean that the referenced DWORD must be 0.
Try adding:
DWORD cchReferencedDomainName = 0;
if (!LookupAccountName(NULL, (LPSTR)pszUserNa... |
2,588,431 | 2,589,492 | How can I get type information at runtime from a DMP file in a Windbg extension? | This is related to my previous question, regarding pulling objects from a dmp file.
As I mentioned in the previous question, I can successfully pull object out of the dmp file by creating wrapper 'remote' objects. I have implemented several of these so far, and it seems to be working well. However I have run into a s... | DOH! It was much simpler than I thought. The virtual function tables are simply other symbols, so I can use GetSymbol() with the address of the field1's vftable. Then simply setup a case statement with the few types I expect, and create the right one for the situation.
For example:
char buffer[255];
ULONG64 displac... |
2,588,777 | 2,588,810 | Capturing the input stream as a user types | I am working on a C++ based command line tool and I want to capture the user's keystrokes in real-time without requiring them to hit Return to commit the input. I can't seem to find an iostream call to support this kind of behavior but I recall from my college years that it can be done. Can anyone point me in the right... | That is outside of the C++ spec and requires OS specific calls. On Posix, you do this by enabling raw or cbreak mode instead of cooked mode.
The easiest way to enable this is via curses.
|
2,588,803 | 2,588,852 | Best way to insert items from a Derived class's constructor into a Base class's private std::vector? | I have these classes:
class Base
{
...
private:
std::vector<X> v;
};
class Derived : public Base
{
Derived(X*, int n);
};
where the constructor of Derived is passed an array of item Xs, which I need to insert into my vector v in the Base class. (X is a smart pointer)
Currently I see two ways to do this:
Create a fun... | There is a third option if you can modify Base. You could make the vector protected which will allow base classes full access:
class Base
{
...
protected:
std::vector<X> v;
};
Your base class can now directly operate on v. If you need to expose much of the vector functionality to Derived, this is the easiest way... |
2,588,962 | 2,589,066 | push_back of STL list got bad performance? | I wrote a simple program to test STL list performance against a simple C list-like data structure. It shows bad performance at "push_back()" line. Any comments on it?
$ ./test2
Build the type list : time consumed -> 0.311465
Iterate over all items: time consumed -> 0.00898
Build the simple C List: time consumed -> 0... | Your STL codes create a memory piece twice for each cell.
The following is from STL 4.1.1 on x86_64
void push_back(const value_type& __x)
{
this->_M_insert(end(), __x);
}
// Inserts new element at position given and with value given.
void _M_insert(iterator __position, const value_type& __x)
{
_Node* __tmp = _M... |
2,589,197 | 2,589,220 | How do I repass a function pointer in C++ | Firstly, I am very new to function pointers and their horrible syntax so play nice.
I am writing a method to filter all pixels in my bitmap based on a function that I pass in. I have written the method to dereference it and call it in the pixel buffer but I also need a wrapper method in my bitmap class that takes the f... | If I understand what you want:
inline void cBitmap::Filter(sColour (*FilterFunc)(sColour))
{
_pixels->FilterAll( FilterFunc);
}
Often dealing with function pointers can be made easier to read if you use a typedef for the function pointer type (yours actually isn't too bad on its own - they can get much worse ve... |
2,589,198 | 2,589,211 | How to change this C++ code to make input work better | cout << "Input street number: ";
cin >> streetnum;
cout << "Input street name: ";
cin >> streetname;
cout << "Input resource name: ";
cin >> rName;
cout << "Input architectural style: ";
cin >> aStyle;
cout << "Input year built: ";
cin >> y... | That's because when you use the extraction operator with a string as the right-hand side, it stops at the first white space character.
What you want is the getline free function:
std::getline(std::cin, streetnum); // reads until \n
You can specify some other delimiter if you want:
char c = /* something */;
std::getlin... |
2,589,282 | 2,589,354 | Templates, and C++ operator for logic: B contained by set A | In C++, I'm looking to implement an operator for selecting items in a list (of type B) based upon B being contained entirely within A.
In the book "the logical design of digital computers" by Montgomery Phister jr (published 1958), p54, it says:
F11 = A + ~B has two interesting and useful associations, neither of them ... | The way this is done all over the place in the standard library is two have a templated parameter that can take a function/functor and that is used for the comparisons:
template<typename Predicate>
void container::select(Predicate p) {
if (p(items[0])) {
// something
}
}
Some examples from the standard libr... |
2,589,357 | 2,589,658 | Coupling between controller and view | The litmus test for me for a good MVC implementation is how easy it is to swap out the view. I've always done this really badly due to being lazy but now I want to do it right. This is in C++ but it should apply equally to non-desktop applications, if I am to believe the hype.
Here is one example: the application contr... |
The litmus test for me for a good MVC implementation is how easy it is to swap out the view.
I'll probably draw fire for saying this, but I don't agree with this statement. This looks good on paper, but real-world examples show that a good UI is responsive and interactive, which often times necessitates intertwinin... |
2,589,433 | 2,589,441 | Sub-classing templated class without implementing pure virtual method | I have the following class definition:
template<typename QueueItemT>
class QueueBC
{
protected:
QueueBC() {}
virtual ~QueueBC() {}
private:
virtual IItemBuf* constructItem(const QueueItemT& item) = 0;
}
I created the following sub-class:
class MyQueue
: public QueueBC<MyItemT>
{
public:
MyQueue(... | Try using it:
MyQueue m;
You can't instantiate an abstract class, but you can define one (obviously, as you defined QueueBC). MyQueue is just as abstract.
For example:
struct base // abstract
{
virtual void one() = 0;
virtual void two() = 0;
};
struct base_again : base // just as abstract as base
{
};
struct... |
2,589,506 | 2,589,805 | lock file so that it cannot be deleted | I'm working with two independent c/c++ applications on Windows where one of them constantly updates an image on disk (from a webcam) and the other reads that image for processing. This works fine and dandy 99.99% of the time, but every once in a while the reader app is in the middle of reading the image when the writer... | Try using a synchronization object, probably a mutex will do. Whenever a process wants to read or write to a file it should first acquire the mutex lock.
|
2,589,533 | 2,589,544 | What is a Cursor Linked List? [C++] | My professor provided me with a file called CursorList.cpp that implements a "Cursor Linked List". The problem is - I have no idea what that even is!
Could anybody give me the gist of it?
Thanks!
| According to this, here is some background on a cursor linkedlist:
some languages do not support pointers
use arrays of objects instead
start with a Freelist
allocate space from Freelist when needed
to delete: change pointers, add to Freelist
So basically a linked list that is implemented without using pointers. Mayb... |
2,589,650 | 2,611,737 | Multicolor text in TreeView (Embarcadero RAD studio) | I am writing a piece of software in C++ RAD studio 2010 and got a question about TreeView.
Is it possible to use multicolor text in a TTreeView component? I could not find a easy way but to implement custom drawing which seems to be weird nowadays. Are there any straight-forward ways or maybe additional components that... | Custom drawing is the only way. There is nothing weird about that. Many controls support custom drawing.
|
2,589,668 | 2,589,756 | boost::program_options bug or feature? | Very simple example:
#include <string>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char* argv[])
{
po::options_description recipients("Recipient(s)");
recipients.add_options()
("csv", po::value<std::string>(), "" )
("csv_name",... | Yes, this is a "feature" due to default options parsing style. Try with short options, like:
recipients.add_options()
("csv,c", po::value<std::string>(), "" )
("csv_name,C", po::value<unsigned>(), "" )
;
Or play with the basic_command_line_parser::style(int) method. I haven't tried this, so YMMV.
|
2,589,674 | 2,589,694 | What is the best way to store incremental downloaded data? | Inspired by Chromium's sha1 class, I am thinking to store incrementally downloaded data using std::string
// pseudo-code
char buff[BUFF_SIZE];
std::string data;
do {
size = ReadInternetFileTo(buff,BUFF_SIZE);
data.append(buff,size);
} while (not_finished);
Any foreseeable problems with this method or better wa... | Should be OK, but you may want to consider rope instead of string. It is more efficient to append to a rope, as it won't promise to keep all bytes consecutive, which will require a reallocation.
|
2,589,861 | 2,589,883 | C++ template meta-programming, number of member variables? | Is it possible in C++ to determine number of variables/fields in the generic class?
for example
// suppose I need metaclass number_members determines number of members
struct example { int i, j; };
assert(number_members<example>::value==2);
I looked through mpl but could not find implementation.
thanks.
| No. C++ does not provide general introspection into structures.
You can try a C++0x std::tuple, which has some of the features of a general POD struct. Or, try to roll your own from the Boost MPL library. That would be a bit advanced if you're just getting started with C++.
|
2,590,167 | 2,590,239 | What are the advantages and disadvantages of using boost::iterator_facade? | Yep -- the title pretty much sums it up. I've got quite a few types that implement iterator concepts, and I'm wondering if it's worthwhile to pull in this boost header instead of implementing things manually.
So far:
Advantages
Well specified
Less likely to have bugs
| If maintaining your own iterator types becomes a burden then switch to boost. They are well specified and tested and less likely to have bugs.
|
2,590,265 | 2,590,412 | Learning Visual C++ 2008 and C++ at the same time? Any resources to recommend? | I am trying to learn Visual C++ 2008 and C++ at the same time to get involved with sourcemod, a server side modding tool for valve games. However I have never touched Visual C++ or C++ in general, and doing some preliminary research I am quite confused on these different versions of C++ (mfc, cli, win32), and why a lot... | why a lot of people seem to hate Visual C++ and use something like Borland instead
You must be looking at old data. Borland's C++ department is essentially defunct nowadays if I'm not mistaken. Their commandline compiler is still available for free, but it seems Borland is happier to focus on Delphi rather than continu... |
2,590,299 | 2,590,436 | Importing .dll into Qt | I want to bring a .dll dependency into my Qt project.
So I added this to my .pro file:
win32 {
LIBS += C:\lib\dependency.lib
LIBS += C:\lib\dependency.dll
}
And then (I don't know if this is the right syntax or not)
#include <windows.h>
Q_DECL_IMPORT int WINAPI DoSomething();
btw the .dll looks something like this:
... | Your "LIBS +=" syntax is wrong. Try this:
win32 {
LIBS += -LC:/lib/ -ldependency
}
I'm also not sure if having absolute paths with drive letter in your .pro file is a good idea - I usually keep the dependencies somewhere in the project tree and use relative path.
EDIT:
I suppose that something is wrong in your dll... |
2,590,310 | 2,590,763 | Can I use boost::make_shared with a private constructor? | Consider the following:
class DirectoryIterator;
namespace detail {
class FileDataProxy;
class DirectoryIteratorImpl
{
friend class DirectoryIterator;
friend class FileDataProxy;
WIN32_FIND_DATAW currentData;
HANDLE hFind;
std::wstring root;
DirectoryItera... | You will indeed need to make some boost pieces friend for this. Basically make_shared is calling the constructor and the fact that this is done from within a friend function does not matter for the compiler.
The good news though is that make_shared is calling the constructor, not any other piece. So just making make_sh... |
2,590,553 | 2,590,569 | Function pointer demo | Check the below code
int add(int a, int b)
{
return a + b;
}
void functionptrdemo()
{
typedef int *(funcPtr) (int,int);
funcPtr ptr;
ptr = add; //IS THIS CORRECT?
int p = (*ptr)(2,3);
cout<<"Addition value is "<<p<<endl;
}
In the place where I try to assign a function to function ptr with same... | It is very likely that what you intended to write was not:
typedef int *(funcPtr) (int,int);
but:
typedef int (*funcPtr) (int,int);
|
2,590,668 | 2,590,977 | Customize page number when printing a QTextDocument | I'm trying to print the content of a QTextEdit. For that I'm using QTextDocument::print(QPrinter*). Doing that, a page number is automatically added at the right bottom of the page.
Is there any way to change its format / move it / get rid of it?
Thanks.
| As far as I know that is hard coded into Qt, so you can't change it.
Have a look at QTBUG-1688. There you see that this fact has already been reported, but they don't seem to work on it. So you will have to do it yourself, I think.
|
2,590,677 | 2,595,226 | How do I combine hash values in C++0x? | C++0x adds hash<...>(...).
I could not find a hash_combine function though, as presented in boost. What is the cleanest way to implement something like this? Perhaps, using C++0x xor_combine?
| Well, just do it like the boost guys did it:
template <class T>
inline void hash_combine(std::size_t& seed, const T& v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
|
2,590,726 | 3,332,502 | How to enable BDS2006's C++ WARN & TRACE macros | I am trying to find out how to enable (& use) Borland's WARN & TRACE macros.
My starting point was this link:
http://bcbjournal.org/articles/vol2/9809/Debugging_with_diagnostic_macros.htm?PHPSESSID=37bf58851bfeb5c199d1af31d7b2e7ff
However, that appears to be for BCB5, and not the 2006 Borland Developer Studio.
I've se... | I was investigating this debug TRACE feature too since I use Borland's toolchain. A couple things I noted while I was figure this out.
Make sure __TRACE and __WARN are define before #include <checks.h>.
You can also remove the #define __TRACE and __WARN from the translation unit and instead pass it to bcc32 using the ... |
2,590,910 | 2,590,976 | Is there a way to use template specialization to separate new from new[]? | I have an auto pointer class and in the constructor I am passing in a pointer. I want to be able to separate new from new[] in the constructor so that I can properly call delete or delete[] in the destructor. Can this be done through template specialization? I don't want to have to pass in a boolean in the constructor.... | std::unique_ptr in C++0x will have a specialization for dynamic arrays, somewhat like shown below. However, it will be the user's task to instantiate an appropriate instance. At language level there is no way to distinguish one pointer from another.
template <class T>
class pointer
{
T* p;
public:
pointer(T* pt... |
2,590,964 | 2,590,982 | Getting started with C++ ( the paradigm shift from Python ) | I want to learn C++ so that i can develop C++ Python modules for server-related stuff.
I'm a purely dynamic languages developer (Python, PHP, Ruby, etc). I want to learn a fast language, and if I'm going to do this, I'd rather learn a really fast language like C++. Before I even get started though, I understand that su... | I doubt there is any specific advice that can be given, other than that you must read a good book on C++ written by an authoritative author or authors - do not pick the first or cheapest one that comes your way. For a list of books see The Definitive C++ Book Guide and List - I personally would strongly recommend Acc... |
2,591,025 | 2,591,047 | C++ code to class diagram | Is there is a way I can generate a hierachial class diagram from C++ code. My code is spread over 5 to 6 .cpp files.
I would like to know if there is any free tool for the same.
Regards,
AJ
| There's e.g. doxygen
http://www.doxygen.nl/manual/features.html says:
Uses the dot tool of the Graphviz tool kit to generate include dependency graphs, collaboration diagrams, call graphs, directory structure graphs, and graphical class hierarchy graphs.
It creates graphs like
(from http://www.vtk.org/doc/nightly/html... |
2,591,419 | 2,593,959 | Expected output from an RM-1501 RS232 interface? | I have an old RM-1501 digital tachometer which I'm using to try to identify the speed of an object.
According to the manual I should be able to read the data over a serial link. Unfortunately, I don't appear to be able to get any sensible output from the device (never gives a valid speed). I think it might be a signal... | I tried every combination of hardware control (both enabled and disabled) I could think of so I think it must be a hardware problem. Removnig the CLS link between PC and the device solved the issue.
|
2,592,101 | 2,592,166 | Who calls the Destructor of the class when operator delete is used in multiple inheritance | This question may sound too silly, however , I don't find concrete answer any where else.
With little knowledge on how late binding works and virtual keyword used in inheritance.
As in the code sample, when in case of inheritance where a base class pointer pointing to a derived class object created on heap and delete... | The compiler generates all necessary code to call destructors in the right order, whether it be a stack object or member variable going out of scope, or a heap object being deleted.
|
2,592,155 | 2,592,190 | Testing C++ program with Testing classes over normally used classes | This will probably be a bot of a waffly question but ill try my best.
I have a simple c++ program that i need to build testing for. I have 2 Classes i use besides the one i actually am using, these are called WebServer and BusinessLogicLayer.
To test my own code i have made my own versions of these classes that feed d... | You can define abstract base classes that declare the public interfaces for your components, then wire the objects together at runtime (in main() or something else fairly high up in the food chain). In testing, you simply wire up different objects.
|
2,592,449 | 2,592,482 | Why is calling close() after fopen() not closing? | I ran across the following code in one of our in-house dlls and I am trying to understand the behavior it was showing:
long GetFD(long* fd, const char* fileName, const char* mode)
{
string fileMode;
if (strlen(mode) == 0 || tolower(mode[0]) == 'w' || tolower(mode[0]) == 'o')
fileMode = string("w");
... | If you open a file with fopen, you have to close it with fclose, symmetrically.
The C++ runtime must be given a chance to clean up/deallocate its inner file-related structures.
|
2,592,523 | 4,692,115 | About inconsistent dll linkage | How can I remove this link warning? You can see code segment that causes this warning.
static AFX_EXTENSION_MODULE GuiCtrlsDLL = { NULL, NULL };
//bla bla
// Exported DLL initialization is run in context of running application
extern "C" void WINAPI InitGuiCtrlsDLL()
{
// create a new CDynLinkLibrary for t... | There are multiple possibilities:
1) static AFX_EXTENSION_MODULE GuiCtrlsDLL = { NULL, NULL };
You use AFX_EXTENSION_MODULE. This means that you are implementing an MFC extension DLL. For such extension dlls you have to define the preprocessor _AFXEXT. Set this in the C++ compiler settings of your Visual C++ project
se... |
2,592,552 | 2,592,578 | using macro defined in header files | I have a macro definition in header file like this:
// header.h
ARRAY_SZ(a) = ((int) sizeof(a)/sizeof(a[0]));
This is defined in some header file, which includes some more header files.
Now, i need to use this macro in some source file that has no other reason to include header.h or any other header files included in ... | Include the header file or break it out into a smaller unit and include that in the original header and in your code.
As for code size, unless your headers do something incredibly ill-advised, like declaring variables or defining functions, they should not affect the memory footprint much, if at all. They will affect ... |
2,592,622 | 2,627,376 | How to control flash movie using activex wrapper? | How to play the flash movie always from the beginning ?
Any way to rewind movie ?
I have use rewind() method for that but it didn't work.
Any help is welcomed....
| At first I have tried Rewind() method of activeX wrapper but it didn't work.
Another good approach is to Call Flash function from VC++.
m_Flash.CallFunction("<invoke name=\"MethodName\"returntype=\"xml\"><arguments></arguments></invoke>");
|
2,592,653 | 2,592,720 | Trying to create a .NET DLL to be used with Non-.NET Application | I am trying to create a .NET DLL so I can use the cryptographic functions with my non .NET application.
I have created a class library so far with this code:
namespace AESEncryption
{
public class EncryptDecrypt
{
private static readonly byte[] optionalEntropy = { 0x21, 0x05, 0x07, 0x08, 0x27, 0x02, 0x2... | You don't appear to have flagged the Interface as visible via COM. I'd expect to see something like:
namespace AESEncryption
{
[Guid("[a new guid for the interface]")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEncrypt {
string Encrypt(string data, string filePath... |
2,592,746 | 2,659,679 | template specialization of a auto_ptr<T> | Maybe I'm overcomplicating things, but then again, I do sort of like clean interfaces. Let's say I want a specialization of auto_ptr for an fstream - I want a default fstream for the generic case, but allow a replacement pointer?
template <>
class auto_ptr<fstream> {
static fstream myfStream;
fstream* p... | This wouldn't end up good. The biggest problem is that std::auto_ptr deletes the underlying object in its destructor. This means your default parameter can't be static. The only choice you can make is to do a lot of hacks there and IMHO the price you'll pay while maintaining all that crappy code isn't worth the small a... |
2,592,800 | 2,592,899 | Help with C++ Boost::regex | I'm trying to get all words inside a string using Boost::regex in C++.
Here's my input :
"Hello there | network - bla bla hoho"
using this code :
regex rgx("[a-z]+",boost::regex::perl|boost::regex::icase);
regex_search(input, result, rgx);
for(unsigned int j=0; j<result.size(); ++j)
{... | regex_search only finds the first match. To iterate over all matches, use regex_iterator
|
2,592,821 | 2,594,836 | Building external code trees with SCons | I'm trying to use SCons for building a piece of software that depends on a library that is available in sources that are installed in system. For example in /usr/share/somewhere/src. *.cpp in that directory should be built into static library and linked with my own code. Library sources have no SConscript among them.
S... | You could use a Repository to do this. For example, in your SConstruct you could write:
sys_lib = env.SConscript("external.scons", variant_dir=".build/external")
Then in the external.scons file (which is in your source tree), you add the path to the external source tree and how to build the library therein.
env = Envi... |
2,593,137 | 2,593,492 | Tool for finding C-style Casts | Does anyone know of a tool that I can use to find explicit C-style casts in code? I am refactoring some C++ code and want to replace C-style casts where ever possible.
An example C-style cast would be:
Foo foo = (Foo) bar;
In contrast examples of C++ style casts would be:
Foo foo = static_cast<Foo>(bar);
Foo foo = re... | If you're using gcc/g++, just enable a warning for C-style casts:
g++ -Wold-style-cast ...
|
2,593,167 | 2,593,272 | Can I specify default value? | Why is it that for user defined types when creating an array of objects every element of this array is initialized with the default constructor, but when I create an array of a built-in type that isn't the case?
And second question: Is it possible to specify default value to be used while initializing elements in the a... |
Something like this (not valid):
As far as I know that is perfectly valid.
Well not completely, but you can get a zero intialized character array:
#include <iostream>
#include <cstdlib>
int main(int argc, char* argv[])
{
//The extra parenthesis on the end call the "default constructor"
//of char, which inita... |
2,593,173 | 2,593,197 | Smart pointers - cases where they cannot replace raw pointers | HI,
I have this query about smart pointers.
I heard from one of my friends that smart pointers can almost always replace raw pointers.
but when i asked him what are the other cases where smart pointers cannot replace the raw pointers,i did not get the answer from him.
could anybody please tell me when and where they c... |
Passing pointers to legacy APIs.
Back-references in a reference-counted tree structure (or any cyclic situation, for that matter). This one is debatable, since you could use weak-refs.
Iterating over an array.
There are also many cases where you could use smart pointers but may not want to, e.g.:
Some small programs... |
2,593,288 | 2,593,470 | How to use C++ Boost's regex_iterator() | I am using Boost to match substrings in a string. Io iterate over the results, I need to use regex_iterator().
That is the only usage example I have found, but I do not understand the callback. Could someone give me an example uage of the function?
Let us assume that my input text is:
"Hello everybody this is a senten... | If the only part of the example you don't understand is the callback, consider that:
std::for_each(m1, m2, ®ex_callback);
is roughly equivalent to:
for (; m1 != m2; ++m1){
class_index[(*m1)[5].str() + (*m1)[6].str()] = (*m1).position(5);
}
Assuming that, in your case, you want to store all the matches in a vec... |
2,593,471 | 2,593,680 | Do classes which have a vector has a member have memory issues | I am just starting out C++, so sorry if this is a dumb question. I have a class Braid whose members are vectors. I have not written an assignment operator. When I do a lot of assignments to an object of the type Braid, I run into memory issues :-
0 0xb7daff89 in _int_malloc () from /lib/libc.so.6
#1 0xb7db2583 in ma... | Another problem :
while(depth > 1)
{
netscore += curr.evaluateMove(1,0,depth,b);
....
--depth;
}
causes endless recursion when depth >1
|
2,593,655 | 2,593,682 | Segfault when calling a method c++ | I am fairly new to c++ and I am a bit stumped by this problem. I am trying to assign a variable from a call to a method in another class but it always segfaults. My code compiles with no warnings and I have checked that all variables are correct in gdb but the function call itself seems to cause a segfault. The code I ... | From what I can see there's nothing wrong with the code you've displayed. However, segfaults often are a good indication that you've got corrupted memory. It's happening some place else besides what you've shown and only happens to impact the code here. I'd look any place you're dealing with arrays, pointers, or any... |
2,594,092 | 2,594,356 | How to set configuration properties in VS once and for all? | In VS 2010RC I have to specify configuration properties and specifically included path every time I'm creating new project. Is there a way to do it just once for all future projects?
I'm asking this for a reason that I'm starting to use Boost libraries and I have to specify all those paths every time I'm creating proje... | The VC++ Directories (which is what I think you're looking to configure) have been moved to a property sheet to make them more MSBuild-friendly.
A snippet from http://blogs.msdn.com/vsproject/archive/2009/07/07/vc-directories.aspx:
If you open up the Property Manager view to see the property sheets associated with y... |
2,594,114 | 2,595,640 | Using deprecated binders and C++0x lambdas | C++0x has deprecated the use of old binders such as bind1st and bind2nd in favor of generic std::bind. C++0x lambdas bind nicely with std::bind but they don't bind with classic bind1st and bind2nd because by default lambdas don't have nested typedefs such as argument_type, first_argument_type, second_argument_type, and... | Never tried to do such thing, and I don't have the time to provide a full answer, but I guess that something could be done with Boost.FunctionTypes.
Here's a rough, incomplete and untested draft to give you an idea:
template <typename T>
struct AdaptedAsUnary : T
{
namespace bft = boost::function_types;
namesp... |
2,594,151 | 2,595,268 | error: 'void Base::output()' is protected within this context | I'm confused about the errors generated by the following code.
In Derived::doStuff, I can access Base::output directly by calling it.
Why can't I create a pointer to output() in the same context that I can call output()?
(I thought protected / private governed whether you could use a name in a specific context, but app... | In short, it's "because the standard says so." Why? I don't know, I've emailed a couple of the standards guys, but haven't received a response, yet.
Specifically, 11.5.1 (from C++0x FCD):
An additional access check beyond
those described earlier in Clause 11
is applied when a non-static data
member or non-static... |
2,594,172 | 2,594,254 | invalid conversion from ‘char*’ to ‘char’ | I have a,
int main (int argc, char *argv[])
and one of the arguements im passing in is a char. It gives the error message in the title when i go to compile
How would i go about fixing this?
Regards
Paul
| When you pass command line parameters, they are all passed as strings, regardless of what types they may represent. If you pass "10" on the command line, you are actually passing the character array
{ '1', '0', '\0' }
not the integer 10.
If the parameter you want consists of a single character, you can always just ta... |
2,594,178 | 2,594,222 | Why do you need "extern C" for C++ callbacks to C functions? | I find such examples in Boost code.
namespace boost {
namespace {
extern "C" void *thread_proxy(void *f)
{
....
}
} // anonymous
void thread::thread_start(...)
{
...
pthread_create(something,0,&thread_proxy,something_else);
...
}
} // boost
Why do you actually... |
It is clear that the thread_proxy function is private internal and I do not expect that it would be mangled as "thread_proxy" because I actually do not need it mangled at all.
Regardless, it's still going to be mangled. (Had it not been extern "C") That's just how the compiler works. I agree it's conceivable a compil... |
2,594,423 | 2,594,614 | What's a good way to detect wrap-around in a fixed-width message counter? | I'm writing a client application to communicate with a server program via UDP. The client periodically makes requests for data and needs to use the most recent server response. The request message has a 16-bit unsigned counter field that is echoed by the server so I can pair requests with server responses.
Since it's... | If I understand things correctly, you may be able to use some windowing, if you are not already.
That is, do not accept an message that is outside your window. For example, if your counter is at 1000, you may limit your range of incoming counter IDs you will accept to 1000...1031 inclusive. Thus anything outside that... |
2,594,502 | 2,594,548 | Count white spaces to the left of a line in a text file using C++ | I am just trying to count the number of white spaces to the LEFT of a line from a text file.
I have been using
count( line.begin(), line.end(), ' ' );
but obviously that includes ALL white spaces to the left, in between words and to the right.
So basically what I'm wanting it to do is once it hits a non-space characte... | Assuming line is a std::string, how about:
#include <algorithm>
#include <cctype>
#include <functional>
std::string::const_iterator firstNonSpace = std::find_if(line.begin(), line.end(),
std::not1(std::ptr_fun<int,int>(isspace)));
int count = std::distance(line.begin(), firstNonSpace);
|
2,594,772 | 2,601,110 | Loading a RSA private key from memory using libxmlsec | I'm currently using libxmlsec into my C++ software and I try to load a RSA private key from memory. To do this, I searched trough the API and found this function.
It takes binary data, a size, a format string and several PEM-callback related parameters.
When I call the function, it just stucks, uses 100% of the CPU tim... | I changed the format of data to PEM, using the OpenSSL function PEM_write_bio_RSAPrivateKey() and changed the third argument to the call to xmlSecCryptoAppKeyLoadMemory() so it matches the new format.
The new code is:
d_xmlsec_dsig_context->signKey =
xmlSecCryptoAppKeyLoadMemory(
reinterpret_cast<const xmlSecByte*>... |
2,594,913 | 2,594,953 | Getting the fractional part of a float without using modf() | I'm developing for a platform without a math library, so I need to build my own tools. My current way of getting the fraction is to convert the float to fixed point (multiply with (float)0xFFFF, cast to int), get only the lower part (mask with 0xFFFF) and convert it back to a float again.
However, the imprecision is ki... | If I understand your question correctly, you just want the part after the decimal right? You don't need it actually in a fraction (integer numerator and denominator)?
So we have some number, say 3.14159 and we want to end up with just 0.14159. Assuming our number is stored in float f;, we can do this:
f = f-(long)f;
... |
2,595,634 | 2,595,649 | Idiomatic STL: Iterating over a list and inserting elements | I'm writing an algorithm that iterates over a list of points, calculates the distance between them and inserts additional points if the distance is too great. However I seem to be lacking the proper familiarity with STL to come up with an elegant solution. I'm hoping that I can learn something, so I'll just show you my... | Consider using adjacent_find to find an iterator position where the distance between consecutive elements is too large, then inserting pointsToInsert items.
http://www.sgi.com/tech/stl/adjacent_find.html
In addition, you could use generate with a functor to fill in the intermediate points.
http://www.sgi.com/tech/stl/g... |
2,595,701 | 2,595,734 | What is the role of asserts in C++ programs that have unit tests? | I've been adding unit tests to some legacy C++ code, and I've run into many scenarios where an assert inside a function will get tripped during a unit test run. A common idiom that I've run across is functions that take pointer arguments and immediately assert if the argument is NULL.
I could easily get around this by ... |
A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug.
This is a pretty fundamental point. Unit tests are not meant to replace assertions (which IMHO are a standard part of producing good quality code), they're meant to complement them.
Secondly, lets say you have a function Fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.