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
6,340,307
6,340,329
C++ place char in corresponding slot in array
I need to store a letter a-z char to its corresponding slot in a size 0 - 25 array in c++. What's the best way to do this without a lot of if statements?
You can determine character index the following way: int index = yourCharacter-'a'; And then use that index to store what you need
6,340,407
6,340,459
is there a way in c++ to inititialize an array of some class objects without defining the size first
I use code like this: const vector<filterStat> someArray={ {"Ana",1}, {"Bob",2}, {"Charlie",5}, }; static const int knElements=filterStats.size(); Ignore the kn prefix, it is my way of saying constant, size. I found it useful because I don;t have to change or calculate knElements when I change ...
A const vector is a perfectly good thing to have - your code is the right way to do things.
6,340,467
6,343,681
fwrite and fread between matlab and c/cpp
I am having problem when i save a single variable of 460 elements in MATLAB using fwrite and when i try to read in MATLAB its fine but trying to access same bin file using fread in Visual C gives fine result for the first 88 values or so but then it experience EOF or so such as it doesn't give the required result for ...
Windows, right? Files are by default open in text mode, and byte 26 is interpreted as EOF marker. Rewrite your fopen as fopen("r01.bin", "rb") to force opening the file in binary mode.
6,340,553
6,350,014
Concurrent Object Pool giving a boost::shared_ptr
I wanted to implement a concurrent object pool where in a shared_ptr is returned and explicitly returning it to the pool is not required. I basically allocated an array pushed shared_ptrs for it in a concurrent queue and implemented a custom deletor. Seems to work. Am I missing anything? #ifndef CONCURRENTOBJECTPOOL_H ...
There is a race between setting the _goingDown flag in the destructor of ConcurrentObjectPool and reading the flag in payBack(). It can lead to memory leaks. Actually, maybe it's better if you do not try to make the destructor safe to run concurrently with payBack(). It's not safe anyway, starting from the fact that th...
6,340,674
6,340,733
C++ calls the wrong function
I have this weird bug, where C++ calls the wrong function: So this bit of code get called: class FmeGrid { // .... virtual void saveGridParameters() const; virtual void setCellSignalValue(int row, int col, double double_value, const std::string& string_value); // .... } void EnfClientFram...
Most common causes for this are: Dirty build (i.e. interface changed, but objects that used those interfaces weren't rebuilt) Stack corruption (you overwrote something on the stack that's causing the wrong function to be called and/or the correct function with invalid arguments) Try fixing with a clean rebuild and i...
6,340,730
6,341,034
Directx mesh vertices problem
I use DirectX to create a boxmesh,and I want to get the vertices position in the mesh, but I find the 24 vertices are wrong! or is there any way to use the 24 vertices??? here is my code D3DXCreateBox(pd3dDevice,2,2,2,&g_model,NULL); DWORD size=g_model->GetNumVertices();g_model->GetVertexBuffer(&Points); Points->Lock...
Your vertex buffer contains normals as well as positions -- The odd vectors are the normals. Try: for(int i=0;i<size;i++) { D3DXVECTOR3 vertcle(v[2*i].x,v[2*i].y,v[2*i].z); Pos.push_back(vertcle); }
6,340,753
23,428,075
Poco HTTPServer connections still served after calling stop() and destructor
I am facing a problem using the Poco::HTTPServer. As descibed in the doc of TCPServer: After calling stop(), no new connections will be accepted and all queued connections will be discarded. Already served connections, however, will continue being served. Every connection is executed in its own thread. Although i...
This is actually a bug in the implementation of the stopAll() method. The listening socket is being shut down after closing the currently active connections, which allows the server to accept new connections in between, which in turn will not be closed and keep running. A workaround is to call HTTPServer::stop() and th...
6,340,775
6,341,930
How to use C++ optimization flags in SWIG?
I am creating a python module that is implemented in C++. I am using SWIG to create the interface. There are various ways to create the extension, I'm using the "preferred approach," which is via python's distutils and which is described here. The name of my module is "ParseEvents," and to compile it I run the follo...
The GCC doc explicitly says: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Optimize-Options.html If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. This means your code will be compiled with -O3 in effect, just as you want it. No need to bother for duplicate ...
6,340,986
6,341,158
Generating a C++ executable from a C# application
I have a WCF service accepting requests from our clients. After analyzing the request I need to generate (compile + link) C++ EXE. What is the best method to create an C++ EXE from a C# application??? 10x
I can only guess what it is you want, but I assume your requirements are something like: You run a WCF service on a server somewhere. Upon receiving a certain call, the service must output a (binary) executable, based on the parameters it receives. C++ should be used as the intermediate language. Let's look at what y...
6,341,023
6,341,327
How to pass address of objects created in a C# List to C++ dll?
I have been looking all over google to find some answers to my questions but do not quite understand what I have found. I have some objects which are created and stored in C# List after using System.IO to read some text files. After that, I want to send references (using const pointers) to each of these objects to the ...
First you need to change your interop signature to take a pointer (and thus making it unsafe). [DllImport("SimpleDLL")] public unsafe static extern void AddSimpleReference(SimpleClass* inSimple); Then, because the GC is free to move objects around in memory as it pleases, you will need to pin the object in memory for ...
6,341,131
6,341,229
Nothing is displayed in QGraphicsScene
I am trying to use the qgraphicsview qgraphicsitem to create a scene like a chess. I am following the Official example trying to create it, but there is nothing displaying. The code is pretty the same. At the first, I am wondering is my Cell class. So I just try to draw a rect. But there is nothing displaying. Below i...
Your QFrame does not "own" your QGraphicsView. So there is no reason for it to display the view inside it. Just replace graphicsView = new QGraphicsView; with : graphicsView = new QGraphicsView(this); And don't forget to resize the window, (or set in the code a minimum size) otherwise, you may think that it didn't w...
6,341,148
6,341,649
How to manually run message pump in C++
ORIGINAL QUESTION Our application uses CSocket which requires the message pump to be running in order for it to work. Currently it's not practical to change to another socket implementation, though that is where we'd like to end up at some point. The application is in Visual C++ (NOT managed). We currently launch the ...
My translated C++ code is below (not checked :) PS: Calling DLLStart, DLLStop in the same thread will be more reliable. A global variable holds threadID DWORD threadID = 0; In OnStart equivalent: CreateThread(0, 0, PumpThread, 0, 0, 0); In OnStop equivalent: PostThreadMessage(threadID, WM_QUIT, 0, 0); Thread routine...
6,341,446
6,341,674
Using static class members of the class being defined
Using static class members in a class is a common practice. consider the following definition: foo.h class foo { public: virtual ~foo(); protected: foo(); static foo ms_oFooStaticObject; } foo.cpp foo foo::ms_oFooStaticObject; foo::foo(){} foo::~foo(){} void main() { ...
@user797308: I assume you would have no problem if someone declared and defined a global variable named ms_oFooStaticObject. In other words, rather than defining foo foo::ms_oFooStaticObject; define foo ms_oFooStaticObject; (This would require the constructor was public, of course). Plain old vanilla global variables a...
6,341,595
6,347,049
Can I precisely time overlapped ReadFileEx operations?
I'm reading sector-aligned chunks from a file using ReadFileEx (opened with CreateFile and the FILE_FLAG_NO_BUFFERING flag), recording a start time before the call, and an end time in the completion routine (times from QueryPerformanceCounter). The size of my chunk reads is constant, regardless of the size of the overa...
TL;DR My question is, can I measure the actual time of the read operation, and not the time between calling ReadFileEx (which may not start the read straight away) and the completion routine? Probably not from user-mode code. There are too many variables outside your control. You don't know what seeking ma...
6,341,693
6,342,407
directory path error, am I doing it wrong
I have my .exe and three folders with it. in each folder is a .txt file that my program reads and some images to load. This was all working fine when everything was with the .exe but has stopped working now it is in folders. I think the problem is that in folder A there is A.txt that loads A.png which is working but A...
I'm not 100% sure as I cannot try it out myself at the minute, but try ./ (from .exe root) or ../ (up one level).
6,341,828
6,341,871
QT progress bar speed
Does QT provide any functions to control a progress bar's speed? For example, if I want it to increase by 1% every 1 second, is there any QT way to do it instead of using a loop and sleeping for 1 second between each value change?
You can use QTimeLine for this. The detailed description in the documentation gives an example of exactly what you want.
6,341,951
6,342,009
What's actually going on in this AnonymousClass(variable) declaration?
Trying to compile: class AnonymousClass { public: AnonymousClass(int x) { } }; int main() { int x; AnonymousClass(x); return 0; } generates errors from MSVC: foo.cpp(13) : error C2371: 'x' : redefinition; different basic types foo.cpp(12) : see declaration of 'x' foo.cpp(13) : error C251...
AnonymousClass(x); It defines a variable x of type AnonymousClass. That is why you're getting redefinition error, because x is already declared as int. The parentheses are superfluous. You can add even more braces like: AnonymousClass(x); AnonymousClass((x)); AnonymousClass(((x))); AnonymousClass((((x)))); //and so on...
6,342,220
6,342,744
Problem when calling template CUDA kernel
I've been trying to create template kernels but I'm been having some trouble calling them in my program. I have a Matrix<T> template class, and some methods defined inside it Matrix.h: template <typename T> class Matrix { ... void sum(Matrix<T>& m1, Matrix<T>& m2, Matrix<T>& sum); ... } #include "Matrix.cu...
So, it seems you do have a strange #include, leading to code getting compiled by the wrong compiler. Make a distinction between gpu headers and cpu headers by using .cu.h for cuda headers. Make sure only NVCC compiles .cu and .cu.h files. Cuda files should never be included in cpp files. The kernel and kernel call shou...
6,342,643
6,342,714
copying an array into a vector
I have written a small program: void showrecord() { char *a[]={ "O_BILLABLE_ACCOUNT","O_CUSTOMER_TYPE_INDICATOR", "O_A_PARTY_MSISDN_ID","O_A_PARTY_EQUIPMENT_NUMBER", "O_A_PARTY_IMSI","O_A_PARTY_LOCATION_INFO_CELL_ID", ... }; vector<std::stri...
Why 75? Change vector<std::string> fields(a,a+75); to vector<std::string> fields(a, a + sizeof a / sizeof *a); There's no arguably 'better' way to initialize your vector for C++03, but for C++0x you have access to a more convenient syntax, dispensing with the C array: std::vector<std::string> fields { "O_BILLABL...
6,343,285
6,343,397
How to dump nested maps in C++ for debugging purposes?
for debugging I need to dump the contents of nested maps. I tried to describe this in the following code: struct Foo { string name; }; typedef std::map<string, Foo> MapFoo; struct Bar { string name; MapFoo mapFoo; }; typedef std::map<string, Bar> MapBar; ... MapBar mapBar = init_mapBar(); cons...
Write a function: template <typename K, typename V, typename C> void Dump( const map <K,V,C> & m ) { typename map <K,V,C>::const_iterator it = m.begin(); while( it != m.end() ) { cout << it->first << " = " << it->second << endl; ++it; } } You can then say: if ( mapBar.end() != it ) { D...
6,343,337
10,232,277
GSOAP: Automatic Proxy configuration URL
How can I setup a GSOAP generated proxy client class to use an automatic HTTP proxy configuration URL? I know I can configure the HTTP proxy address like this: AnyWebServicePortBindingProxy _client; _client.proxy_host = "192.168.0.x"; // A valid network address. _client.proxy_port = 8080; _client.proxy_userid = "user...
A proxy configuration script is actually a javascript code that returns the proxy server address based on his needs. This was meant to work with web browsers that implement the necessary logic to parse the FindProxyForURL response. I don't think GSOAP is able to do the same thing without your interference. You must che...
6,344,241
6,354,538
How can you reach the same level of efficiency using gdb as you do with a visual debugger?
I know this is like heresy, but I simply can't see how using gdb can be more efficient, in daily debug use (not advanced dumping and logging debug), than a visual debugger. I come from a background of .Net (Love the environment hate the mentality) and over the past coupld of years moved to PHP & C++. I am now developin...
As for me, I always use gdb's TUI mode. From gdb manual: The gdb Text User Interface (TUI) is a terminal interface which uses the curses library to show the source file, the assembly output, the program registers and gdb commands in separate text windows. The TUI mode is supported only on platforms where a...
6,344,242
6,344,299
Object Comparison using if else | Operator Overloading
I have to compare(>,<,==) two class object based upon different criteria, explained below. class Student { int iRollNumber; int iSection; int iMarks; } I want to do comparison with iRollNumber, iSection, iMarks (Independently). I want to do comparison with iRollNumber, iSection (Combined). I want to do c...
Write named functions: int CompareR( const Student & a, const Student & b ); int CompareS( const Student & a, const Student & b ); int CompareM( const Student & a, const Student & b ); int CompareRS( const Student & a, const Student & b ); int CompareMS( const Student & a, const Student & b ); although the need to do ...
6,344,251
6,344,465
Repeated random number in a loop
A need to generatera random numbers between 0 and 1 for every different loop. for ( 1 to 10000) a call RandomKey function so as to generate different random numbers. But the problem is every iteration i get same numbers. RandomKey function is as follows: void RandomKey () { srand((unsigned)time(0)); for (int ...
(I'm restating the other suggestions here.) There are at least three things you should verify: Only call srand once in your program If srand is called more than once, or your program is run many times per second, then do not use time(0) to initialize srand. If each random number should only be 0 or 1, you should call ...
6,344,373
6,344,972
Consolidating functions for cleaner code?
Don't be turned off by the length...I don't think it's too difficult of a problem. Language: C++ Development Environment: Microsoft Visual C++ Libraries Used: MFC Problem: I am creating a large preference dialog with several "pages". Many of them require the user to specify a file path. Right now, the user will click o...
How about using CMFCEditBrowseCtrl or COXBrowseFileEdit (or other similar classes) instead of normal edit controls? These classes create edit boxes with a "browse" button which, when clicked, automatically opens a file selection dialog and set the selected file as the edit control text.
6,344,655
6,344,679
making a typedef local to a file or subclasses
I'm consolidating 2 programs into one, and in 2 different files (I have many files), I have a typedef with the same name, different types though. These types will be used in completely different parts of the program and will never talk to each other, or be used interachangely. I can of cause just do a search replace i...
You can encapsulate those typedef inside a namespace: namespace N1 { typedef int T; } namespace N2 { typedef int T; } And in whatever file you want to use first typedef simply declare: using namespace N1; same thing for the other one also.
6,344,884
6,345,322
What is difference b/w PRLock and PRRWLock
What is the difference b/w PRLock and PRRWLock provided by nspr library ?
I don't know anything about the library but the names suggest that one is a standard lock and the other is a reader/writer lock. The first always gives exclusive access, and the second allows multiple concurrent reads but exclusive writes. For example, pthreads api has pthread_mutex_lock/pthread_mutex_unlock and pthrea...
6,345,115
6,347,670
C++ double dispatch "extensible" without RTTI
Does anyone know a way to have double dispatch handled correctly in C++ without using RTTI and dynamic_cast<> and also a solution, in which the class hierarchy is extensible, that is the base class can be derived from further and its definition/implementation does not need to know about that? I suspect there is no way...
The first thing to realize is that double (or higher order) dispatch doesn't scale. With single dispatch, and n types, you need n functions; for double dispatch n^2, and so on. How you handle this problem partially determines how you handle double dispatch. One obvious solution is to limit the number of derived type...
6,346,074
6,346,645
Returning value from C++ into Obj-C?
I'm banging my head for a while with how to return a value from some C++ into Obj-C. Here are my files: XMLParsing.h #include <iostream> #include <libxml/xmlreader.h> #include <string> #include <stdlib.h> using namespace std; class XMLParsing { int i; public: int outputAnArray(); }; XMLParsing.cpp #include ...
The XMLParsing.cpp should be like: #include "XMLParsing.h" int XMLParsing::outputAnArray() { return 1; } Sorry for the late answer.
6,346,250
6,346,283
C++ dynamic type - overriding methods
Normal overriding would work this way: class Fruit { public: string color(); }; string Fruit::color() { return "Unkown"; }; class Apple : public Fruit { public: string color(); }; string Apple::color() { return "Green"; }; Now, you'ld call this like: Apple *apple = new Apple(); std::cout << apple->c...
Mark the function virtual in the base class. class Fruit { public: virtual string color(); };
6,346,581
6,350,348
Strange VC Linker Error LNK1107 that references link.exe
I am getting a really strange linker error appearing: link.exe : fatal error LNK1107: invalid or corrupt file: cannot read at 0x270 But this is strange, because usually the error message tells you what object is invalid or corrupt. In other words, typically this error message looks something like this: myDLL.dll : fat...
I figured out the problem! There is a nasty little ENVIRONMENT variable that the MSVC linker uses (described here) on Microsoft's MSDN page. It says: LINK, if defined, prepends arguments in the command line. My system had the environment variable LINK defined as STATIC by a recent application I installed. This caused ...
6,346,637
6,349,092
Append 1 to 32 bit numbers to a char buffer
I have a char* buffer, that I want to append integers of various bit sizes (between 1 and 32) to. Thus, I need a function: void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size); that can move an object of, say, 13 bits to the 470th bit position of buffer. I could of course shift the bit...
How about something like this: void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size) { int* int_buffer = reinterpret_cast<int*>(buffer); const int bits_per_int = 8 * sizeof(int); int current_int = bits_appended_so_far / bits_per_int; int current_offset = bits_appended_so_far...
6,346,678
6,346,731
How these names conflict is resolved in C++?
Say I have this physical structure: / +-- conflicttest | +-- A.cpp | +-- A.h | +-- main.cpp +-- libconflict | +-- conflict | | +-- A.h | | +-- B.h | +-- A.cpp | +-- B.cpp These are the sources of libconflict, take a deep breath: class B header in libconflict:...
You have violated the One Definition Rule. The compiler didn't complain because it is limited in the things it can detect when crossing translation unit boundaries.
6,346,791
6,346,964
What needs to be done to get a distributable program from Eclipse?
I’ve produced a C++ program in Eclipse running on Redhat, which compiles and runs fine through Eclipse. I thought that to run it separately to Eclipse you use the build artifact which is in the directory set via the project’s properties. However this executable doesn’t run (I know it’s an executable as I’ve set it to b...
You've more or less figure out the first error yourself. when you just run <filename> , it is not in your PATH environment variable, so you get "command not found". You have to give a full or relative path when to the program in order to run it, even if you're in the same directory as the program - you run it with ./<f...
6,346,996
6,347,492
How can I convert this method from C++ to C#?
Could someone explain how I'd write this to C#? //byte[] buffer is priavte in the class //it's for writing Packets (gameserver) void writeString(int location, std::string value, int length) { if (value.length() < length) { memcpy(&buffer[location], value.c_str(), value.length()); memset(&buffer[loca...
The exact answer to your question is this. This is a private method within a C# class (I also added the buffer byte array for clarity): byte[] buffer; private void writeString(int location, string value, int length) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); if ...
6,347,375
6,347,434
Matrix Arithmetic using Vectors in C++ causing segmentation faults
I'm having some issues passing vectors to functions. My concern is not with my logic itself, as if I need to adjust later I will. My program requirements state that I must have separate functions that build the matrices, print the final matrix, and ones to perform the desired mathematical operations. I'm not concerned ...
Your global definitions of row,col,matrix, ... is the problem. int row=0, col=0; vector<vector<int> > matrix(row, vector<int> (col) ); vector<vector<int> > matrix2(row, vector<int> (col) ); vector<vector<int> > matrix3(row, vector<int> (col) ); What's happening here is the following: row and col is now 0 and therefor...
6,347,637
6,347,668
I'm messing up my inheritance
So I've got a Piece class supposed to represent pieces on a board, from which I plan to have two other classes inheriting. I've gotten a lot of problems in doing so, however; here is the relevant code so far. /// /// PIECE CLASS HERE /// this is an abstract class from which Barrier and Pawn inherit. class Piece { pub...
The first error is caused by this: Barrier::Barrier(Space* initial) { Piece(initial); m_Circle = sf::Shape::Circle((float)m_X, (float)m_Y, (float)m_radius, sf::Color(255, 255, 255)); Move(initial); } Needs to look like: Barrier::Barrier(Space* initial) : Piece(initial) { m_Circle = sf::Shape::Circle((f...
6,348,142
6,348,225
Reading file in specific format
I have a rather simple C++-problem, but coming from a C-background I am not really aware of all the I/O capabilities of C++. So here is the problem: I have a simple .txt file with a specific format, the textfile looks like this: 123 points are stored in this file pointer number | x-coordinate | y-coordinate 0 1.12...
I'd probably do it just about like I would in C, just using iostreams: std::ifstream file("input.txt"); std::string ignore; int ignore2; int lines; double x, y; file >> lines; std::getline(ignore, file); // ignore the rest of the first line std::getline(ignore, file); // ignore the second line for (int i=0; i<li...
6,348,359
6,348,439
STL iterator wrapper
I would like to write wrapper for STL iterator. It should only change behavior of some methods... I see it like smth like this: template<***> class custom_iterator : public *** { T & iter; public: custom_iterator(T & iter) : iter(iter) {} // for example, behaviour that increments value T_val operator ...
Take a look at boost::transform_iterator. I think that's what you're trying to get at. Source code
6,348,447
6,348,474
Are conditional typedef's possible in C++?
this question is related to c++ there is a library which declares a class named Solver < TS,FS >. Solver is a member of another class Domain (written by me) now there are many Domains which have a member "int region" what i want to do is depending on the value of region, I want to make the solver accept different argum...
You can specialize a template for any region value. template<int region> struct Decider; template<> struct Decider<1> { typedef TSA TS; typedef FSA FS; }; template<> struct Decider<2> { typedef TSB TS; typedef FSB FS; };
6,348,537
6,348,576
C++ template types nested in a template class definition
I've a situation where there is a class definition that looks like this: template<class T> class Alpha< Bravo<T> > { .... }; I'm compiling with gnu g++ and the compiler is complaining that Alpha is, "is not a template". I've seen this same technique used in the library that Bravo was written in and Bravo is a template...
What you have there is a partial template specialization; however, any template specialization needs a primary template to specialize, and that you do not have. template<class T> class Alpha; template<class T> class Alpha<Bravo<T> > { // ... };
6,348,616
6,348,723
How do I get the value of an object from one window into another window's class with Qt Creator?
This seems like it should be a simple question. I have two QSpinBoxes in my MainWindow, with a push button beside them. The user first selects the dimensions of an array of checkboxes using these spin boxes, then clicks the push button. This pops up a new window with the array of checkboxes in it. The problem I am havi...
You have two problems: MainWindow::ui is private MainWindow::ui is not static, you need an actual instance of a MainWindow to reach it To solve one, you usually create accessor methods in the MainWindow (or whatever class it is that needs to export some of its state). To solve two, you need a pointer to your MainWind...
6,348,725
6,349,576
Static Initialization Fiasco - On Purpose
Just for fun, I was investigating the order of dynamic initialization of static objects. In a file name t.h, I put struct T { static std::vector<std::string> me; static int add(std::string s) { me.push_back(s); return me.size(); } }; (Plus needed headers for vector and string.) "std::vector T::me" is in t.cpp. T...
I've got it. Simple, really. T::me is zero initialized statically according to the rules of C++. There is a constructor, however, to run dynamically. There's no guarantee when that constructor runs. It is apparently - in this case - running after u is initialized.
6,348,742
6,368,414
Remove the defines in this safeguard mutex example
-edit- i cant experiment ATM but will tonight. I am thinking maybe a typedef can be used to hold mut and can be used to declare a var. But my initial thought is typedefs don't play nice with templates so i'll have to check later tonight (for now, to class) I was looking at this piece of code shown below and i was wonde...
You can use an explicit specialization containing using declarations to list the objects protected by the mutex. Then use a base class to "pass" the access out to the user via operator->, so object->member (with object not being a pointer) performs the mutex assertion. This is easier done than said: // Imagine that the...
6,348,868
6,349,589
How to stop recursion if nothing is inputed in cin?
I am writing a program that must print numbers at first which was entered at last. So here is my code: #include <iostream> using namespace std; void recursive() { long long n; if((cin>>n)&&(!cin.eof())) // Dont work because enter is ignored in cmd window os recursive(); cout<<n<<endl; retu...
As your program is right now it will read the long long's until cin's operator void* indicates that the value read was not compatible (but still prints the n , filled with garbage,that it failed to read), as you notice it ignores the blank lines. If I understand correctly, what you want is that when the user inputs a ...
6,349,299
6,404,173
Visual C++ .net: Disappearing project
This is a real newbie question: If I create a simple project in .NET, lets say at c:\project\test, and then change the directory name from project to say project2, when I try to open the .sln file my project will not open, I mean the .NET program opens and runs but nothing is there. If I change the directory name back...
Jorgen was right. It was a dumb question. Nothing disappeared. The answer is to find the moved project in the Solution Explorer and reload the project. Then everything works just fine.
6,349,322
6,349,359
How does std::vector copy objects to its internal storage
I have the following problem: void add(){ cRow Row(); Row.add("Column", "Value"); std::vector<cRow> mRows; mRows.push_back(Row); } cRow::cRow(): mCol(NULL), mVal(NULL) { } cRow::add(const char* Col, const char* Val){ mCol = strdup(Col); mVal = strdup(Val); } cRow::~cRow(){ free(mCol); free(mVal); } ...
std::vector uses the copy constructor to copy objects. Since you have not defined a copy constructor, it will use the implicit C++ copy constructor, which just copies all members recursively; this isn't enough, since you are manually managing memory. You need to either define your own copy constructor, or use something...
6,349,419
6,349,894
Is there are way to set the start frame for cvQueryFrame or cvGrabFrame?
Using OpenCV (HighGUI.h), I have this code in main: int frame_count = 0; while( (frame=cvQueryFrame(capture)) != NULL && (frame_count <= max_frame)) { //If the current frame is within the bouds min_frame and max_frame, write it to the new video, else do nothing if (frame_count >= min_frame){ ...
You can set the next frame to read by means of cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, min_frame); of course only for videos and not for cameras. The next frame read will be min_frame and the reading will go on normally from there (the frames after min_frame will be read) if you don't set the frame posit...
6,349,431
6,349,583
How to choose between some methods at runtime?
In order to make my code a bit clearer, I was trying to split a long piece of code into several methods (a little PHP-like). I have a variable CurrentStep indicating the current screen to be rendered. class Game { private: enum Step { Welcome = 0, Menu, }; unsigned int CurrentStep; } Now I want to call the cor...
I guess what you are looking for is the command pattern. Read this detailed explanation (for C++) http://www.dreamincode.net/forums/topic/38412-the-command-pattern-c/ to learn more about it.
6,349,616
6,349,700
Heap/Stack - Scope of variables going into QGraphicsItemGroup
If I have a QGraphicsItem that I want to put in a QGraphicsItemGroup, in a loop..like so: for(int i =0; i < 2; i++) { for(int j = 0; j < 2; j++) { QPixmap p(imwidth, imheight); p.fill(Qt::gray); QGraphicsPixmapItem *ipi = new QGraphicsPixmapItem(p); group->addToGroup(ipi); } ...
The addToGroup method takes a pointer, so you can't get away with passing it anything else. It doesn't copy the objects passed in, just stores that pointer. If you give it a pointer to stack-allocated objects, it will blow up sooner or later trying to access stack memory which will (probably) have been overwritten sinc...
6,349,748
6,349,882
C++ how to initialize?
add: I tried on the fun below anyone know what is the error? struct node { string info; node *link; node() { info = "string"; link = NULL; } }; void fun( node &node) { if (node.link !=NULL) { fun (node.link); } } I get an error message when I use it inside of my functions: invali...
You're trying to pass a pointer instead of an actual object reference. Simply dereference the pointer like this: void fun( node &node) { if (node.link !=NULL) { fun ( *(node.link) ); }
6,349,822
6,349,840
"Incomplete type" in class which has a member of the same type of the class itself
I have a class that should have a private member of the same class, something like: class A { private: A member; } But it tells me that member is an incomplete type. Why? It doesn't tell me incomplete type if I use a pointer, but I'd rather not use a pointer. Any help is appreciated
At the time you declare your member, you are still defining the A class, so the type A is still undefined. However, when you write A*, the compiler already knows that A stands for a class name, and so the type "pointer to A" is defined. That's why you can embed a pointer to the type your are defining. The same logic ap...
6,349,837
6,350,091
scanf() curious behaviour!
I recently stumbled upon a curious case(atleast for me, since I hadn't encountered this before)..Consider the simple code below:- int x; scanf("%d",&x); printf("%d",x); The above code takes a normal integer input and displays the result as expected.. Now, if I modify the above code to the following:- int x; scanf("%d ...
From http://beej.us/guide/bgc/output/html/multipage/scanf.html: The scanf() family of functions reads data from the console or from a FILE stream, parses it, and stores the results away in variables you provide in the argument list. The format string is very similar to that in printf() in that you can tell it to read ...
6,350,028
6,350,097
Up arrow based command history in console input (C++)
I am trying to build a console application that takes user input. I was able to use printf to keep the cursor in the same place, I could have used curses as well, but I can't get up-arrow command history to work. Any pointers ?
I think you want readline (www.gnu.org/software/readline/ which seems to now redirect to the maintainer site at http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html)
6,350,428
6,350,471
How do I use boost.lambda with boost.range to select from a container?
In C# with Linq, I would write: myContainer.Select(o => o.myMember); I'm not sure what the syntax should be for C++/lambda/range. I'm simply trying to adapt a container of some object type to a container of strings so that I can pass it to boost::algorithm::join. I tried something like: using namespace boost::adaptors...
operator. is not overloadable, thus it can never do anything sensible on a placeholder. Boost.Lambda (and Boost.Phoenix v1 and v2, which were based on Boost.Lambda) implements its own result_of protocol rather than the TR1 result_of protocol, so Boost.Lambda functors will not work with anything using boost::result_of ...
6,350,582
6,350,865
Using afx_msg in Qt with msvc2008 compiler
I'm working on a project in Qt with the msvc2008 compiler, as the title says. The sample code, which I'm trying to work from makes use of afx_maps, and as far as I can tell (I don't really have a clue how afx works), the code below means that when the message WM_PI_RAWDATA_READY is received (I have no idea where or how...
What about just doing what the error message said and #defineing the _AFXDLL preprocessor symbol. Depending on your build environtment you just need to add it to the complier command line as an argument (/D_AFXDLL, if I remember correctly). But when you're working with Qt you probably got a *.pro file anyway and can ju...
6,350,604
6,350,632
Remote Procedure Calls
I am doing a Software Engineering course in which different teams are building different prototype subsystems of a big system (different subsystem of F35 Lightning aircraft!). The problem is that teams can use different programming languages (like C++ and Java) depending upon what they are most comfortable in. However...
There are a couple of options beside XML-RPC. For a short bullet-point comparison, take a look at: http://michaeldehaan.net/2008/07/17/xmlrpc-vs-rest-vs-soap-vs-all-your-rpc-options/ If your exchange is more data-oriented, Protocol Buffers might be an alternative. Protocol Buffers are a way of encoding structured d...
6,350,638
6,350,777
Boost::regex_iterator constructor fails but make_regex_iterator function succeeds
std::string line; This throws std::runtime_error what(): Memory exhausted: regex_it = boost::sregex_iterator(line.begin(), line.end(), re); This works fine: regex_it = boost::make_regex_iterator(line, re); Does anyone know what is causing the difference in performance? The boost::regex lib is compiled on Linux in...
Try working with a regex_iterator<char const*> rather than a regex_iterator<std::string::const_iterator>. (Also, the way you're calling make_regex_iterator is unnecessarily verbose by a large measure.) Assuming line is a std::string, try this: regex_it = boost::make_regex_iterator(line.c_str(), re); or this: regex_it ...
6,350,753
6,360,443
Display a image in a MFC/C++ application using OpenCV
I would like to display in a MFC application, frames that I capture from an avi file with OpenCV (cvCaptureFromAVI function). I'm new to MFC but feel like I'm close to making it work. But instead of the frames being displayed in the picture box they are displayed in a new window. cvGetWindowName returns always a null v...
So I found something to make it work after long researches. The solution is to create the window and then insert it inside the picture box. I'm not sure it's good practice but I haven't found anything better for now. cvNamedWindow("IDC_STATIC_OUTPUT", 0); cvResizeWindow("IDC_STATIC_OUTPUT", 420, 240); HWND hWnd = (HW...
6,350,833
6,350,895
Cooperation between boost::asio and standard C socket interface
I'm currently working on a small project: there's a protocol for sending some strings via UDP implemented with standard C interface. Although it works pretty fine, I'd like to rewrite it with some more sophisticated C++ (consider it exercise). Currently it's something like that: A client wants that string so it sends t...
You're using formatted input, as though the data being sent were textual -- you need unformatted input. Read about the std::istream::read member function, as it's what you should be using rather than operator>>. Note that this would have been immediately obvious if you had been checking the stream state after each extr...
6,350,880
6,350,894
How to use a function in three different .cpp files
I have three .cpp files these are named MeshLoader.cpp, DynamicXMesh.cpp and StaticXMesh.cpp I have a function in the MeshLoader.cpp file named FindTexturePath and I want to call and use it in the DynamicXMesh.cpp and StaticXMesh.cpp files. I have included MeshLoader.cpp(#include "MeshLoader.cpp") file in boot XMesh f...
You need to create MeshLoader.h, and put something like this in it #ifndef INCLUDED_MESH_LOADER_H #define INCLUDED_MESH_LOADER_H char* FindTexturePath( char* TexturePath ,LPSTR FileNameToCombine); #endif And include that in your other cpp files. Each of the cpp files just need the declaration of FindTexturePath to ...
6,350,882
6,350,901
C++ return local object
Several co-workers and I are having a debate about what happens when a local variable (allocated on the stack) is returned from a C++ method. The following code works in a unit test, but I believe that is only because the unit test is lucky and doesn't attempt to reuse the memory on the stack used by obj. Does this w...
What happens is that the copy constructor gets called to make a copy of the local object, and that is what the caller receives. The compiler may eliminate the copy in a process called copy elision, but that's at the discretion of the compiler - you don't have much control over it. This pattern is capable of producing t...
6,351,213
6,351,242
capture variables inside of subclass?
I was wondering something like this is possible. Perhaps using templates and trickery? The only rule right now i'll enforce is you are NOT ALLOWED to use a constructor in the class bar (so you cannot pass in a reference or pointer to foo nor a). class Foo{ int a; public: struct Bar{ int barme(){ return ...
In C++ nested classes are just classes. It's not like Java where a nested class comes with an instance of the parent class along for the ride. Therefore, nothing like this is possible. You have to pass an instance of Foo to operate on inside Bar. (For example std::vector::iterator does not come with a std::vector -- it...
6,351,227
6,351,270
opening files on non-ANSI systems via old (non wchar) API functions
I'm writing some middleware that's driving me nuts. I'm looking for some I18N experts to help me out - this is all pretty new to me. Right now this is all in Windows, but it will have to work on Linux and Mac too, though I bet those will be easy. I have a system (that I can't touch) that will give me a string that's a...
Well, the correct way to fix this would be to fix the other API. Accepting only narrow, non-unicode filenames is simply broken behavior. But... you said you can't do that. You might be able to work around this by getting the short file name, which will not have any non ANSI characters, and passing that to the broken AP...
6,351,255
6,351,287
problem with find function in Vector of Structure in C++
I am trying to use the "find" function here. For that here's the code for the '==' operator. But I am getting a "too many parameters for this operator function" error at the word "operator". Can anyone kindly help me out ? Thanks. struct gr_log { string name; string category; string description; float cos...
A member operator only takes one argument: struct gr_log { string name; string category; string description; float cost; bool operator==(const gr_log& r) { return name == r.name; } }; Alternatively, you could write a friend operator: struct gr_log { string name; string category; s...
6,351,339
6,375,641
Show dialog from MFC DLL
I loaded the form but only buttons without functions HMODULE hModule = LoadLibrary(L"Tools.dll"); if (hModule != NULL) { AfxSetResourceHandle(hModule); CDialog dgl(MAKEINTRESOURCE(199), NULL); dgl.DoModal(); } so how I can load a full function of form and I don't have the DLL source code
This is possible only if you are sure that dialog class implementation is MFC based and the class is exported from Tools.dll. You can try inspect your .dll with Dependency Walker utility. Please note the compiler mangles constructor name. This is what I got for the following declaration. class __declspec(dllexport) Tes...
6,351,406
6,359,630
C++ Unit Testing: Stubs (not mocks)?
Just getting into Unit Testing with C++. It looks like I will need to write several stub classes as I go along. My understanding is there is a difference between Mocks and Stubs. Basically it seems Mocks are for when you are testing something happened on the object (e.g. verifying) while Stubs just facilitate your t...
I think the missing piece of the puzzle is that you don't have to set an expectation on a method and instead you can just set a default return value. Mocks All the discussion and examples in the "Google Mock for Dummies" is focused around setting expectations. Everything talks about using some code similar to the foll...
6,351,466
6,351,960
Manipulate Images in SFML using Pixel Arrays
Hey so i'm trying to make a function that takes in an image refrence and sf::IntRect (this has 4 ints representing the top,bottom,left, and right sides of a rectangle. this rectangle represents the part of the image being displayed, but does not actually cut off the pixels outside the rectangle) and then creates a new...
The usual way to store and access 2-dimensional images (or any 2-dimensional matrix with variable size), is to allocate a 1-dimensional array of suitable size (width * height, or (width + padding) * height), and calculate the index into the array "manually" (y * stride + x, where stride is width + padding). (I normally...
6,351,632
6,351,653
C++ pointer to a vector of objects, need to access attributes
I have a vector called actorVector which stores an array of objects of type actorManager. The actorManager class has a private attribute, which is also an object of type GLFrame. It has an accessor, getFrame(), which returns a pointer to the GLFrame object. I have passed a pointer of actorVector to a function, so its ...
Assuming MultMatrix takes an ActorManager by value or by reference (as opposed to by pointer), then you want this: modelViewMatrix.MultMatrix(*((*actorVector)[i].getFrame())); Note that the precedence rules mean that the above is equivalent to: modelViewMatrix.MultMatrix(*(*actorVector)[i].getFrame()); However, that'...
6,351,780
6,351,821
What data structures are commonly used for LRU caches and quickly locating objects?
I intended to implement a HashTable to locate objects quickly which is important for my application. However, I don't like the idea of scanning and potentially having to lock the entire table in order to locate which object was last accessed. Tables could be quite large. What data structures are commonly used to overc...
Linked lists are good for LRU caches. For indexed lookups inside the linked list (to move the entry to the most recently used end of the linked list), use a HashTable. The least recently used entry will always be last in the linked list.
6,352,014
6,352,031
If a Qt signal is emitted in the forest and noone is around to hear it, does it make a sound?
Sorry for the humorous phrasing of the question. I couldn't resist ;-) If I emit a signal that's not connected to a slot anywhere in the code, is there still a performance cost associated with that "emission". I'm not familiar with the mechanism via which Qt's signal/slots are implemented, so I apologize if this questi...
At least a small one. Qt at least needs to look into the signal's connected slot list (or something like this, not sure about that) until it sees that it doesn't have to call anything. But that performance hit should be negligable, considering that you're using such a high-level environment as Qt's signals and slots, a...
6,352,280
6,352,434
pthread create error in c++
Possible Duplicate: pthread Function from a Class I am getting an error ("Can not convert .....") and I think the third argument in the pthread_create call is wrong. I know the type of the third argument should be (void*)*(void *) but I am still getting an error. void ServerManager::Init(){ pthread_t thread; ...
To be portable the callback function must use the C ABI; extern "C" void* AcceptLoop(void*); class ServerManager { public: void Init(); private: friend void* AcceptLoop(void*); void* AcceptLoop(); // Implement this yourself pthread_t thread; }; void ServerManager::Init() { ...
6,352,317
6,352,570
Pointer Error Debugging Help
I am new to C++, and I am trying to program a replica of Pong using freeglut with Visual Studio 2010. My code was working fine until I made some revisions to it in order to make it more object oriented. When I ran it again, it worked a couple times, until I made some minor edit (to be honest, I can't remember what it w...
Use F5 to run the program with debugging in visual studio. When you get the error the debugger should place you right on the line with the illegal access. If it doesn't have source code for the location then check up the call stack. Cheers & hth.
6,352,606
6,357,686
Public member without inheritance
I have a base class which looks something like this: class Base { public: typedef std::shared_ptr<Base> ptr_t; typedef std::weak_ptr<Base> wptr_t; enum class Type { foo, bar, baz }; Type x; // ... }; I'd like those internal types to be public so that I can do stuff like Base::ptr_t my_ptr(new Base); and so...
Based on the answers of iammilind and Luc Danton, here's what I've come up with: class Base { private: // only 'BaseClass' is allowed to derive from Base Base() { } friend class BaseClass; public: typedef std::shared_ptr<Base> ptr_t; typedef std::weak_ptr<Base> wptr_t; enum class Type { foo, bar, baz }; ...
6,352,632
6,352,645
How to store void* in a stack c++ container
I'm using a library written in C and the library provides headers which only use void*. The library is used to create a kind of graph, which is stored inside the C data-base. The headers return void* to the nodes in the graph. To create the graph, I need to parse a stack of lets say node names. In parallel to the stack...
std::stack::pop() doesn't return the element removed. You have to read it with top() before popping it.
6,352,723
6,352,742
When is a semicolon after } mandated in c/c++?
if(...) { ... } It seems in the above case a ; is optional,when is a semicolon after } necessary in c/c++?
int a[2] = {1,2}, j = 5; When initialization of array or structure are done with {} all the subsequent variables are declared after ,. Edit: As you changed your question; ; is mandatory after the class, enum, initialization syntax declarations. class A {}; // same for `struct enum E {}; // enum class (c++0x) int a[...
6,352,771
6,353,102
In what languages are the C and C++ standard libraries written? Where is their source code?
I always wonder what language was the C/C++ runtime and standard library written in. At first I thought it is a casual C/C++ language, but to be able to talks with the machine I doubt C/C++ is enough. Therefore, I think it may be assembly language instead. If it is either C/C++ or asm language, then why don't I really ...
They are typically written in their host language, interoperating with the operating system API to obtain things that can't be obtained natively. Many features are written in pure language- for example, the containers & algorithms section of the C++ Standard library pretty much has to be written in C++. In fact, nearly...
6,352,793
6,382,712
Approach to developing an application across many Nokia devices
First off, greetings everyone and thank you for your interest in my question. I'm currently working at a mobile startup. Our product is a communication app for Android, iOS and BlackBerry devices and we're looking to expand onto some Nokia platforms. I don't know a lot about Symbian details as I've never actually progr...
There are STL implementations that are possible to use on Symbian. I was once part of a team hat used a C++ core (with STL) on Symbian devices ranging from S60v1 to S60v5 as well as UIQ, S80 and S90. The same core was also used on windows mobile. We used STLPort for the STL implementation, but I have been unable to f...
6,352,805
6,352,841
How do I close a thread safely?
pthread_create(&thread, NULL, AcceptLoop, (void *)this); I have declared like this and inside of the AcceptLoop function I have infinity while loop. I'd like to close this thread when the server is closed. I have read pthread_cancel and pthread_join but I am not sure which one is better and safer. I would like to...
I believe you would like to exit the worker thread by signalling from the main thread. Inside AcceptLoop instead of looping infinitiely you loop on a condition, you can set the condition through your main thread, You will have to use some synchronization for this variable. Once the variable is set from main thread the ...
6,352,989
6,391,970
Extract multiple IClass values from a registry key
I am trying to get the IClass values from registry key using RegQueryVaueEx and convert them to GUID for my application. I could do that for REG_SZ size, however, I am trying to figure out a way to do the same for IClass values with REG_MULTI_SZ that have more than one IClass. It doesn't seem to be straightforward as ...
Looks like the best way to achieve this is to open the registry key of the driver with RegOpenKeyEx and use RegEnumValue to get the IClass values (by passing IClass value name as parameter) in a loop (do-while) until RegEnumValue fails. Thanks all for the comments and suggestions.
6,353,054
6,353,116
What is `#pragma pack` for in network programming?
#pragma pack(push) #pragma pack(1) I downloaded a tutorial and it has these lines in the header file. I will appreciate if you guys can provide me any tutorials or references related to this.
Microsoft's explanation: http://msdn.microsoft.com/en-us/library/aa273913(v=vs.60).aspx IBM's AIX xlC explanation: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Fcompiler%2Fref%2Frnpgpack.htm Basically, it determines the byte boundaries that will be used when storing a...
6,353,104
6,353,132
how to Ensure exe launch using ShellExecuteEx
I have a EXE1 which requires an Config file when launched. I am using ShellExecuteEx to launch EXE1 from EXE2. It is working fine as such but the if the config file is not preset for EXE1 then it do not get launched however ShellExecuteEx returns TRUE(1) . I am checking the return value of ShellExecuteEx to Disable t...
You would have to signal from the second program into the first program in some way -- by using shared memory, mutants, or some other interprocess communication method. ShellExecuteEx only cares about whether the executable is able to start, not whether it's able to do what you expected it to. Alternately, use CreatePr...
6,353,149
6,353,169
Does vector::erase() on a vector of object pointers destroy the object itself?
I have a vector of pointers to objects. I need to remove an element from the vector and place that element in another list. I read that erase can be used to remove the object from the vector, but I also read that it calls the objects destructor before doing so. I need to know whether or not erasing the object will de...
vector::erase Removes from the vector container and calls its destructor but If the contained object is a pointer it doesnt take ownership of destroying it. You will have to explicitly call delete on each contained pointer to delete the content it is pointing to, for example: void clearVectorContents( std::vector <Yo...
6,353,249
6,366,292
Local version of Google Maps API
Do you guys know if there is a version of the Google Maps API for C++ which works using local maps rather than having to connect to a Google server? The application is the plotting of GPS positions in an area with no internet coverage. Thanks in advance.
As an alternative for Google Maps, you might want to have a look at OpenStreetMap. (See also the usage and software sections on Wikipedia)
6,353,320
11,636,658
How to create a video streaming httpserver?
I'm using c++ and poco libraries. I'm trying to implement a video streaming httpserver. Initially i used Poco::StreamCopier. But client failed to stream. Instead client is downloading the video. How can i make the server to send a streamresponse so that client can stream the video in browser instead of downloading?
While not within POCO, you could use ffmpeg. It has streaming servers for a number of video protocols and is written in C (which you could write POCO-like adapters for). http://ffmpeg.org/ffmpeg.html#rtp http://ffmpeg.org/ffmpeg.html#toc-Protocols http://git.videolan.org/?p=ffmpeg.git;a=tree And it has a pretty liberal...
6,353,515
6,353,592
How to load icons manually without using any resource editor?
I want to load an icon without the need of resource editors. Suppose I have the source files in the same directory as the icon files, how do I load and use it? BeginUpdateResource only update binary file that isn't currently running, while LoadIcon can only load icon file from resource inside the module. Therefore, how...
You could use LoadImage for that. You'd have to set the first parameter to NULL. Example: LoadImage(NULL, _T("youricon.ico"), IMAGE_ICON|LR_LOADFROMFILE, 0, 0, LR_DEFAULTSIZE);
6,353,825
6,489,178
stack traces stop before getting to my code (on Android using NDK)
I'm developing on Android 2.3.x using NDK r5b. Occasionally my code crashes and I'd like to know where. I already know how to get the corresponding line in my application when I have a have a pointer (i.e. from Android's stack traces.) However, oftentimes I see useless stack traces like this (full stack trace): #0...
Is there any way at all to get better stack traces than this? As far as I know, you must build and write the Android image by yourself. It enables you to have the whole complete symbols of the Android (executable files and shared libraries) except proprietary shared libraries. Building from source - Compile Cyanogen...
6,353,912
6,353,940
what is long long type?
Possible Duplicate: “long int”, “long long” Data Types I am a newbie of C++ and I looked at a sample code and I saw long long type. It says something like this long long deviceId; Is this same as long type? I am trying to send a device id from java(Android) to my server. In java, device id is long type(8byte) and ...
long long is not the same as long (although they can have the same size, e.g. in most 64-bit POSIX system). It is just guaranteed that a long long is at least as long as a long. In most platforms, a long long represents a 64-bit signed integer type. You could use long long to store the 8-byte value safely in most conve...
6,354,203
6,354,263
C++ function using reference as param error
struct node { string info; node *next; node() { info = "string"; next = NULL; } }; void insert(node &anode) { node newNode; anode.next = &newNode; } What is wrong with this implementation of insert for this structure ? How should I fix this? added: Very sorry that I wasn't clear. I know what is wr...
What's wrong is that newNode lives in the scope of the insert function. You probably want something like void insert(node &anode) { node* newNode = new node; anode.next = newNode; } but the parent node, or something else, then has to take care of the new node's lifetime. It now owns the next node. If you want the ca...
6,354,261
6,354,379
C++ Befriending boost::ptr_map / boost::checked_delete fails
I want to use a boost::ptr_map inside a specific class which stores instances of itself. However, please consider the following example: #include <boost/checked_delete.hpp> #include <boost/ptr_container/ptr_map.hpp> class foo { friend void boost::checked_delete<>(foo*); ~foo() {} }; int main() { boost::...
Here is the start of the huge error message* from GCC, which is the start of the chain of instantiations (usually, and in this case): In file included from main.cpp:1:0: main.cpp: In function 'void boost::checked_delete(T*) [with T = const foo]': Adding friend void boost::checked_delete<>(foo const*); makes the co...
6,354,358
6,354,764
C++ dll returned string is corrupted in the C# caller, why?
I have a C# app that calls a C++ DLL. In C#, I have code as follows: [DllImport(@"111.dll", CharSet = CharSet.Unicode)] public extern static String Func1(String arg); ...... String arg = "test text"; String retstring = Func1(arg); In CPP, I have the function defined as follows: extern "C" { __declspec(dllexport) LPWST...
I would always use a BSTR for this because it makes the responsibility of memory allocation/deallocation transparent. C++ #include <comutil.h> BSTR GetSomeText() { return ::SysAllocString(L"Greetings from the native world!"); } C# [DllImport(@"test.dll", CallingConvention = CallingConvention.Cdecl)] [return: Marsh...
6,354,386
6,354,430
Is it valid to use constexpr function as template argument?
constexpr int get () { return 5; } template<int N> struct Test {}; int main () { int a[get()]; // ok Test< get() > obj; // error:'int get()' cannot appear in a constant-expression } I have compiled this code with ideone. And was wondering that why it's giving compilation error. Is constexpr function not allowed...
GCC 4.5 (at least the version used at Ideone) does not entirely support constexpr, including your valid usage; it waters down to a const. GCC 4.6 and up correctly supports it.
6,354,449
6,354,558
Two dynamic_cast questions
Would you use dynamic cast in a frequently run method? Does it have a large overhead? What exactly IS the pointer returned by dynamic_cast. A pointer to the same address? a pointer to a different instance? I lack this understanding. More in specific - There's an assignment I wish to make to a pointer of a father type...
dynamic_cast helps you check the validity while performing downcasting. It returns a NULL or throws an exception(std::bad_cast for References)if the pointer or the reference cannot be safely downcasted. Would you use dynamic cast in a frequently run method? Does it have a large overhead? dynamic_cast does use some ad...
6,354,471
6,354,687
Running a program on a 64bit and 32bit system
Is there any reason why a c++ program that runs perfectly on a 64 bit system crashes on a 32 bit system? I have a program tested on 2 servers. one a 64bit and other 32bit. The program doesnt have bit specific commands. Initially it was working in both until i made a chage and added a structure and called it. The progra...
There's multiple things that could go wrong, and without a debugger it's going to be a nightmare to find out. Option 1: Convince whoever has admin rights to the server to install gdb. Option 2: Add print statements everywhere to figure out exactly which line the segfault occurs on a post it here (or try and figure it o...
6,354,567
6,355,617
Fill dynamic size vector recursively
Maybe let me state my situation in pseudo-C++-code first: std:vector<double> sample(someFunctor f, double lower, double upper) { double t = (lower + upper)/2; double newval = f(t); if (f(upper) - newval > epsilon) subsample1 = sample(f, t, upper); if (newval - f(lower) > epsilon) subsam...
Since space is not your major concern so I'll go on using the recursion. 1. Use copy by reference instead of copy by (return) value. 2. No need to pass in functor as it's constant. 3. It could have been faster if low and high are integers. It's depends on requirements though. // Thanks to Space_C0wb0y, here we avoi...
6,354,568
6,354,617
Boost: dereference a template argument if it's a pointer
What can I use to dereference a template argument if it's a pointer (or a smart pointer), or leave it as is if it's not? template<class T> void subf(const T& item) { item.foo(); } template<class T> void f(const T& item) { subf(magic_dereference_function(item)); } Anything in Boost is an option.
template <typename T> T& maybe_deref(T& x) { return x; } template <typename T> T& maybe_deref(T* x) { return *x; } You'll have to add overloads for smart pointers individually. There's no way to detected if a class is a "smart pointer". You could detect the presence of operator->, but that doesn't mean it's a smart p...
6,354,681
6,354,789
Flexible design to replace a switch statement
I am working on a networking program and designing a Linux server using C++. This is quite straightforward to design the basic structure. I have a packet definition with a header that has a fixed size. typedef enum{ PACKET_LOGIN_REQ = 1, PACKET_LOGIN_RES, PACKET_STORE_REQ, PACKET_STORE_RES }PACKET_...
You should use classes and instead of switch use a polymorphic call. Something like that (pseudo-codish): class Packet{ public: Packet(); virtual ~Packet(); virtual HandleMe()=0; protected: // fields } PacketTypeOne: public Packet{ public: virtual HandleMe(); // implementation for type 1 } PacketType2:...
6,354,756
6,354,859
How to convert A16B16G16R16F to ARGB32?
I'm writing a C++ program which reads a texture image file then convert and save as .png. When I met the ARGB half precision float pixel format. I tried for each pixel ARGB channel read 16 bits convert to 32bit c primitive float multiply 255 or 1 (i'm not sure what's the valid range of the half-float value) cast to a ...
The details of reading half floats are explained, including code, in a blog post here: http://fpmurphy.blogspot.com/2008/12/half-precision-floating-point-format_14.html After reading in your floats you will have to perform a tone mapping operation to get you values in the 0..255 ranged allowed for PNGs. This operations...
6,354,829
6,354,878
"xor eax, ebp" being used in C++ compiler output
I just tried compiling a couple of C++ snippets on VS2010 and analyzed the executables on IDA Pro. Something I noticed is that there most of them have something like the following at the start(shortly after a call to __security_check_cookie) xor eax, ebp and something like xor ecx, ebp at the bottom. Why does this happ...
These are buffer overrun protection methods, and have nothing to do with compiler optimisation. MSVC will (if you specify the /GS switch) push a security cookie onto the stack near the return address so that it can detect a common case of stack corruption. Stack corruption can either be caused by bad code along the lin...
6,354,839
6,355,417
Pointer being freed was not allocated problem with ALL objects!
I'm working (at least trying...) on a Cocoa application, which uses several custom Cocoa frameworks and one of these frameworks is a mix of C++ and Objective C++ (mostly C++) code... The problem is that each memory deallocation inside this framework gives me the Pointer being freed was not allocated error, even in the ...
Is there a chance, that one of these custom frameworks redefines new and/or delete? Try to add this replacements to your test program and look if a) the test program builds without complaining about multiple definitions of new and/or delete and b) it runs and shows a delete for every new? // not a real replacement, fo...