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 |
|---|---|---|---|---|
3,171,838 | 3,171,853 | How to use external cpp projects in a cpp project in Visual Studio 2008 | i m trying to make small test driven example by using cppunit. So i have 2 project which are test and normal library project. Whatever i do, i cannot be successfull. i got alltime LNK Error. Any help will be apreciated.
| Your test program needs to have a dependency on the library, so that it links against it.
In addition to this, you need to add the cppunit libraries as additional libraries, in the "properties -> linker -> input" section of the test program.
|
3,172,024 | 3,172,030 | A quick question on stack impl of C++ standard library | What does the line:
template<typename _Tp1, typename _Seq1>
friend bool
operator==(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
in http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a01367.html
do?
Why is _Tp1 repeated twice in arguements list?
Thanks,
| It declares the equality operator between two stacks a friend function of this class, which is necessary for it to access private members.
The const stack<_Tp1, _Seq1> appear twice because there are 2 arguments.
Of course it can be written as
bool operator==(const stack<_Tp1, _Seq1>& y) const { return c == y.c; }
but... |
3,172,026 | 3,195,635 | Qt setColumnWidth does not work | Have written the following code:
m_selectCategoryTableWidget = new QTableWidget;
m_selectCategoryTableWidget->setRowCount(0);
m_selectCategoryTableWidget->setColumnCount(2);
m_selectCategoryTableWidget->setHorizontalHeaderLabels(QStringList()<<tr("Category")<<tr("Number of items"));
m_selectCategoryTableWidget->vertic... | Well, Qt's logic is so, that after column resize, scroll bar area checks how columns fit into it. And if the sum of all columns' widths is less than the widget's visible width, then the last column gets resized to fill up the space leading to no visible result of calling setColumnWidth(). Actually two resizes happen - ... |
3,172,294 | 3,172,387 | What is the proper procedure on compiling templates and/or compiling with templates? | I have some template classes I've written that are dependencies for several other classes I need to compile. I have a few options as to how I can do this in my Makefile:
Each class that requires a template lists its template requirements. This has the drawback of needing to recreate the dependency tree every time I w... | As Neil Butterworth mentioned in a comment, make deals with files. Say you have a foo.cpp and a bar.h. The latter contains your template. And the former might do, for example:
#include "bar.h"
class Foo : public Bar<Widget> { [...] };
While your Foo class inherits and thus depends on your Bar template class, you are a... |
3,172,392 | 3,172,404 | Detecting user name from process ID | Ho can i get user account name, that ran the process with specified id. Is there any api function for this?
I am using windows,c++.
| There is not an API function that does this directly, however you can combine a few API calls to do this. Of course your program will need to satisfy any ACLs that are applied to the process that you are interested in examining.
First, given the process ID, you'll need to open a handle to the process. You can use OpenP... |
3,172,399 | 3,172,422 | can memory corruption be caused by invalid *reading* freed memory? | I'm getting
*** glibc detected *** (/my/program/...): malloc(): memory corruption: 0xf28000fa ***
I've run under valgrind, which reports cases of reading memory that has been freed, but no cases of illegal memory writes.
Could reading freed memory cause memory corruption? If not, any suggestions where else to look b... | You can use GDB to watch each write in this memory address, like this:
(gdb) watch *((int*)0xf28000fa)
Then you can debug where the problem is.
Reading doesn't cause memory corruption, but there are a lot of situations that you don't even imagine that could be the cause of this, and Valgrind is not a perfect tool.
See... |
3,172,415 | 3,172,630 | QComboBox and QSpinBox in QTableWidget with appropriate alignment | How to create a QTable widget which has 2 columnes, and in first column there is a QComboBox and in the second column there is a QSpinBox so that the combo box gets all the space of table and only a very small place leaves for QSpinBox (for 2-3 digits).
| First, use setCellWidget() to set the QComboBox and QSpinBox as the widgets to be displayed in the appropriate cell.
Second, use horizontalHeader() to access the QHeaderView for the QTableView, then set the ResizeMode accordingly.
QTableWidget* table = new QTableWidget( this );
table->setColumnCount( 2 );
table->setRow... |
3,172,418 | 3,172,453 | How to create a generic container with unknown member functions? | I noticed that I'm often in the need of a container class. For example when working on a particle system, I create a container class Particles which has a member vector<Particle*>. Then I call: Particles* my_particles like my_particles->draw(), and in the Particles.draw() I iterator over the vector<Particle*> and call ... | The short answer is that you can't do this in c++. You can, however, use STL algorithms and containers to wrap this behavior up.
First, you'd put your Cube or Particle instances into a std::vector or other container (like you have now).
Then you'd use STL's std::for_each in combination with std::mem_fun.
It'd result i... |
3,172,451 | 3,172,722 | Error handling for xml parsing | I'm using tinyxml to parse xml files, and I've found that error handling here lends itself to arrow code. Our error handling is simply reporting a message to a file.
Here is an example:
const TiXmlElement *objectType = dataRoot->FirstChildElement( "game_object" );
if ( objectType ) {
do {
const char *path... | Using return values as error codes just leads to such code, it can't be improved much. A slightly cleaner way would use goto to group all error handling into a single block and to decrease the nesting of blocks.
This does however not solve the actual problem, which is using return values as error codes. In C, there... |
3,172,549 | 3,172,557 | why macros return what we are not expected |
Possible Duplicate:
Problem with Macros
Hi all
I have defined this macro:
#define SQ(a) (a*a)
and called it in this way:
std::cout << SQ(2+3) << '\n';
the output was 11. Why ?
Thanks
| Macros do only simple text manipulation, i.e. they are very stupid that way in that they don't see 'code', only 'text' which are then sent to to the C/C++ parser for validation.
SQ(2+3) becomes (2+3*2+3)
That's why you should use templates, which are a bit smarter, they would do what you expected: first calculate 2+3, ... |
3,172,571 | 3,172,584 | Force a std::vector to free its memory? |
Possible Duplicates:
reduce the capacity of an stl vector
Is this normal behavior for a std::vector?
I know that std::vectors do not 'free' the memory when you call vector.clear(), but how can I do this? I want it to release all of its resources once I clear it but I don't want to destroy it.
Here is what is happe... | Use the swap trick:
#include <vector>
template <typename T>
void FreeAll( T & t ) {
T tmp;
t.swap( tmp );
}
int main() {
std::vector <int> v;
v.push_back( 1 );
FreeAll( v );
}
|
3,172,699 | 3,172,736 | Is this normal behavior for a std::vector? | I have a std::vector of a class called OGLSHAPE.
each shape has a vector of SHAPECONTOUR struct which has a vector of float and a vector of vector of double. it also has a vector of an outline struct which has a vector of float in it.
Initially, my program starts up using 8.7 MB of ram. I noticed that when I started fi... | Calling std::vector<>::clear() does not necessarily free all allocated memory (it depends on the implementation of the std::vector<>). This is often done for the purpose of optimization to avoid unnessecary memory allocations.
In order to really free the memory held by an instance just do:
template <typename T>
inline ... |
3,172,717 | 3,172,737 | How to start using xml with C++ | (Not sure if this should be CW or not, you're welcome to comment if you think it should be).
At my workplace, we have many many different file formats for all kinds of purposes. Most, if not all, of these file formats are just written in plain text, with no consistency. I'm only a student working part-time, and I have ... | Don't just use XML because it's XML.
Use XML because:
other applications (that only accept XML) are going to read your output
you have an hierarchical data structure that lends itself perfectly for XML
you want to transform the data to other formats using XSL (e.g. to HTML)
EDIT:
A nice personal experience:
Customer:... |
3,172,733 | 3,172,992 | Faster method for rendering anisotropic textures? | Is there any faster methods for improving texture quality on oblique angles than using anisotropic texture filter?
In my previous question i asked if it takes more memory than normal mip mapped textures, but apparently it doesnt, so i am hoping this could be optimized.
So is there any way to optimize the rendering spee... | No. The alternatives such as supersampling are significantly slower. Your best bet on OpenGL is using the anisotropic filter.
|
3,172,789 | 3,172,926 | C++/Qt enum - should I use locking to share the value across threads? | I have a C++/Qt QThread worker thread, which stores its current status as an ENUM (e.g. values such as Working, Finished). Only the worker thread sets the ENUM.
I need to be able to read the status of the worker thread from another thread (the GUI thread), to display on the screen whether work is being done.
Is it safe... | As Neil said: Yes, you need locking. For your use case QReadWriteLock should be better suited than QMutex.
|
3,172,805 | 3,172,974 | C++ Raii and stack unwinding | (I modified the original question to be more meaningful)
With respect to return statement, are Raii object destroyed before/after/between return statement?
for example
size_t advance() {
boost::lock_guard<boost::mutex> lock(mutex_);
return value_++; // is lock destroyed after increment?
}
thank you
| To answer your modified question, given the code:
return X;
X will always be evaluated before the return takes place. Then what happens is equivalent to all the nested scopes of the function being exited, in order from inmost to outmost, with destructors being called appropriately at each exit.
|
3,172,878 | 3,204,966 | How to open file\live stream with FFMPEG edit each frame with openCV and save that as encoded with FFMPEGfile\live stream? | How to open file\live stream with FFMPEG edit each frame with openCV and save that as encoded with FFMPEGfile\live stream?
| Well it is quite simple.
I suggest you begin with the simple ffmpeg decoding example. With that you get a struct which is an FFMPEG image. You have to convert it to an opencv image struct (IplImage). Then you can apply any opencv operation. Then you can look at FFMPEG encoding example and you have your whole processing... |
3,172,891 | 3,172,972 | How can I find a window with a specific window style? (WS_CHILDWINDOW) | I've got a specific window with the window style WS_CHILDWINDOW. It's the child window of a window of which I've got the handle already. This window is the second-last one. How do I get it?
It's C++ by the way.
| As an alternative to EnumChildWindows posted above, you can use this:
HWND first_child = GetWindow(parent_hwnd, GW_CHILD);
HWND last_child = GetWindow(first_child, GW_HWNDLAST);
HWND prev_to_last_child = GetWindow(last_child, GW_HWNDPREV);
A drawback of this approach is a possibility of a race if a new child window is... |
3,172,909 | 3,172,912 | How to use local classes with templates? | GCC doesn't seem to approve of instanciating templates with local classes:
template <typename T>
void f(T);
void g()
{
struct s {};
f(s()); // error: no matching function for call to 'f(g()::s)'
}
VC doesn't complain.
How should it be done?
| In C++03 it can't be done, C++0x will lift that restriction though.
C++03, §14.3.1/2:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
|
3,172,931 | 3,172,948 | C++ - Optional arguments by reference | I have an exam on C++ coming up, and I'm solving a few ones from past years. I have this question in one of them:
A function calculates the volume of a
prysm. Arguments passed are height,
depth and width. Arguments and return value are doubles
Depth is optional and
should default to 10.
Hypothesis 1:
All ... | I don't know if that is what the question was aiming at, but temporaries can be bound to const references:
double volume_prisma(const double& largura, ..., const double& depth = 10);
|
3,172,933 | 3,172,961 | How to manually cause a signal of another control to emit? | I wanted to know if its possible to emit some specific signal through coding .. For example, I want to emit another button's clicked event without the user actually clicking that button .. can do I do this ?
| You could call that other button's click function. It will emit the clicked signal.
|
3,173,012 | 3,173,126 | Performing an edge contraction on a graph | I am trying to do edge contraction on a graph.
n is the number of vertices in the graph.
The vector f containing pairs of vertices representing an edge contains the edges which are to be contracted.
The graph does not contain any self loops.
Please point out any logical mistakes if any in the code.
If the method is en... | Given the following example graph:
a d
\ /
b---e
/ \
c f
Would "contracting" the edge {b, e} result in the following?:
a d
\ /
g
/ \
c f
"Yes, it is exactly that" - amit. Thx, I wanted to get the specification right, before I answer Your question. Further assumptions are:
Graph is direc... |
3,173,088 | 3,173,232 | How to set all struct members to same value? | I have a struct:
struct something {
int a, b, c, d;
};
Is there some easy way to set all those a,b,c,d into some value without needing to type them separately:
something var = {-1,-1,-1,-1};
Theres still too much repetition (lets imagine the struct has 30 members...)
I've heard of "constructs" or something, but i... | This is my second answer for this question. The first did as you asked, but as the other commentors pointed out, it's not the proper way to do things and can get you into trouble down the line if you're not careful. Instead, here's how to write some useful constructors for your struct:
struct something {
int a, b... |
3,173,441 | 3,173,450 | Requirements for directly returning a class instance from a function? | I'm got a function in C++ that wraps an output stream constructor so it can pass in a pointer to a parent class that it's running in, ala:
pf_istream PF_Plugin::pf_open_in() {
return pf_istream(this);
}
When I do it that way, however, I get something like this:
pf_plugin.cc:103: error: no matching
function ... | > pf_istream::pf_istream(pf_istream&)
This is your problem. It's not properly finding your copy constructor, because it's passing a temporary. Your copy constructor should take a const&, like so:
pf_istream::pf_istream(const pf_istream&) { ... }
|
3,173,500 | 3,173,514 | creating a 2D array of vectors | I have been trying to create a 2D array of vector for a game. Here is an example of what I am doing.
struct TILE {
int a;
char b;
bool c;
};
TILE temp_tile;
std::vector<TILE> temp_vec_tile;
std::vector<std::vector<TILE>> tile;
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
temp_t... | You are not clearing the internal vector each time. Probably what you want is to put the internal vector declaration inside of the first for loop.
|
3,173,520 | 3,175,470 | nested class access control in C++ | Can inner class access a private member variable of its enclosing class? There seems to be some contradictions on the internet and compiler. Compile (g++ on cygwin) allows it. But, some technical documents say that it is not allowed.
| This issue has been addressed in Defect Report #10 and Defect Report #45.
The original and the current C++ language standard does not grant the nested class any extra access rights, i.e. it has no privileges when accessing members of the enclosing class. Nested classes are just ordinary completely independent classes,... |
3,173,603 | 3,173,617 | Implications of a const_cast in a copy constructor? | So I've got an output stream class that owns a pointer to a class that actually does the writing, and I need a copy constructor so that I can return initialized instances from a function so that I can bind certain values transparently to the user. To have reasonable copy semantics I'd really like to clear the writer p... | You would be violating the public contract of your object and the expectations of any client code by making your const copy constructor destructive.
Other than that, there's no problem with removing the constness of the parameter.
|
3,173,630 | 3,173,769 | Why does boost::asio appear to do nothing | I'm trying to implement the irc protocol in a very basic manner. My first attempt is to use boost::asio and connect to a server and read the motd. AFAIK the motd is sent to every client when they connect. I have made the following test program and it seems to not do anything. It's not a very good piece of code but this... | If you're making asychronous calls, you have to post requests to the io_service. In your case after the "x.connect();" you should call "ios.run();"
Just remember if you don't make any further posts after the async callback returns, run will exit/return.
btw in "ios.dispatch(boost::bind(onM, data));" is onM meant to be... |
3,173,668 | 3,173,684 | c++ container search by key and value | I'm trying to build a container of string representations of ordinal numbers, searchable both by the string and by the number. For example, I can do it trivially, but inefficiently, with an array:
std::string ordinalStrings = {"zeroth", "first", "second",..}
getting the string with ordinalStrings[number], and the inte... | You can provide two different lookup mechanisms using boost::multi_index (here's an example of a bidirectional map using multi_index). Another (maybe simpler) option is to maintain two containers: one to lookup by ordinal, one to search by string. You could use two std::map or a std::map and a std::vector (for consta... |
3,173,708 | 3,173,713 | Help identifying memory leak | I have a class here that is defined like this:
struct USERFPOINT
{
POINTFLOAT UserPoint;
POINTFLOAT LeftHandle;
POINTFLOAT RightHandle;
bool isBezier;
};
struct SHAPEOUTLINE {
GLuint OutlineVBO;
int OutlineSize;
int OutlineWidth;
ARGBCOLORF OutlineColor;
};
struct SHAPECONTOUR{
st... | If you've deleted everything, there is no leak, by definition. I don't see any unwrapped pointers, ergo everything gets deleted. Therefore, you have no leaks.
Likely, the OS has simply decided to leave that memory available to your program, for whatever reason. (It hasn't "reclaimed" it.) Or maybe it needs to allocate ... |
3,173,739 | 5,851,688 | File handle leak on dynamically loaded DLL caused by activation context | I have a dynamically loaded & unloaded DLL which requires COMCTL32.dll >= v6.0 and MSVCR >= v9.0. To ensure that the correct versions are loaded, I enable manifest file generation in Visual Studio project setting, and add this entry to another manifest file:
<dependency>
<dependentAssembly>
<assemblyIdentit... | The ProcessExplorer HANDLE leak reports are a symptom of an activation context leak. Most likely this leak is in your code indirectly in that you've not correctly called MFC.
To help yourself validate that this is your bug and not MFC's, you can create a simple MFC DLL from the AppWizard without any of your code and c... |
3,173,772 | 3,173,796 | C++ return value versus exception performance | Somewhere I have read that modern Intel processors have low-level hardware for implementing exceptions and most compilers take advantage of it, to the effect that exceptions become faster than returning results state using variables.
Is it true? are exceptions faster than variables as far as returning state/responding ... | I don't know where you read this, but it is surely incorrect. No hardware designer would make exceptional circumstances, which are by definition uncommon, work FASTER than normal ones. Also keep in mind that C, which according to TIOBE is the most popular systems language, does not even support exceptions. It seems EXT... |
3,173,902 | 3,174,570 | What is the difference between a .h(header file) and a .cpp file? | I am creating a windows:forms application. I have read some of the answers give to try to understand the concept of .h(header file) & .cpp(implementation files). As I created the GUI for my app. I noticed the code being placed in the .h file. But when I double clicked a button control to add code to the procedure, the ... | There are two considerations here. First off, header files are not nearly as important in managed code as they are in native C or C++. Managed code compilers read declarations from the assembly metadata, you don't (and shouldn't) write C++/CLI type declarations that need to be visible in other modules in header files... |
3,174,676 | 3,174,725 | Are there any predefined functions in Qt which save a QImage object to a JPG/PNG/BMP file? | Pretty simple question .. Are there any predefined functions in Qt which save a QImage object to a JPG/PNG/BMP file ?
| This is exactly what you'll need:
http://doc.qt.io/qt-5/qimage.html#reading-and-writing-image-files
Google is your friend, but more so are the Qt docs.
|
3,174,835 | 3,174,873 | Memory implementation of member functions in C++ | I read an article on virtual table in Wikipedia.
class B1
{
public:
void f0() {}
virtual void f1() {}
int int_in_b1;
};
class B2
{
public:
virtual void f2() {}
int int_in_b2;
};
used to derive the following class:
class D : public B1, public B2
{
public:
void d() {}
void f2() {} // override B2::f2()
... | Non-virtual member functions are implemented like global functions that accept a hidden this parameter. The compiler knows at compile time which method to call based on the inheritance tree, so there's no need for a runtime table.
|
3,175,055 | 3,175,229 | Integral promotion when passing and returning argument by reference? | I'm reading something about overload resolution and I found something that bothers me...In the following code:
int const& MaxValue(int const& a, int const& b)
{
return a > b ? a : b;
}
void SomeFunction()
{
short aShort1 = 3;
short aShort2 = 1;
int const & r2 = MaxValue(aShort1, aShort2); // integral p... | Short answer: it is unsafe.
The standard guarantees that a temporary variable can be bound to a constant reference in which case the lifespan of the temporary expands to the lifetime of the bound reference. The problem in your particular case is what reference is actually binding the temporary.
When you call MaxValue( ... |
3,175,111 | 3,175,144 | CURL is not following 301 Redirects, what do I need to do? | I am using the CURL c++ api to get quotes from Yahoo's financial API. The curl api and my code seem to be working fine, however I am getting a "301" redirect message when I tell CURL to visit the url I want. How can I get CURL to follow through to the 301 redirect and get the data I want?
Here is the URL I am using:
... | In the PHP world, the option is named CURLOPT_FOLLOWLOCATION. I assume the constant names are standardized and come from the same header file, so this should work for you.
curl_easy_setopt(eh, CURLOPT_FOLLOWLOCATION, 1);
(or whatever "boolean true" is in this context.)
Alternatively, when receiving a 30x status code,... |
3,175,159 | 3,175,227 | How do i make a some sort of istream for a vector of unsigned chars | how can i create an istream from a buffer unsigned char* or vector.
basically i want :
void Func(vector<unsigned char> data)
{
someSortOfIstream x (data);
x >> something;
}
using boost too....
| I would recommend:
use a std::string (a fancy vector of chars) instead of a std::vector<unsigned char>, because that's what it's for. You can then use the readily available std::stringstream in the <sstream> header.
You can subclass a std::vector<unsigned char> and overload the operator>>() for what you need it.
OR
(h... |
3,175,219 | 3,175,232 | Restrict C++ Template Parameter to Subclass | How can I force a template parameter T to be a subclass of a specific class Baseclass?
Something like this:
template <class T : Baseclass> void function(){
T *object = new T();
}
| In this case you can do:
template <class T> void function(){
Baseclass *object = new T();
}
This will not compile if T is not a subclass of Baseclass (or T is Baseclass).
|
3,175,295 | 3,247,258 | Outputting stl from multiple ellipse sources VTK | I currently have a small (I'm a complete beginner) project in VTK where I've used different vtkParametricFunctionSource objects and arranged them spatially. Now what I want to do is find a way to output all that data I'm currently rendering into a .stl file.
I don't know how I'd manage to convert my implicit parametri... | a vtkActor only modifies the rendered representation of the data. Because of this you cannot easily write it out using pre-existing vtk writers.
What you want to do is apply a vtkTransformFilter to each vtkParametricFunctionSource with the transformation matrix being equal to the vtkActor for that vtkParametricFunctio... |
3,175,437 | 3,175,875 | Virtual inheritance in C++ | I was reading the Wikipedia article on virtual inheritance. I followed the whole article but I could not really follow the last paragraph
This is implemented by providing
Mammal and WingedAnimal with a vtable
pointer (or "vpointer") since, e.g.,
the memory offset between the
beginning of a Mammal and of its
... | Sometimes, you just really need to see some code / diagrams :) Note that there is no mention of this implementation detail in the Standard.
First of all, let's see how to implement methods in C++:
struct Base
{
void foo();
};
This is similar to:
struct Base {};
void Base_foo(Base& b);
And in fact, when you look at... |
3,175,449 | 3,175,463 | C++ REG_SZ to char* and Reading HKLM without Elevated Permissions | So I've been trying to get a REG_SZ value out of the registry and store it as a char*. After looking around the internet this is what I came up with. The problem is that the value I get is not what is stored in the registry, I get a bunch of random garbage. How would I correctly get the value?
HKEY hKey;
char value[256... | (Updated, since previous answer was wrong.)
The problem may be that you're returing value, which is a stack-allocated buffer. This will work only if you declared your function as returning a char[256]--if you're trying to return a char*, then the caller is getting the address of the first byte in value, which is now po... |
3,175,632 | 3,175,671 | c++ pair template struct declaration ambiguity! | In definition of pair class in c++ there are two typedefs. what are they for? there are no use of them in the code!
template <class T1, class T2> struct pair
{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& x, const T2& y) : first(x)... | They are just here for you convenience, so you can use them in your code. C++ doesn't have a reflection model , so that's the only way you have "know" what types they are
Suppose you define your own pair
typedef pair MyPair;
Then you can use
MyPair::first_type
MyPair::second_type
for example,
MyPair::first_type... |
3,175,832 | 3,175,855 | Which of these is better practice? | Let's say I have a class FOO.
I want to have a std::vector of FOO.
Is it better if I do something like this:
FOO foo;
foo.init();
foo.prop = 1;
std::vector<FOO> myvec;
myvec.push_back(foo);
foo.prop = 2;
myvect.push_back(foo);
or is it better practice to do:
std::vector<FOO> myvec;
FOO foo;
myvec.push_back(foo);
myve... | Neither method has any memory issues as you're dealing with values and aren't dynamically allocating any objects manually.
I would favour giving FOO a constructor which does whatever init does and sets prop to the appropriate value. Then you can just push the values you want:
myvec.push_back(FOO(1));
myvec.push_back(FO... |
3,175,887 | 3,176,010 | Simple-iphone-image-processing source code question, what does this do | I am going through the source code for the above project and I don't understand the following lines of code can anyone help explain it to me please? I am trying to get the code to work with color images as it currently only works with greyscale images. I have the main methods working however the filters only get applie... | Image::initYptrs() initializes an array of pointers to the beginning of each row of the image.
The line in question should probably read
m_yptrs[i] = m_imageData + i*BPP*m_width;
Where BPP is bytes per pixel (e.g. 3 for RGB, 4 for RGBA images).
|
3,175,972 | 3,223,863 | STL container function return values | When looking over the member functions of the STL containers, an odd thought occurred to me. Why don't functions like std::vector<T>::push_back(T) not have an (optional) return value (iterator or even a reference to the appended object)? I know std::string functions like insert and erase return iterators, but that's fo... | Returning the added element, or the container in container member functions is not possible in a safe way. STL containers mostly provide the "strong guarantee". Returning the manipulated element or the container would make it impossible to provide the strong guarantee (it would only provide the "basic guarantee").
The ... |
3,176,004 | 3,176,076 | Object Oriented Design Problem, Liskov Substitution Principle | I'm making the design of a OO framework and I'm facing the following problem.
Let's say that in the framework I have a Shape interface and the users are free to implement and extends (adding new functions) the Shape interface to create their own figures, e.g. Square and Circle. To make these new objects available the u... | Unless your shapes have a common interface that must be used by the workers, this approach seems fully correct to me. A shape worker is more or less specialized on a specific shape, thus has knowledge about the class it handles. It would be nicer to do that using a common interface for all shapes but you cannot put eve... |
3,176,016 | 3,176,027 | Is quick sort followed by binary search faster than linear search? | Is it better to sort then binary search or simply linear search?
Thanks
| It depends how often you want to search after the sort - if only once, then a linear search will probably be faster. Of course, an even better bet is normally (but not always) to maintain things in sorted order using something like set or a map.
|
3,176,035 | 3,176,086 | Link the static versions of the Boost libraries using CMake | I've got both the static and the dynamic versions of the boost libraries in /usr/lib. Now I'd like CMake to prefer the static versions during the linkage of my executable. What can I do?
| In your CMakeLists.txt file:
set(Boost_USE_STATIC_LIBS ON)
find_package(Boost REQUIRED ...)
Where I have ..., you optionally put the names of the libraries you want to use, and then target_link_libraries(targetname ${Boost_LIBRARIES}) later below. If you have a fairly recent distribution of CMake, it should work exa... |
3,176,056 | 3,177,662 | Need advice in converting in one of the legacy C++ component into C# | Currently, we are working on a C++ legacy code base, which consists of several software components.
One of the components, are written in a way that is extremely difficult to maintain. (For example, memory allocation is done in X place, but memory de-allocation is done in Y place. This make memory management a painful ... | I am in a similar situation and I also did some experiments mixing C++ and C#. The problems in my application however were that:
the application is not clearly split up in different modules, making it hard to move specific modules from C++ to C#
the application is quite cpu-intensive and experiments revealed a big ov... |
3,176,110 | 3,189,661 | C++ FSM design and ownership | I would like to implement a FSM/"pushdown automaton" parser for this syntax: parser with scopes and conditionals which has already been "lexed" into Finite State Machine parser
I have the following:
class State
{
public:
virtual State* event( const string &token );
State* deleteDaughter();
private:
A* m_par... | Feel free to still post your take on this, but I have figured out how to handle everything gracefully:
First: my event loop will keep a pointer to the last State* created.
Second: Each State has a pointer to the parent State, initialized in the constructor, defaulting to 0 (memory leak if used for anything but the firs... |
3,176,114 | 3,177,923 | Under what circumstances will C++ fail to call an inherited class's constructor? | EDIT following resolution, this has been substantially edited to dump irrelevant detail and explain the real issue.
I found a problem recently in some old code. The particular code was only rarely used and had insufficient unit tests (I was adding some more when I spotted the problem). I only relatively recently stoppe... | The most important case is when it skips calling copy constructors entirely. This is a specific optimization that is allowed even in cases where the observable behavior changes.
Another case that catches some inexperienced developers is that unless specified otherwise, Derived::Derived(T) calls Base::Base() - not Base:... |
3,176,156 | 3,176,197 | How to use c++ std complex numbers in QtScript | I try to find out how to use complex numbers in QtScripts such that slots defined with complex arguments can be called from a QtScript. Also basic algebra (+,-,exp, ... ) of complex-numbers should be accessible to the user from the script.
Just for illustration want I want to call is:
#include<complex>
typedef complex<... | I think you must implement complex algebra in QtScript (something like http://examples.oreilly.com/9781565923928/text/8-6.txt) and then modify mySignal to accept an object like this.
|
3,176,204 | 3,176,231 | To code background process in Ruby or C++ for rails app? | I've been working on a rails app for a couple of days now that I need an underlying "middle layer" for that connects my rails application to the various services that make up the data.
The basic setup looks like this:
Frontend ("Rails app") -> user requests data to be aggregated -> info goes in database and a JSON req... | It depends. What are your data sources? Are they on the same machine? Are they databases?
My gut tells me that the language you choose won't play much of a role in how well this kind
of application performs, but it it hard to say without knowing the details.
C++ is probably a bad idea for a scalable web-app though. It ... |
3,176,518 | 3,176,531 | C/C++: Pointers within Const Struct | How do I force const-ness of the memory pointed to by obj->val1 in the function fn?
#include <iostream>
struct foo {
int* val1;
int* val2;
int* val3;
};
void fn( const foo* obj )
{
// I don't want to be able to change the integer that val1 points to
//obj->val1 = new int[20]; // I can't change ... | Since you tagged as C++, you could make the member private and make an accessor that returns a const int *. You could originally set the member via your constructor or a friend function.
|
3,176,612 | 3,176,694 | GlBufferDataARB is giving me memory issues | Basically I do something like this:
GenerateLinePoly(Contour[i].DrawingPoints, Contour[i].Outline.OutlineWidth);
Contour[i].Outline.OutlineSize = OutlineVec.size() / 2;
glBindBufferARB(GL_ARRAY_BUFFER_ARB,Contour[i].Outline.OutlineVBO);
glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * OutlineVec.size()... | Man page of glDeleteBuffers
It doesn't say anywhere that the memory should be released immediately. If it's not leaking (which is a driver bug), then i would say that what you're expecting is not happening. The GL implementation is free to do the real deallocation anytime it wants, specially if the resources are still ... |
3,176,621 | 3,176,658 | Is the unordered_map really unordered? | I am very confused by the name 'unordered_map'. The name suggests that the keys are not ordered at all. But I always thought they are ordered by their hash value. Or is that wrong (because the name implies that they are not ordered)?
Or to put it different: Is this
typedef map<K, V, HashComp<K> > HashMap;
with
templat... | In answer to your edited question, no those two snippets are not equivalent at all. std::map stores nodes in a tree structure, unordered_map stores them in a hashtable*.
Keys are not stored in order of their "hash value" because they're not stored in any order at all. They are instead stored in "buckets" where each buc... |
3,176,761 | 3,176,872 | usual hashtable implementation compared to tree | Usually (as in C++), the hash function returns any size_t value -- thus many different hash values are possible (2^32).
That is why I always thought that when people talked about them being implemented as tables, that is not really true in practice because the table would be much too big (2^32 entries). Of course my as... | Note that there are other ways to implement hash tables as Matthieu M points out. The remainder of this answer assumes that you want to use hashing with buckets made of some kind of list.
Assuming you are talking about time complexity.
Hash tables are expected to have O(1) best-case access. Your proposal for implemen... |
3,176,766 | 3,178,304 | BST preorder traversal and writing tree content to temporary array | I'm trying to write binary search tree's content to temporary array in order to use in main. However I'm not sure how to do it... I have tried something like this:
void Book::preorder(TreeNode *ptr, Person &temp[], int x)
{
if(ptr!=NULL)
{
temp[x].name=ptr->item.name;
x++;
preorder(ptr->left, temp, x);
preor... | void Book::preorder(TreeNode *ptr, Person temp[])
{
if(ptr!=NULL)
{
temp[globX].name=ptr->item.name;
temp[globX].phoneNumber=ptr->item.phoneNumber;
globX++;
preorder(ptr->left, temp);
preorder(ptr->right, temp);
}
}
is my final code. And i'm pretty sure that it work... |
3,176,788 | 3,176,829 | Why does the number of elements in an enumeration change the visibility of a private typedef in C++? | Sorry for the not very descriptive question title. I'm not very sure how to describe this, hopefully I can make it better later if someone can explain this to me.
I was about to come on here and ask why the following example was working. It was exhibiting the behaviour I was hoping for but I wasn't sure why or whether ... | I can verify your results about four vs. five enum elements... this looks like an obscure GCC bug.
As for "what's at work here", it's due to a technicality between different symbol namespaces in C++ (inherited from C). See this answer for more details.
If you don't want a symbol named BAR to be exposed, simply omit the... |
3,176,845 | 3,176,847 | Is calling base class constructor always necessary in C++? | Suppose I have some class C, and I inherit from it and name this class D. Do I always have to call C's default constructor as in this example:
class C {
public:
C() { ... }
};
class D {
public:
D() : C() { ... }
};
Note that C has only the default constructor. Do I have to call it from D? I co... | You don't need to specify the base class constructor in your derived type constructor's initializer list. When it is omitted an attempt will be made to call the base constructor with no parameters. If no such parameterless base constructor exists, then you'll get a compiling error.
|
3,176,867 | 3,176,883 | What do I do if constructor fails to allocate memory in C++? | I just came across a problem where the constructor of a class needs to allocate memory. So I happily wrote char *mem = static_cast<char*>(malloc(100*sizeof(*mem)));. But then I suddenly realized that in case of error I can't return error code (I am not using exceptions in my code). How can I solve this problem?
Should ... | You should use new, not malloc. new throws std::bad_alloc when you are out of memory. An exception should be propagated from the constructor if you fail to allocate (or for any other reason have a problem with initialization), as this is the only way you prevent the destructor from being called. If the constructor succ... |
3,176,899 | 3,176,924 | Do access modifiers work for static class functions? | I just came across code that had protected static class functions, as in:
class C {
...
protected:
static int fun() { ... }
};
I got curious if static class functions could have access modifiers and what would it mean? Since they are class globals and not pre-instance.
Thanks, Boda Cydo.
| Access modifiers in C++ do not work per-instance. They always work per-class. That is how it's always been. Which makes it perfectly logical to have them apply to static members as well.
It is a rather popular misconception that access protection in C++ is somehow supposed to work per-instance, which seems to be what i... |
3,176,937 | 3,176,946 | What are the most common uses of static class functions in C++? | I am learning today about static class functions in C++ and I can't really understand what are they good for? Does anyone have some good examples where they can be applied successfully?
Thanks, Boda Cydo.
| Static member functions of a class are just ordinary (non-member) functions. You do know what ordinary functions are good for, do you? So, static member functions are good for the same things for the same reasons.
It is just that sometimes an ordinary function has a tight relationship with the class, so it makes sense ... |
3,176,989 | 3,177,006 | How does one rename a variable midway through a block? | In C++, how does one rename a variable midway through a block? References and macros feel wrong.
| You can't.
But you can make a reference to it and access it under different "name".
If you really don't like the variable, just go out of current block, return from the function, leave the block.
|
3,177,028 | 3,177,035 | Can I throw C++ exceptions from legacy C callbacks? | I have C++ code that uses some C libraries. The C libraries take C language callbacks. I wrote a callback in my C++ code and now I somehow need to report error from it (but it returns void). I wonder if I can throw an exception from a C callback that is used from C++ code?
This is very difficult for me to understand.
T... | Yes, you should be able to do so. However, keep in mind it's entirely likely that the C library was not written to be exception safe, and as a result you might leave some of that library's structures in some inconsistent state. It depends entirely on the specific library and on the specific callback function. If nothin... |
3,177,032 | 3,177,062 | segmentation fault when i access member variables using a callback function | I have a class, in which i declare a static function. I register this function as the callback function for another library. Now, inside this function, i dereference the callback data to the class pointer and invoke a particular non-static member.
The invocation succeeds and the control comes into the non-static member... | The ptr passed to callackwrapper is most likely an invalid pointer or not an object of the class test. The invocation still succeeds because as long as you don't access a member variable, a class method is the same as a normal C++ function. Where you access count is when you actually dereference the object, hence the s... |
3,177,141 | 3,299,459 | What is the best free/paid C++ Video Training resource out there? | I'm a .NET Developer, primarily using c#, asp.net mvc, entity framework and programming for the Web. I want to know what you guys recommend to get a quick startup in learning c++. My biggest worries are pointers, memory management and other languages differences between managed and native languages. I want to know if t... | XoaX.net best video resource I've found so far. I Suggest you guys take a look.
|
3,177,227 | 3,178,090 | Templates, Circular Dependencies, Methods, oh my! | Background: I am working on a framework that generates C++ code based on an existing Java class model. For this reason I cannot change the circular dependency mentioned below.
Given:
A Parent-Child class relationship
Parent contains a list of Children
Users must be able to look up the list element type at run-time
I'... | The error is due to the Child class not being present when the template is instantiated.
Add the following either to Main or at the end of Parent.h:
#include "Child.h"
This compiles fine with both g++ 4 and VS 2010.
|
3,177,241 | 3,177,252 | What is the best way to concatenate two vectors? | I'm using multitreading and want to merge the results. For example:
std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;
I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?
| AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );
|
3,177,268 | 3,353,074 | Generating word documents (.doc/.odt) through C++/Qt | I am using Qt 4.5.3 and Windows XP. I need my application to generate documents that contains the information that is being used and generated. The information that is being used will be just strings (QString to be more specific) and the information that is being generated will be strings and images as well.
I want doc... | I have done this through the Qt way. i.e by using ActiveQt module.
The reference documentation for MS Word can be obtained through,
MSDN documentation, which actually pointed to the VBAWD10.chm file that has the ActiveX apis for MS Word.
The Word Application can be initialized by
QAxWidget wordApplication("Word.Applica... |
3,177,302 | 3,177,309 | Is it safe for multiple threads to call the same function? | Is it safe to for example do:
void AddTwo(int &num)
{
num +=2;
}
void ThreadProc(lpvoid arg)
{
AddTwo((int)arg);
}
Would it be safe for this to occur if 4 threads were doing this at the same time? Thanks
| The function itself is safe to call. It becomes dangerous if they're all trying to operate on the same variable.
|
3,177,319 | 3,177,488 | set GLOBAL clipboard text in windows, native c++ | I have an ASCII string (A null terminated char array)
in a console app.
all I want to do is make it so my app will put this string into the "global clipboard"
so that after running it, I can ctrl+v in any standard app (in this case, visual studio) and my string will be pasted!
how do I do this?
I have done:
void SetCli... | How to Set text on clipboard
CString source;
//put your text in source
if(OpenClipboard())
{
HGLOBAL clipbuffer;
char * buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, LPCSTR(source));
GlobalUnlo... |
3,177,552 | 3,359,463 | MS Word/ ODF Automation in Qt | How can I perform automation of MS Word documents (.doc) or ODF documents (.odt) in Qt 4.5? I know using the QAxWidget, QAxObject.
I have data (QString) and few images as well. I have to add them into the document. I googled but I couldn't find any commands for MS- Word/ ODF. But I want the specific commands that shou... | The ActiveX commands related to the MS Word can be obtained by the VBAWD10.chm that is being installed along with MS - Word.
The details of the ActiveX help documents available can be obtained here.
The toughest part is to conform those in such a way that it can accessed through the ActiveQt Module.
I provided a simila... |
3,177,584 | 3,177,626 | C/C++: How to figure out the chain of header files for a given definition? | In Visual C++, one can find the header file where any name (variable or type) is defined by pressing F12 on it or choosing Go to Definition. This feature is very useful, but it only shows the final location (header file) where the name is defined. Is there a way to figure out the chain of header files that lead from my... |
Right click project, "Project Properties"
"Configuration Properties" -> "C/C++" -> "Advanced".
Set "Show Includes" to "Yes".
The complete hierarchy of headers will be printed out in the output window when you compile every file.
|
3,177,686 | 3,177,723 | how to implement is_pointer? | I want to implement is_pointer. I want something like this:
template <typename T >
bool is_pointer( T t )
{
// implementation
} // return true or false
int a;
char *c;
SomeClass sc;
someAnotherClass *sac;
is_pointer( a ); // return false
is_pointer( c ); // return true
is_pointer( sc ); // return false
is_point... | template <typename T>
struct is_pointer_type
{
enum { value = false };
};
template <typename T>
struct is_pointer_type<T*>
{
enum { value = true };
};
template <typename T>
bool is_pointer(const T&)
{
return is_pointer_type<T>::value;
}
Johannes noted:
This is actually missing specializations for T *con... |
3,177,842 | 3,177,884 | why append Slot doesn't work? | I have got a problem when I try to make following simple connections
QSpinBox *spinBox = new QSpinBox;
QSlider *slider = new QSlider(Qt::Horizontal);
QTextEdit *text = new QTextEdit("Hello QT!");
QObject::connect(spinBox, SIGNAL(valueChanged(int)),slider, SLOT(setValue(int)));
QObject::connect(slider, SIGNAL(valueChan... | Unfortunately, you cannot pass custom values to your slots via QObject::connect (only type information for the arguments is allowed/interpreted correctly). Instead, create your own slot, something like
void MyWidget::mySliderChangedSlot(int newValue)
{
text->append("slider changed!");
}
and use
QObject::connect(sli... |
3,177,850 | 3,177,924 | problem splitting a string | Can some one please tell me the problem with this code. I am reading each line using getline function and again using the same function for splitting the string for : delimiter.
string line,item;
ifstream myfile("hello.txt");
if(myfile.is_open()) {
string delim =":";
while(!myfile.eof()) {
vector<string>... | Use char delim = ':'; and I also suggest using istringstream instead of stringstream. Also, the loop is wrong:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
...
char delim = ':';
while (std::getline(myfile,line))
{
vector<string> tokens;
istringstream iss(line);
while(st... |
3,177,875 | 3,177,916 | Member function hidden in derived class | Please look at the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {};
virtual void foo(double d) { cout << d << endl; }
virtual void foo(double d, int a) = 0;
};
class B : public A {
public:
B() {};
virtual void foo(double d, int a) { cout << d << endl <<... | The hiding rule is not about overriding, it is about hiding of names. If the derived class declares a member function, this hides other base class member functions with the same name. This also happens in your case.
|
3,178,126 | 3,178,221 | What's the cleanest implementation of this container of typed containers? | I have different types, say A, B, C, that all inherit from some base class Base:
class Base { ... };
class A : public Base { ... };
class B : public Base { ... };
class C : public Base { ... };
I need a container, let's call it Master, that holds pointers to objects of types A, B and C. I want the Master container to ... | Here's a sketch of what I would do:
// Beware, brain-compiled code ahead
template< typename T >
class typed_container
{
typedef std::vector<T> data_t;
public:
typedef data_t::iterator iterator;
iterator begin() {return data_.begin();}
iterator end () {return data_.end();}
private:
data_t data_;
};
typedef ... |
3,178,165 | 3,207,143 | How to use python build script with teamcity CI? | I am currently researching using the TeamCity CI software for our comapanies CI automation needs but have had trouble finding information about using different build scripts with TeamCity. We have C++ projects that need to have build/test automation and we currently have licenses for TeamCity. I have looked into using ... | We use TeamCity to run our acceptance test suite (which uses Robot Framework - done in python).
Getting it to run was as simple as wrapping the python call with a very simple NAnt script. It does 2 things:
Uses an exec task to run python with the script as an argument.
Gets the xml output from the build and transforms... |
3,178,281 | 3,178,401 | Manage mapped memory (glMapBuffer) with std::vector | it occurred to me that it would be a good idea to manage a range of mapped memory (from glMapBuffer) with a std::vector.
// map data to ptr
T* dataPtr = (T*)glMapBuffer(this->target, access);
[... debug code ...]
// try to construct a std::vector from dataPtr
T* dataPtrLast = dataPtr + size;
mappedVector = new std::v... | No, and for good reason. This code would never work. For example, you could alter the MapBuffer and break the size/capacity values inside the vector. You could push into the vector and cause an access violation/segmentation fault. You could cause a resize, destroying the buffer. And, fundamentally, if it's already with... |
3,178,309 | 3,178,345 | How to create a correct hierarchy of objects in C++ | I'm building an hierarchy of objects that wrap primitive types, e.g integers, booleans, floats etc, as well as container types like vectors, maps and sets. I'm trying to (be able to) build an arbitrary hierarchy of objects, and be able to set/get their values with ease. This hierarchy will be passed to another class (n... | Take a look at boost::any and boost::variant for existing solutions. The closest to what you propose is boost::any, and the code is simple enough to read and understand even if you want to build your own solution for learning purposes --if you need the code, don't reinvent the wheel, use boost::any.
|
3,178,342 | 3,206,195 | Compiling a C++ program with GCC | How can I compile a C++ program with the GCC compiler?
File info.c
#include<iostream>
using std::cout;
using std::endl;
int main()
{
#ifdef __cplusplus
cout << "C++ compiler in use and version is " << __cplusplus << endl;
#endif
cout <<"Version is " << __STDC_VERSION__ << endl;
cout << "Hi" << __FILE__ ... | gcc can actually compile C++ code just fine. The errors you received are linker errors, not compiler errors.
Odds are that if you change the compilation line to be this:
gcc info.C -lstdc++
which makes it link to the standard C++ library, then it will work just fine.
However, you should just make your life easier and ... |
3,178,478 | 3,178,483 | When do I have to declare a function used in a template? | I've got (probably) a simple question.
When do I have to declare a function used in a template?
The following code prints out (using gcc >=4.1):
init my A object
no init
Using gcc 4.0 the following code prints out:
init my A object
init my string object
#include <iostream>
#include <string>
template<typename T>
vo... | Functions at the instantiation point are looked up only using argument dependent lookup (looking up functions in the namespaces associated with a function argument). Normal lookup is only done at the point of the template definition.
So for std::string, only the generic init function template is visible and called, si... |
3,178,651 | 3,178,661 | Critique this c++ code | Similar to the code written below exists in production. Could you people review it and tell me if such code works well all the time.
class Base
{
public:
virtual void process() = 0;
};
class ProductA : public Base
{
public:
void process()
{
// some implementation.
doSomething()... | With good design you wouldn't need a dynamic_cast. If process() can't be called without calling setSomething() first they should have been exposed in the same base class.
|
3,178,739 | 28,086,658 | Invoking MSVC compiler from VS extension | Is it possible to invoke cl.exe, the MSVC++ compiler, from inside a Visual Studio extension? I'm using VS2010 and not bothered about maintaining compatibility for 2008/2005. I've hunted through MSDN and had a poke through my DTE object, but not found anything of use. The documentation on what you can do with this stuff... | You certainly can invoke cl.exe from the normal command line if you simply set up the appropriate environment variables.
|
3,178,877 | 3,181,637 | Multiple application entry points | Recently I was trying to add unit tests to an existing binary by creating a extra (DLLMain) entry point to an application that already has a main entry point (it is a console exe). The application seemed to compile correctly although I was unable to use it as a DLL from my python unit test framework, all attempts to us... | There are some problems which you should solve to implement what you want:
The exe must have relocation table (use linker switch /FIXED:NO)
The exe must exports at least one function - it's clear how to do this.
I recommend use DUMPBIN.EXE with no some switches (/headers, /exports and without switches) to examine the... |
3,178,928 | 3,178,978 | uvaoj 208 how can i speed up my program | why my program Time Limited Error?
because of the sort?
this is the question
link text
#include <cstdio>
#include <cstring>
using namespace std;
int map[22][44];
int book[22];
int total;
int sum;
int way[22];
int tails[22];
int tail;
void init()
{
memset(map,0,sizeof(map));
memset(book,0,sizeof(book));
sum =0;
... | Because your sorting algoritm is in worst-case O(n*n), you can use InnoSort for better worst-case complexity O(n*log(n)).
You are using C++ then use sort function from <algorithm> header to do this simplest.
Documentation you can find at http://www.sgi.com/tech/stl/sort.html
|
3,178,946 | 3,178,962 | Using #define to include another file in C++/C | I want to define a macro which includes another header file like so:
#define MY_MACRO (text) #include "__FILE__##_inline.inl"
So that when the preprocessor parses file person.h, MY_MACRO(blahblah) expands to
#include "person.h.inline.inl"
any hints on how to do this ?
| It's not possible to use #define to construct other preprocessor directives, unless you run the preprocessor twice.
But in your case even running the preprocessor twice won't help because the #include must be a single string of the form "..." or <...>.
|
3,179,199 | 3,179,234 | Simplest way to write output message to 'output window' in Visual Studio 2010? | I've tried OutputDebugString function and most of the time I get error like :
error C2664: 'OutputDebugStringA' : cannot convert parameter 1 from 'int' to 'LPCSTR'
Examples
Attempt 1:
//ERROR: sprintf is unsafe. Use sprintf_s instead
int x = 4;
char s[256];
sprintf(s, "There is %d numbers", x);
OutputDebugString((LPC... | It only accepts a string as a parameter, not an integer. Try something like
sprintf(msgbuf, "My variable is %d\n", integerVariable);
OutputDebugString(msgbuf);
For more info take a look at http://www.unixwiz.net/techtips/outputdebugstring.html
|
3,179,494 | 3,179,812 | Under what circumstances are C++ destructors not going to be called? | I know that my destructors are called on normal unwind of stack and when exceptions are thrown, but not when exit() is called.
Are there any other cases where my destructors are not going to get called? What about signals such as SIGINT or SIGSEGV? I presume that for SIGSEGV, they are not called, but for SIGNINT they... |
Are there any other circumstances where they[destructors] will not be called?
Long jumps: these interfere with the natural stack unwinding process and often lead to undefined behavior in C++.
Premature exits (you already pointed these out, though it's worth noting that throwing while already stack unwinding as a r... |
3,179,676 | 3,179,963 | C++ Exposed property for COM in idl is showing as lower case "all of a sudden" | I have this old C++ COM component. I took the latest code base, built it and found that one of the properties has become lower case. For example, in the pre-compiled dll i have a property "Type", but when building from source it's called "type". The idl shows that the property is called "Type". So what could possib... | You discovered a quirk in the OS stock implementation of ICreateTypeLib, used by practically all tool chains on Windows that can create a type library. It uses a rather crude way to deal with possible problems caused by languages that are not case-sensitive, VB/A being a prominent example.
At issue is the definition o... |
3,179,729 | 3,179,762 | Is there anything that prevents this form of use of XOR test? | Is there anything that prevents this form of use of XOR test?
bool result = false;
bool b1 = false;
bool b2 = false;
...
if ( b1 ^ b2 )
{
result = true;
}
| I would prefer the much clearer:
if ( b1 != b2 )
{
result = true;
}
|
3,179,936 | 3,179,974 | Goto out of a block: do destructors get called? | Consider the following code:
void foo()
{
{
CSomeClass bar;
// Some code here...
goto label;
// and here...
}
label:
// and here...
}
Will the destructor of bar be called ?
| The C++ Standard says:
On exit from a scope (however
accomplished), destructors (12.4) are
called for all constructed objects
with automatic storage duration
(3.7.2) (named objects or temporaries)
that are declared in that scope, in
the reverse order of their
declaration.
So the answer is "yes".
|
3,180,138 | 3,180,168 | On Sandboxing a memory-leaky 3rd-Party DLL | I am looking for a way to cure at least the symptoms of a leaky DLL i have to use. While the library (OpenCascade) claims to provides a memory manager, i have as of yet being unable to make it release any memory it allocated.
I would at least wish to put the calls to this module in a 'sandbox', in order to keep my appl... | The only reliable way is to separate use of the library into a dedicated process. You will start that process, pass data and parameters to it, run the library code, retrieve results. Once you decide the memory consumption is no longer tolerable you restart the process.
|
3,180,164 | 3,180,235 | Correct way of checking if threads are done? | I'm using multithreading in my application with _beginthread and right now to wait until all threads are done I have global bools that get set to true as each thread completes so I'm in a while loop until then. There must be a cleaner way of doing this?
Thanks
| You can use WaitForMultipleObjects to wait for the threads to finish in primary thread.
|
3,180,268 | 3,180,285 | Why are C++ STL iostreams not "exception friendly"? | I'm used to the Delphi VCL Framework, where TStreams throw exceptions on errors (e.g file not found, disk full). I'm porting some code to use C++ STL instead, and have been caught out by iostreams NOT throwing exceptions by default, but setting badbit/failbit flags instead.
Two questions...
a: Why is this - It seems an... |
C++ wasn't built with exceptions from day one. "C with classes" started in 1979, and exceptions were added in 1989. Meanwhile, the streams library was written as early as 1984 (later becomes iostreams in 1989 (later reimplemented by GNU in 1991)), it just cannot use exception handling in the beginning.
Ref:
Bjarne St... |
3,180,702 | 3,180,801 | Convert datetime from one timezone to another (native C++) | Customers from around the world can send certain 'requests' to my server application. All these customers are located in many different time zones.
For every request, I need to map the request to an internal C++ class instance. Every class instance has some information about its 'location', which is also indicated by... | I don't know of a way to extract information about other TimeZones via the API: I've seen it done by querying the registry though (we do this in a WindowsCE-based product).
The TimeZones are defined as registry keys under
HKLM\Software\Microsoft\Windows NT\Current Version\Time Zones
Each key contains several values,... |
3,180,887 | 3,180,897 | std::string vs string literal for functions | I was wondering, I normally use std::string for my code, but when you are passing a string in a parameter for a simply comparison, is it better to just use a literal?
Consider this function:
bool Message::hasTag(string tag)
{
for(Uint tagIndex = 0; tagIndex < m_tags.size();tagIndex++)
{
if(m_tags[tagInd... | If you want to use classes, the best approach here is a const reference:
bool Message::hasTag(const string& tag);
That way, redudant copying can be minimized and it's made clear that the method doesn't intend to modify the argument. I think a clever compiler can emit pretty good code for the case when this is called w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.