question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,556,168 | 1,556,219 | Making a non-object resource RAII-compliant | in my code I use HANDLEs from windows.h. They are used like
HANDLE h;
if (!openHandleToSomething(arg1, arg2, &h)) {
throw std::exception("openHandleToSomething error");
}
/* Use the handle in other functions which can throw as well */
if (!CloseHandle(h)) {
throw std::exception("closeHandle error");
}
As you s... | One idea that comes to mind is to use boost::shared_ptr with a custom deleter.
|
1,556,229 | 1,556,677 | vector <unsigned char> vs string for binary data | Which is a better c++ container for holding and accessing binary data?
std::vector<unsigned char>
or
std::string
Is one more efficient than the other?
Is one a more 'correct' usage?
| You should prefer std::vector over std::string. In common cases both solutions can be almost equivalent, but std::strings are designed specifically for strings and string manipulation and that is not your intended use.
|
1,556,284 | 1,556,312 | Is there a way to get the byte size of vectors through type alone? | How can I predict the size of a vector?
#include <vector>
#include <iostream>
using namespace std;
int main() {
cout << sizeof(vector<char[8]>) << endl;
cout << sizeof(vector<char[16]>) << endl;
return 0;
}
[starlon@localhost LCDControl]$ ./test
12
12
| Since vector<> itself is a class that does its own dynamic memory management, using the sizeof operator to ask it about size is not terribly meaningful. I suspect you will find that the value you calculate above will always be 12.
You can ask a vector how many elements it contains using the .size() method. Also, the .c... |
1,556,333 | 1,556,414 | A question about C++ template syntax (STL library source code) | I am reading STL source code right now.
Though I understand the meat in what I am reading in stl_list.h, I want to fully understand the following snippet (mainly related to the template syntax, I think).
template
class _List_base {
...
typedef typename _Alloc::template rebind<_List_node<_Tp> >::other _Node_Alloc_ty... | The template keyword is needed to identify the name rebind as a class template. Without it, rebind could be considered a variable or a constant (in this case a type due to the typename keyword) and the following < could be interpreted as a less-than operator.
This is somewhat similar to the typename keyword (which is o... |
1,556,581 | 1,556,685 | Is it possible to create a linked list on the stack in C++? | I just started learning C++ couple of weeks ago. So now I have this school assignment problem that asks me to implement a linked-list without using "new" or anything to do with dynamically allocating memory (and cannot use any ADT from STL). The prof says that everything can be done on the stack, but how? I have been w... | The difference between heap and stack are mainly (not only, but for the sake of this question mainly) where the memory is allocated and how it is freed. When you want to allocate a node on the heap, you say new Node and the system will provide you with the memory, keeps track of which chunks are used and which ones are... |
1,557,158 | 1,557,238 | Converting an application to use dlls. class 'std::map<_Kty,_Ty>' needs to have dll-interface to be used by clients of class | This seems to be a common error, but most people online choose to just ignore the warning and move on. I do not wish to ignore the warning.
Basically, when using __declspec(dllexport) to convert a project to use dlls, the compiler has trouble dealing with templates and stl objects. An explanation of the problem, and ... | Read this similar thread for a good discussion of the topic. I would suggest either of the following:
Use a static library
Hide all template-related types and interfaces behind non-template compiler firewall or pimpl.
After fighting with the linker changes from Visual C++ 6.0, to 2003, and then to 2005, I will never ... |
1,557,244 | 1,557,294 | Abusing the comma operator | I'm looking for an easy way to build an array of strings at compile time. For a test, I put together a class named Strings that has the following members:
Strings();
Strings(const Strings& that);
Strings(const char* s1);
Strings& operator=(const char* s1);
Strings& operator,(const char* s2);
Using this, I can success... | I think that the comma in your second example is not the comma operator but rather the grammar element for multiple variable declarations.
e.g., the same way that you can write:
int a=3, b=4
It seems to me that you are essentially writing:
Strings s="Hello", stringliteral
So the compiler expects the item after the c... |
1,557,245 | 1,557,266 | Access Control for objects | Is it Possible to limit the functionality of class to certain objects only (in C++). What that would mean is, suppose there are 10 methods in a class and this class has 10 objects. Is it possible to have object1 & object2 access only 3 functions.
Object3, object4,object5, object6 access 6 functions.
and rest of the obj... | As far as I know, no. This is part, however, of Aspect Oriented Programming research. I saw something like what you need in this book: Aspect Oriented Software Development.
The main issue you face is the lack of knowledge of "who is the caller" of your function. You could get along by requiring each caller to call your... |
1,557,265 | 1,557,282 | Unable to write file in C++ | I'm trying to to the most basic of things .... write a file in C++, but the file is not being written. I don't get any errors either. Maybe I'm missing something obvious ... or what?
I thought there was something wrong with my code, but I also tried a sample I found on the net and still no file is created.
This is th... | You need to open the file in write mode:
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt", ios::out);
Make sure to look at the other options for that second argument, as well. If you're writing binary data you'll need ios::binary for example.
You should also be checking the stream after opening it:
myfile.open... |
1,557,352 | 1,557,472 | How do I escape the const_iterator trap when passing a const container reference as a parameter | I generally prefer constness, but recently came across a conundrum with const iterators that shakes my const attitude annoys me about them:
MyList::const_iterator find( const MyList & list, int identifier )
{
// do some stuff to find identifier
return retConstItor; // has to be const_iterator because list is co... | If I understand what you're saying correctly, you're trying to use const to indicate to the caller that your function will not modify the collection, but you want the caller (who may have a non-const reference to the collection) to be able to modify the collection using the iterator you return. If so, I don't think th... |
1,557,570 | 1,557,636 | How can I sort a list when the sorting criterion requires an extra variable? C++ | this is for an assignment so I will be deliberately general. My question is related to implementation decisions I already made--maybe they weren't good ones.
I have a list of pointers to structs, e.g. list<MyStruct*> bob; At one point I've needed to sort these pointers by one of the data members of their targets and I ... | Similar to ltcmelo's example, but if the objects themselves don't contain the counter:
struct sort_with_counter {
sort_with_counter(const double d): counter(d) {}
bool operator()(const MyStruct* a, const MyStruct* b) {
return(counter*a->arrival < counter*b->arrival);
}
const double counter;
};... |
1,557,579 | 1,557,596 | moc in QT wont compile my c++ header file. says its too different | ok wtf this is what moc tells me when i try to moc one of my header files. im doing this through Qt 4.5.3 command prompt and it says this:
C:\Documents and Settings\The Fuzz\Desktop\GUI2>moc App_interface.h
/****************************************************************************
** Meta object code from reading... | moc converts its input header into a generated file, which is printed on its output. You should send its output to a file, with a command like:
moc App_interface.h > App_interface.h_moc
then include that.
If you're using QMake, I believe this process is automated.
|
1,557,714 | 1,565,249 | How to automate Qt moc? | I have to run the following commands from Qt command prompt: qmake -project then make and this gives me the debug folder with the Moc file.
This is strangely the only way my PC will generate the moc_.cpp file.
So how can I automate the task of these commands so I don't have to use these commands again?
| You should not run qmake -project multiple times. The -project option is meant to provide you a template project file for you to edit. An equivalent of what you are doing in an IDE would be creating a "New Project" every time you want to build. After you have the initial project, you should edit it manually, add files ... |
1,558,013 | 1,558,027 | Delete NULL but no compile error | I'm confused why the following C++ code can compile. Why does a call to delete the method of 0 not produce any error?!
int *arr = NULL; // or if I use 0, it's the same thing
delete arr;
I did try to run it, and it did not give me any error at all...
| The C++ language guarantees that delete p will do nothing if p is equal to
NULL.
For more info, check out Section 16.8,9 here:
|
1,558,052 | 1,558,105 | Is it possible to translate twice in one OpenGL Matrix? | This is a homework question I am sorry but I am lost. What happens is the following I am asked to do a tiling of hexagons. Like the grid map in many Risk games and Wild Arms XF. I understand the current transformation is the matrix that translates the points I give to OpenGL to screen coordinates and if you apply a tra... | You're translating behind the camera; Each translation goes up in the y axis by 20, and in the z axis by 1. After the second step, your hexagons are behind the camera, and can't be seen in the viewport.
Try
glTranslated(0.0f,20.0f,0.0f);
for each translation; that should help.
|
1,558,194 | 1,558,218 | Learning and cross-platform development (C++) | I am writing a small C++ program for fun and for extending my C++ skill. Since its scope is relatively small, I also planning to try out cross-platform development by making this program support both Windows and Linux.
I reckon my C++ proficiency is sitting somewhere between casual and intermediate level: OO, a bit of ... |
Can somebody give some advice if there is any "best practice" for doing C++ cross-platform development?
There are three things:
Write your own code so that it's portable
Wrap platform-specific APIs behind an abstraction/insulation/utility layer
Choose cross-platform libraries
You can choose option #2 and/or #3.
Adv... |
1,558,379 | 1,558,391 | Why is nl_langinfo(CODESET) different from locale charmap? | This post originated from How do you get what kind of encoding your system uses in c/c++?
I tried using
nl_langinfo(CODESET)
but I got ANSI_X3.4-1968 instead of UTF-8 (which is what I get when typing: locale charmap). Am I using nl_langinfo() wrong? How should I use it?
| You need to first call
setlocale(LC_ALL, "");
nl_langinfo always gives information about the current locale.
|
1,558,768 | 1,558,948 | How do I open links from a TCppWebBrowser component in the systems default browser | We are using a TCppWebBrowser Component in our program as a kind of chatwindow, but since the TCppwebrowser is using the IExplorerengine all links that are clicked is opening in IExplorer.
One idea I have is to cancel the navigation in Onbeforenavigate2 an do a Shell.execute, but where hoping for a more elegant solutio... | Assuming that TCppWebBrowser is like TWebBrowser in Delphi, something like the code below should get you going.
The OnBeforeNavigate2 event gets fired before the TWebBrowser navigates to a new URL.
What you do is cancel that navigation, and redirect the URL with ShellExecute to an external application (which is the def... |
1,558,860 | 1,558,898 | CListCtrl get item index | How do I get an item's index number using the caption text? I'm using CListCtrl class of MFC. I have the item's caption text, can I get the index for that item and then update its text. It will be helpful if you could provide an example.
| CListCtrl::FindItem (MSDN link with example)
|
1,558,879 | 1,559,281 | Regular expressions question | I've got the following string :
const std::string args = "cmdLine=\"-d ..\\data\\configFile.cfg\" rootDir=\"C:\\abc\\def\""; // please note the space after -d
I'd like to split it into 2 substrings :
std::str1 = "cmdLine=...";
and
std::str2 = "rootDir=...";
using boost/algorithm/string.hpp . I figured, regular expre... | To solve problem from your question the easiest way is to use strstr to find substring in string, and string::substr to copy substring. But if you really want to use Boost and regular expressions you could make it as in the following sample:
#include <boost/regex.hpp>
...
const std::string args = "cmdLine=\"-d ..\\da... |
1,559,006 | 1,559,025 | Wrapping C in C++, just for try/catch | So, I have a big piece of legacy software, coded in C. It's for an embedded system, so if something goes wrong, like divide by zero, null pointer dereference, etc, there's not much to do except reboot.
I was wondering if I could implement just main() as c++ and wrap it's contents in try/catch. That way, depending on th... | Division by zero or null pointer dereferencing don't produce exceptions (using the C++ terminology). C doesn't even have a concept of exceptions. If you are on an UNIX-like system, you might want to install signal handlers (SIGFPE, SIGSEGV, etc.).
|
1,559,334 | 1,560,389 | Assignment across data types in C++ |
Possible Duplicate:
Make VS compiler catch signed/unsigned assignments?
I've compiled the following snippet of code in VC++ 2005/2008:
unsigned long ul = ...;
signed long l = ...;
l = ul;
and was expecting to see a compiler warning (Warning Level set to 4), but none was generated. Am I missing something obvious h... | I think it's a duplicate (here).
Quoting the accepted answer:
You need to enable warning 4365 to catch the assignment.
That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does. (quamrana)
You could also use ... |
1,559,490 | 1,559,719 | SidBySide: 3rd Party Dll refers to two versions of MSVCR80.DLL | We include a 3rd Party lib+DLL that recently causes a lot of trouble on installations. Using dependencywalker, we found that the dll itself refers to two different Versions of
MSVCR80.DLL:
Version 8.0.50727.4053 and
Version 8.0.50727.42
alt text http://img101.imageshack.us/img101/1734/dependencywalk2.jpg
In MOST case... | Your best option is to ship the needed DLLs within your applications installer package. Use at least the version that your 3rd party DLL depends on.
Microsoft offers standalone installers for its runtime DLLs (vcredits_*). The latest version for VisualStudio 2005 can be downloaded here. That is also the version that yo... |
1,559,695 | 1,559,956 | Implementing the derivative in C/C++ | How is the derivative of a f(x) typically calculated programmatically to ensure maximum accuracy?
I am implementing the Newton-Raphson method, and it requires taking of the derivative of a function.
| I agree with @erikkallen that (f(x + h) - f(x - h)) / 2 * h is the usual approach for numerically approximating derivatives. However, getting the right step size h is a little subtle.
The approximation error in (f(x + h) - f(x - h)) / 2 * h decreases as h gets smaller, which says you should take h as small as possibl... |
1,559,786 | 1,559,846 | C++ GCC 4.3.2 error on vector of char-array | It is similar in problem to this bug
Question about storing array in a std::vector in C++
but for a different reason (see below).
For the following sample program in C++:
#include <vector>
int main(int c_, char ** v_)
{
const int LENGTH = 100;
std::vector<char[LENGTH]> ca_vector;
return 0;
... | Yes there is something in the standard stopping using arrays Using Draft C++98 Standard
Section 23 Containers
The type of objects stored in these components must meet the requirements of CopyConstructible
types (20.1.3), and the additional requirements of Assignabletypes.
where components are various containers
20.1.... |
1,559,809 | 1,559,923 | Multiple meshes in one vertex buffer? | Do I need to use one vertex buffer per mesh, or can I store multiple meshes in one vertex buffer? If so, should I do it, and how would I do it?
| You can store multiple meshes in one vertex buffer. You may gain some performance by putting several small meshes in in one buffer. For really large meshes you should use seperate buffers. SetStreamSource lets you specify the vertex buffer offset for your current mesh.
pRawDevice->SetStreamSource( 0, m_VertexBuffer->Ge... |
1,559,884 | 1,562,133 | Convert three letter language code to language identifier (LANGID) | Is there some way in the Win32 API to convert a three letter language code, as returned by GetLocaleInfo() with LOCALE_SABBREVLANGNAME specified, to a corresponding LANGID or LCID? That is, going in "reverse" to what GetLocaleInfo() normally does?
What I'm trying to do is to parse what kind of language a resource DLL i... | Unfortunately, there's no direct Win32 API that gives you a LANGID given a 3-letters abbreviation.
It looks like CLanguageSupport is your friend today :-) It already implements your plan B to lookup the LANGID based on the contents of the version info resource.
The piece of code you're looking for is int the function
L... |
1,560,033 | 1,562,335 | Getting HTTP xml error response using cURL | I am currently using cURL to communicate to a cloud site... everything is going well except for an annoying issue. The issue is that I cannot get the site's xml response when there is an error. for example, when I use Wire Shark to check the transfer I can see that in the HTTP header that I'm getting which contains the... | Set CURLOPT_FAILONERROR to 0. If this is set to 1, then any HTTP response >= 300 will result in an error rather than processing like you want.
|
1,560,176 | 1,560,199 | C++ function pointer as a static member | I cannot figure the syntax to declare a function pointer as a static member.
#include <iostream>
using namespace std;
class A
{
static void (*cb)(int a, char c);
};
void A::*cb = NULL;
int main()
{
}
g++ outputs the error "cannot declare pointer to `void' member". I assume I need to do something with parenthes... | I introduced a typedef, which made it somewhat clearer in my opinion:
class A
{
typedef void (*FPTR)(int a, char c);
static FPTR cb;
};
A::FPTR A::cb = NULL;
|
1,560,351 | 1,560,475 | To Disable the multimedia contents in IE | I need to disable the multimedia contents in IE Programatically. Is there any way my programming environment is VC++
| I'm not quite sure what you mean here.
MSDN has the registry settings for various IE options (such as ShowPictures)
This page shows an example of creating a web browser control with extremely fine grained settings:
The most complete C# Webbrowser wrapper control
|
1,560,977 | 1,561,009 | Why isn't c++ offered as a code-behind language for asp.net? | I was curious why C++ isn't offered as a code-behind language for ASP.NET applications?
| If you are interested, here's some interesting articles about how you could use managed C++ as your code-behind:
http://www.codeproject.com/KB/mcpp/helloworldmc.aspx
http://msdn.microsoft.com/en-us/magazine/cc301369.aspx
|
1,561,007 | 1,561,475 | Error when have private copy ctor with public assignment operator | Can one of you explain why the following piece of code does not compile?
#include <iostream>
using namespace std;
class Foo
{
public:
Foo() { cout << "Foo::Foo()" << endl << endl; }
Foo& operator=(const Foo&) { cout << "Foo::operator=(const Foo&)" << endl << endl; }
private:
Foo(const Foo& b) { *this = b; cout ... | You are initializing a reference from temporary.
The standard states:
The temporary should be initialized (8.5.3 par 5)"using the rules for a non-reference copy initialization (8.5)".
The copy construction is removed for the temporary (permitted by the standard. 12.8 par 5).
However, the standard clearly states (12.2... |
1,561,008 | 1,561,236 | SideBySide error on another computer with MSVC++ 2005 installed | I'm having some strange issues building and running a project on another computer. It's a side-by-side error. Usually the cause is that c++ redistributable is not installed on the machine etc. However in this case the project is compiled on that machine. MSVC++ 2005 is installed, the runtimes should be there (I ins... | sxstrace will tell you exactly what is going on with respect to SxS. It will show what dlls are searched and how they are mapped to actual versions.
Now, which runtime is loaded is coming from the manifest file that gets included in your project. Looking at the one you mention, it looks like the one from Visual2005, wi... |
1,561,183 | 1,561,192 | C++ operator overloading, understanding the Google style guide | I am following a book to learn C++ (come from a python background). I've written this, which works:
class CatalogueItem
{
public:
CatalogueItem();
CatalogueItem(int item_code, const string &name, const string &description);
~CatalogueItem() {};
bool operator< (const CatalogueItem &o... | A functor type would be more like this:
struct CatalogueItemLessThan
{
bool operator()(const CatalogueItem &a, const CatalogueItem &b)
{
}
};
Then the usage would look like this:
list<CatalogueItem> my_list;
// this is just me playing around
CatalogueItem items[2];
items[0] = CatalogueItem(4, string("... |
1,561,243 | 1,561,274 | What's the meaning of (int&) conversion in C++ | float b = 1.0f;
int i = (int)b;
int& j = (int&)b;
cout << i << endl;
cout << j << end;
Then the output of i was 1, and the output of j was 1065353216! It is a big surprise to me! So what is the true meaning of (int&) conversion?
| This is the problem with a C-style cast. You have to look closely to see what you're getting. In your case "(int)" was a normal static cast. The value is converted to an int via truncation. In your case "(int&)" was a reinterpret cast. The result is an lvalue that refers to the memory location of b but is treated as an... |
1,561,370 | 1,561,387 | How to get the length of IStream? C++ | I'm creating an IStream as follow:
IStream* stream;
result = CreateStreamOnHGlobal(0, TRUE, &stream);
Then I have a CImage object that I save to this stream:
image->Save(stream, Gdiplus::ImageFormatBMP);
I need to get the size of bytes written to this IStream.
How can I do this?
There is no Length or something like t... | IStream::Stat should do what you want.
|
1,561,416 | 1,561,437 | Get a Win32 program to request a debugger on startup? | We have a C++ Win32 application which spawns, using Qt's QProcess (undoubtedly a wrapper for CreateProcess()), a secondary 'slave' program.
Unfortunately, when debugging the system with Visual Studio 2008, the debugger does not automatically attach to the spawned process.
I know it's possible to programmatically trigge... | Use Image File Execution Options. You can specify the Visual Studio just-in-time debugger as the default debugger to attach to the process.
If you're into using the command-line debuggers, you can use ntsd -o to automatically debug child processes as well.
|
1,561,469 | 1,562,180 | Is there an alternative to inet_ntop / InetNtop in Windows XP? | I'm trying to compile beej's guide to network programming examples, but Windows XP doesn't have such a function. I'm using mingw, if it makes any difference.
| If you're only dealing with IPv4 addresses, you can use inet_ntoa. It's available on Windows 2000 or later. Otherwise you'll have to either require Vista and later, or write your own inet_ntop function.
You could also look at boost - the boost::asio has an inet_ntop implementation that works in Windows: boost::asio::... |
1,561,536 | 1,561,558 | C++ program not moving past cin step for string input | I'm obviously not quite getting the 'end-of-file' concept with C++ as the below program just isn't getting past the "while (cin >> x)" step. Whenever I run it from the command line it just sits there mocking me.
Searching through SO and other places gives a lot of mention to hitting ctrl-z then hitting enter to put th... | If you're on windows ^Z has to come as the first character after a newline, if you're on a unixy shell then you want to type ^D.
|
1,561,620 | 1,561,713 | Is it possible to use function pointers across processes? | I'm aware that each process creates it's own memory address space, however I was wondering,
If Process A was to have a function like :
int DoStuff() { return 1; }
and a pointer typedef like :
typedef int(DoStuff_f*)();
and a getter function like :
DoStuff_f * getDoStuff() { return DoStuff; }
and a magical way to com... | No. All a function pointer is is an address in your process's address space. It has no intrinsic marker that is unique to different processes. So, even if your function pointer just happened to still be valid once you've moved it over to B, it would call that function on behalf of process B.
For example, if you had
... |
1,561,629 | 1,561,898 | What are some techniques or tools for profiling excessive code size in C/C++ applications? | I have a C++ library that generates much larger code that I would really expect for what it is doing. From less than 50K lines of source I get shared objects that are almost 4 MB and static archives pushing 9. This is problematic both because the library binaries are quite large, and, much worse, even simple applicatio... | If you want to find out what is being put into your executable, then ask your tools. Turn on the ld linker's --print-map (or -M) option to produce a map file showing what it has put in memory and where. Doing this for the static linked example is probably more informative.
If you're not invoking ld directly, but only v... |
1,561,767 | 1,561,863 | error returning std::set<T>::iterator in template | I'm making a template wrapper around std::set. Why do I get error for Begin() function declaration?
template <class T>
class CSafeSet
{
public:
CSafeSet();
~CSafeSet();
std::set<T>::iterator Begin();
private:
std::set<T> _Set;
};
error: type ‘std::set, std::allocator<_CharT> >... | Try typename:
template <class T>
class CSafeSet
{
public:
CSafeSet();
~CSafeSet();
typename std::set<T>::iterator Begin();
private:
std::set<T> _Set;
};
You need typename there because it is dependent on the template T. More information in the link above the code. Lot's of thi... |
1,561,768 | 1,561,901 | Porting c++ code from unix to windows | Hi i have to port some stuff written on c++ from unix bases os to windows visual studio 2008.
The following code implements array data type with void ** - pointer to the data.
struct array
{
int id;
void **array; // store the actual data of the array
// more members
}
When i compile with g++ on Unix it's ... | You are dealing with a bug in GCC compiler. C++ language explicitly prohibits having data members whose name is the same as the name of the class (see 9.2/13). MS compiler is right to complain about it. Moreover, any C++ compiler is required to issue a diagnostic message in this case. Since GCC is silent even in '-ansi... |
1,561,910 | 1,566,620 | How to Draw pixel data taken from the backbuffer back to itself? | I'm working on a mobile application for Symbian 5th edition using OpenGLES.
This application is a pretty standard 2D app, and I make no use of the DepthBuffer.
I need to grab a snapshot of the display and then draw the very same snapshot back to the backbuffer.
I'm using glReadPixels((GLint)0, (GLint)0,
(GL... | You first need to make sure that the version of OpenGL-ES on Series60 5th edition can handle textures whose height and width aren't powers of 2.
I would advise forum nokia for that kind of query.
Shameless plug:
Quick Recipes On Symbian OS contains a whole chapter explaining the basics of OpenGL-ES on Symbian OS. The 3... |
1,562,010 | 1,562,032 | How to find the length of an LPCSTR | I'm trying to convert an LPCSTR to an integer using atoi(), and to verify that the conversion occurred successfully I want to count the number of digits in the integer it produced and the original LPCSTR (it should contain nothing but integers)
I'm having a hard time finding a good way to calculate the length of the LP... | Isn't that what strlen does?
|
1,562,182 | 1,562,218 | memorystream - stringstream, string, others? | i am reading in a binary file via the usual c++/STL/iostream syntax.
i am copying the whole content into an dynamically allocated char array and this works fine so far.
but since i want to serve parts of the content as lines to another part of the program,
i think it would be better/easier to stick to streams because i... | If you want to read from it as a stream, you might as well read directly from the file to the stringstream:
std::stringstream data;
data << input_file.rdbuf();
That reads the entire contents of 'input_file' into 'data'. You can read the data from there like you would any other stream.
|
1,562,421 | 1,562,602 | Making a HANDLE RAII-compliant using shared_ptr with a custom deleter | I've recently posted a general question about RAII at SO.
However, I still have some implementation issues with my HANDLE example.
A HANDLE is typedeffed to void * in windows.h. Therefore, the correct shared_ptr definition needs to be
std::tr1::shared_ptr<void> myHandle (INVALID_HANDLE_VALUE, CloseHandle);
Example 1 ... | Example 1 is OK
Example 2 is wrong. By blindly casting to PHANDLE, the shared_ptr logic is bypassed. It should be something like this instead:
HANDLE h;
OpenProcessToken(...., &h);
shared_ptr<void> safe_h(h, &::CloseHandle);
or, to assign to a pre-exising shared_ptr:
shared_ptr<void> safe_h = ....
{
HANDLE h;
Open... |
1,562,572 | 1,562,723 | Better method to search array? | I have an array (nodes[][]) that contains values of effective distances that looks something like this:
__ __
|1 0.4 3 |
|0.4 1 0 |
|3 3.2 1 ... |
|0.8 4 5 |
|0 0 1 |
-- --
Where the first value, node[0][0] is the distance fro... | You can simplify it quite a bit. A lot of your checks and temporary variables are redundant. Here's a small function that performs your search. I've renamed most of the variables to be a little more precise what their roles are.
int maxDistance(int fromNode) {
int max = -1;
for (int toNode = 0; toNode < nodeCo... |
1,562,948 | 1,563,167 | C++ overload resolution problem | I've got the following structure:
struct A
{
A();
virtual ~A();
virtual void Foo() =0;
};
struct E;
struct F;
struct B: public A
{
B();
virtual ~B();
virtual void Bar(E*) =0;
virtual void Bar(F*) =0;
};
struct C: public B
{
C();
virtual ~C();
voi... | Only the versions of Bar in the most-derived class containing an override of Bar will be considered for overload resolution unless you add in using declarations. If you try
struct D: public C
{
D();
virtual ~D();
void Foo();
void Bar(F*);
using C::Bar;
};
then it should work.
|
1,562,992 | 1,563,021 | Best Way to Store a va_list for Later Use in C/C++ | I am using a va_list to construct a string that is rendered.
void Text2D::SetText(const char *szText, ...)
This is all fine and good, but now the user has the ability to change the language while the application is running. I need to regenerate all the text strings and re-cache the text bitmaps after initialization. ... | Storing the va_list itself is not a great idea; the standard only requires that the va_list argument work with va_start(), va_arg() and va_end(). As far as I can tell, the va_list is not guaranteed to be copy constructable.
But you don't need to store the va_list. Copy the supplied arguments into another data structu... |
1,563,124 | 1,563,136 | C++ Vector class as a member in other class | Please I have this code which gives me many errors:
//Neuron.h File
#ifndef Neuron_h
#define Neuron_h
#include "vector"
class Neuron
{
private:
vector<double>lstWeights;
public:
vector<double> GetWeight();
};
#endif
//Neuron.cpp File
#include "Neuron.h"
vector<double> Neuron::GetWeight()
{
return lstWeights;
}
Co... | It's:
#include <vector>
You use angle-brackets because it's part of the standard library, "" with just make the compiler look in other directories first, which is unnecessarily slow. And it is located in the namespace std:
std::vector<double>
You need to qualify your vector in the correct namespace:
class Neuron
{
pr... |
1,563,218 | 1,563,274 | Are there any IDE's or plugins to one that will expand/preprocess a macro and show their results inline without compiling? | Are there any IDE's or plugins to one that will expand/preprocess a macro and show their results inline without compiling?
I've found a couple of other questions that are related, but they require compiling.
| Most compilers offer you the option to do that. Different compilers will have different switches though. Consult your docs.
For example, with Microsoft C++ compilers that would be /E /EP and /P command-line switches. They can be specified from within their IDE as well. These switches also disable compilation, just as y... |
1,563,311 | 1,563,327 | How do I get a description of the current OS version in windows? | I need to get a simple description of the OS, such as "Windows XP (SP2)" or "Windows 2000 Professional" to include in some debugging code. Ideally, I'd like to simply retrieve it by calling a "GetOSDisplayName" function.
Is there such a function available for C++ win32 programming?
| Have a look at this: http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx
|
1,563,409 | 1,563,658 | Fastest implementation of one thread providing data, many threads consuming data | I have a lot of data that I want to disseminate to many different threads. This data is coming from a single thread. The consuming threads can safely access the container simultaneously.
The data needs to be merged into the container ever delta seconds (50ms < delta < 1), during which time the consuming threads need ... | If there is only one data producer thread and memory is not a consideration, you may want to consider using a merge and swap algorithm.
In it, the writer thread creates a copy of the data structure while readers continue to use the original, merges in new changes, then performs an exchange of the two structures within ... |
1,563,491 | 1,578,871 | What is the recommended design for public-facing APIs to support multiple POD types while maximizing binary compatibility? | I am currently designing a public-facing C++ API for a product which will require a pre-compiled binary/DLL (it will be cross-platform). I would like for the API to allow the user to use any POD we support (where applicable), however the base requirements are maximum flexibility and binary compatibility. I am doing som... | Right, I think I've got what I need, at least for now.
The above mentioned
class ConstraintExpressionArgument : public Expression;
template<typename ValueType>
class Constraint : public ConstraintExpressionArgument;
got me on the right track to separating type from constraint-ness.
|
1,563,700 | 1,563,717 | Compression Libraries For C++ | I was reading about compression in programs and I started to create a new simple project, a zipper (just a zipper, not an unzipper), but I only found zLib, and it's for C. I know that C libraries can be used in C++, but I like to use C++ libraries. Does anyone know a good one to suggest?
Best Regards.
| Most compression libraries that I know of are written in C for two reasons: one, the general age of good compression algorithms; and two, the high portability (and stability) of C across platforms.
I suggest any of the following. If you want good licenses select one of the top two, otherwise if you're open to using GPL... |
1,563,704 | 1,563,711 | VS2008: how to run two separate projects from the same solution | I have a single un-managed C++ console-app solution (.sln) with two projects (.vcproj) both are built as .exe. I want to run them both at the same time (one is a client and one is a server). How do I configure my Visual Studio such that when I hit a single button, say F5, it would be smart enough to run one after anoth... | Right-click on the solution in Solution Explorer, click Properties (If the window is blank, select the solution again), and go to the Startup Projects section under Common Properties. Select the Multiple Startup Projects option. Then, you can specify which project(s) to launch and whether each one should have the deb... |
1,563,774 | 1,563,795 | Help interpret this stack trace | I know that it fails at strcmp. I've provided operator< below, which calls strcmp.
On line #1 there's the value @0xbfffeeac. What does the @ mean?
#0 0x00212bd8 in strcmp () from /lib/libc.so.6
#1 0x0012ed2f in Json::Value::CZString::operator< (this=0x8317300, other=@0xbfffeeac)
at src/lib_json/json_value.cpp:22... | You're checking this->cstr_ for null, but you're not checking other.cstr_. Perhaps the container prevents any strings with null cstr_ values from being inserted, so such a check is not necessary.
That's not the problem, however, since other is not null in this case. Rather it looks like the other object may have been... |
1,563,897 | 1,563,906 | Static constant string (class member) | I'd like to have a private static constant for a class (in this case a shape-factory).
I'd like to have something of the sort.
class A {
private:
static const string RECTANGLE = "rectangle";
}
Unfortunately I get all sorts of error from the C++ (g++) compiler, such as:
ISO C++ forbids initialization of
membe... | You have to define your static member outside the class definition and provide the initializer there.
First
// In a header file (if it is in a header file in your case)
class A {
private:
static const string RECTANGLE;
};
and then
// In one of the implementation files
const string A::RECTANGLE = "rectangle"... |
1,564,119 | 1,564,127 | More vs Less Functions | I had a little argument, and was wondering what people out there think:
In C++ (or in general), do you prefer code broken up into many shorter functions, with main() consisting of just a list of functions, in a logical order, or do you prefer functions only when necessary (i.e., when they will be reused very many times... | Small functions, please
It is the conventional wisdom that smaller functions are better, and I think it's true. In fact, there is a company with an analysis tool that rates individual functions by how many decisions they make compared to the number of unit tests that they have.
The theory is that you may or may not be ... |
1,564,240 | 1,564,285 | Polymorph collection in C++ | I need to code a class that recieves a collection with any number of elements of any 'primitive' type. I also need to be able to know the type of each member (or at least the size of the type).
The purpose of this class is to serialize the elements to store them in a file in fixed length registers.
Is this posible?
I k... | Have you looked into boost::any ? It sounds like it might be a good match for your problem: storing a polymorphic collection of objects, without the loss of type information that occurs with arrays of void * or similar hacks.
|
1,564,668 | 1,564,790 | cmake and eclipse: default include paths? | I have a project that builds with CMake system, and I like to import it in Eclipse.
However, when I generate eclipse project files with 'cmake -G "Eclipse CDT4 - Unix Makefiles"'
there are no default include paths in Eclipse project(such as /usr/include' or the gcc path for standard headers).
How to fix that in most r... | You have to go to the project properties (right button over the project), "C/C++ include paths and symbols" and add them here as "external include paths".
|
1,564,802 | 1,564,813 | How to work (portably) with C++ class hierarchies & dynamic linked libraries | Ok, so I know portability is not the strong point of C++, but I have to get my code running on both Mac&Windows. I've come up with a solution, but it's not perfect, and I'm interested to see if there is someone out there who can suggest a better one.
I need to us a class hierarchy in several DLLs/bundles - e.g., I have... | I actually found the answer to my question due to the fact that I needed to formulate it completely, and I did a better google search :)
It seems to be
__attribute__((dllimport)) // import
__attribute__((dllexport)) // export
Will try that, I thought I'd leave the question here too, in case someone else stumbles on t... |
1,564,817 | 1,564,854 | Declare but not define inner struct/class - legal C++ or not? | Is following code legal C++ or not?
class Foo
{
class Bar;
void HaveADrink(Bar &bar);
void PayForDrinks(Bar &bar);
public:
void VisitABar(int drinks);
};
class Foo::Bar
{
public:
int countDrinks;
};
void Foo::HaveADrink(Bar &bar)
{
bar.countDrinks++;
}
void Foo::PayForDrinks(Bar &bar)
{
bar.countD... | legal, and indeed usefull to hide implementation details to the outside world.
|
1,564,824 | 1,564,845 | C++ Overloading << Operator problem | I'm fairly noobish at C++, but very comfortable with pointers, dereferencing, etc. I'm having a problem with my overload of the << operator for a class, in that it compiles fine but crashes when run. It feels like an infinite loop, but I'm not certain. Here's the code, and any help is appreciated.
#include <string>
#in... | In your constructor with just a single argument, you need to set _manager to NULL/0. Test for this in your operator<< and don't output mgr->name if it is NULL/0. As it stands, you are dereferencing an uninitialised pointer.
Person::Person(string name)
{
_name = name;
_manager = 0;
}
ostream &operator<<(ostream... |
1,564,870 | 1,564,882 | Recommended OpenGL / GLUT Reference | What OpenGL / GLUT reference is good for day to day programming as you learn?
Ideally I'm looking for something with lots of C++ sample code to help me learn as I develop OpenGL applications as well as details about the APIs similar to what MSDN provides for .net programming.
If there isn't a one stop shop, then please... | The Red Book is the standard book on OpenGL. Don't be discouraged by the fact that the Amazon review for the 7th Edition has only two stars; this is because people are disappointed that there isn't more on the newest OpenGL features in the book. Previous editions got more stars.
Another good book is the OpenGL SuperBib... |
1,565,065 | 1,565,089 | A Polymorphism Problem | it works when :
list<ItemFixed> XYZ::List()
{
list<Item> items = _Browser->GetMusic();
list<ItemFixed> retItems = _Converter->Convert (items);
return retItems;
}
but not :
list<ItemFixed> XYZ::List()
{
return _Converter->Convert (_Browser->GetMusic());
}
Any suggestions?
thanks
| Are you passing the list<Item> as non-const reference to Convert function? In that case it will not compile as you can not pass temporary object by non-const reference in C++.
|
1,565,406 | 1,567,751 | C++ LINQ-like iterator operations | Having been tainted by Linq, I'm reluctant to give it up. However, for some things I just need to use C++.
The real strength of linq as a linq-consumer (i.e. to me) lies not in expression trees (which are complex to manipulate), but the ease with which I can mix and match various functions. Do the equivalents of .Wh... | I don't have concrete experience with LINQ, but the Boost.Iterator library seems to approach what you're referring to.
The idea is to have functions (IIUC, in LINQ, they take the form of extension methods, but that's not fundamental), taking an iterator and a function, combining them to create a new iterator.
LINQ "Whe... |
1,565,517 | 1,565,720 | Dynamically created scope guards | I've read the article about scope guards (Generic: Change the Way You Write Exception-Safe Code — Forever) in DDJ and I understand their common use.
However, the common use is to instantiate a particular stack guard on the stack for a particular operation, e.g.:
{
FILE* topSecret = fopen("cia.txt");
ON_BLOCK_EX... | It seems you don't appreciate RAII for what it is. These scope guards are nice on occasion for local ("scope") things but you should try to avoid them in favour of what RAII is really supposed to do: encapsulating a resource in an object. The type FILE* is really just not good at that.
Here's an alternative:
void foo()... |
1,565,567 | 1,565,590 | In which scenario it is useful to use Disassembly language while debugging | I have following basic questions :
When we should involve disassembly in debugging
How to interpret disassembly, For example below what does each segment stands for
00637CE3 8B 55 08 mov edx,dword ptr [arItem]
00637CE6 52 push edx
00637CE7 6A 00 push ... | It's quite useful to estimate how efficient is the code emitted by the compiler.
For example, if you use an std::vector::operator[] in a loop without disassembly it's quite hard to guess that each call to operator[] in fact requires two memory accesses but using an iterator for the same would require one memory access.... |
1,565,600 | 1,565,811 | How come a non-const reference cannot bind to a temporary object? | Why is it not allowed to get non-const reference to a temporary object,
which function getx() returns? Clearly, this is prohibited by C++ Standard
but I am interested in the purpose of such restriction, not a reference to the standard.
struct X
{
X& ref() { return *this; }
};
X getx() { return X();}
void g(X &... | From this Visual C++ blog article about rvalue references:
... C++ doesn't want you to accidentally
modify temporaries, but directly
calling a non-const member function on
a modifiable rvalue is explicit, so
it's allowed ...
Basically, you shouldn't try to modify temporaries for the very reason that they are temporar... |
1,565,654 | 1,566,149 | Qt Map Signals Based On Parameter Value | I know that i can use QSignalMapper to call a slot with different parameters based on connection. What i want to achieve is a little different.
We are using plugins in our application and different plugins are responsible for different types of objects. We are connecting multiple slots, each implemented in a different ... | I don't think there's a component for that, but you could create your own signal mapper like this:
create a MySignalMapper component
code an addSourceSignal method to set the signal of the main app
code an addDestinationSlot method that takes a QString/slot pair and maps the string to the slot.
in your component conne... |
1,565,724 | 1,565,727 | Clarification on lists and removing elements | If I have a list<object*>>* queue and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code):
object* objPtr = queue->first();
queue->pop_first();
return objPtr; // is this a pointer to a valid memory address now?
?
According to the documentation ... | Yes, it is a valid pointer. List will not release the memory allocated by you. List will destroy its internal not the user object.
|
1,566,178 | 1,566,191 | Preprocessor definitions going haywire. int define redefinition? | I am trying to add a preprocessor definition so that a value is only defined while a certain project is building, then it becomes undefined. I have gone into my project properties -> preprocessor -> preprocessor definitions. In here, I typed #define PROJECTNAME_EXPORT, in hopes that I could call #ifdef PROJECTNAME_EX... | You don't include the "#define" in the definition. Just the name of the symbol, and optionally a value, like so:
PROJECTNAME_EXPORT=coolness
The way to think of the definitions you enter here, into the IDE, is that they will be passed to the compiler using the /D option, so the syntax ought to be close. There would be... |
1,566,198 | 1,566,222 | How to (portably) get DBL_EPSILON in C and C++ | I am using GCC 3.4 on Linux (AS 3) and trying to figure out to get DBL_EPSILON, or at least a decent approximation. How can I get it programmatically?
| It should be in "float.h". That is portable, it's part of the C and C++ standards (albeit deprecated in C++ - use <cfloat> or sbi's answer for "guaranteed" forward compatibility).
If you don't have it, then since your doubles are IEEE 64-bit, you can just steal the value from someone else's float.h. Here's the first o... |
1,566,241 | 1,566,269 | How to get the name of an Event from a handle | I have an array of Win32 event handles that I'm waiting on using WaitForMultipleObjects(). This returns the index in the array of events that triggered but what I need to know is the name of the event. I've been looking through MSDN and can't see anything to do this.
Basically I have a class that monitors the registr... | Personally I wouldn't do it that way. Create your own mapping (std::map?) between event and key name and then do your own lookup when an event is signalled.
|
1,566,394 | 1,566,413 | Close LogonUser Handle if Failed Logon? | The LogonUser function http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx returns a handle that you can use to impersonate the user, when you are done using it you call CloseHandle to close it. My question is, do you need to close the handle if the logon attempt fails (ie wrong username or password)?
| No. LogonUser returns zero if it fails and no handle is created. Though, if you do call CloseHandle on it, CloseHandle should just return ERROR_INVALID_HANDLE.
|
1,566,445 | 1,566,501 | Accessing a method from a templated derived class without using virtual functions in c++? | How do I get around this? I clearly cannot make the value() method virtual as I won't know what type it is beforehand, and may not know this when accessing the method from b:
class Base
{
public:
Base() { }
virtual ~Base() { }
private:
int m_anotherVariable;
};
template <typename T>
class Derived : public ... | This statement:
int v = b->value();
The variable 'b' is being trated like it is an object of Derived<int>.
So tell the compiler:
int v = dynamic_cast<Derived<int>*>(b)->value();
Note: If b is not a Derived<int> the result of the cast is NULL.
So the following would probably be safer:
Derived<int>* d = dynamic_cast<D... |
1,566,603 | 1,566,650 | What is being done in this bit shifting operation? | (INBuffer[3] << 8) + INBuffer[2]
Is this essentially moving the bit in INBuffer[3] into INBuffer[2] or [3] being zero'ed out then added to [2]?
| This is a simple way to make a 16 bit value from two 8 bit values.
INBuffer[3] = 0b01001011;
INBuffer[2] = 0b00001001;
INBuffer[3]<<8 // 0b0100101100000000;
(INBuffer[3]<<8) + INBuffer[2] // 0b0100101100001001
Usually this is represented as
(INBuffer[3]<<8) | INBuffer[2];
|
1,566,612 | 1,566,715 | Is a cgi different from a console application? | I am having some problems in running cgi on my Apache (Windows, XAMPP), but the exe runs smoothly on the command prompt.
Reading the logs on Apache folder it gives no information about the error. Any ideas about this?
| Weird.
I found the problem, it was in a
sprintf("%f", f);
where f wasn't initiated.
This is weird, because it ran normal on my cmd but not on apache
any clues?
|
1,566,793 | 1,590,281 | WNetAddConnection2 in Windows 7 with Impersonation and no Error Code | I'm doing some crazy impersonation stuff to get around UAC dialogs in Windows 7 so the user does not have to interact with the UI (I have the admin creds of course).
I have a process running as the Administrator and elevated past UAC. The issue that I'm facing is that when I make a call to WNetAddConnection2, within t... | The issue was that the process was running as Administrator. Impersonation will not work because WNetAddConnection2 evaluates on processes user. You must start a separate process to accomplish this.
|
1,566,862 | 1,566,924 | Difference between variable-length argument and function overloading | This C++ question seems to be pretty basic and general but still I want someone to answer.
1) What is the difference between a function with variable-length argument and an overloaded function?
2) Will we have problems if we have a function with variable-length argument and another same name function with similar argu... | 2) Do you mean the following?
int mul(int a, int b);
int mul(int n, ...);
Let's assume the first multiplies 2 integers. The second multiplies n integers passed by var-args. Called with f(1, 2) will not be ambiguous, because an argument passed through "the ellipsis" is associated with the highest possible cost. Passing... |
1,566,895 | 1,566,937 | LNK2019 when converting an app to use DLLs | (Re-written for clarity)
I have a multi-project solution that I am looking to convert from using .lib to .DLL files. I have created my __declspec macros and applied it to every class except for those in the project that creates the final .exe. The linker is throwing a fit on just about everything, however. I have se... | Are you linking against MyRenderer.lib?
|
1,567,138 | 1,567,186 | "const T &arg" vs. "T arg" | Which of the following examples is the better way of declaring the following function and why?
void myFunction (const int &myArgument);
or
void myFunction (int myArgument);
| Use const T & arg if sizeof(T)>sizeof(void*) and use T arg if sizeof(T) <= sizeof(void*)
|
1,567,167 | 1,567,243 | How do I set a specific printer for a report? | I want to print a customized report to a specific printer, bypassing the print dialog. The printer is to be selected by the user for each report template.
Right now I have the code to print the report showing the print dialog, or directly to the default printer. I need to change it in order to print directly to a prin... | Another article from Microsoft's KB: How to programmatically print to a non-default printer in MFC
|
1,567,282 | 1,567,380 | use of extern methods between dll projects? | I have a debug condition to manage memory where I have
extern void* operator new(unsigned int size, const char* file, int line);
extern void operator delete(void* address, const char* file, int line);
extern void Delete(void* address);
#define FUN_NEW new(__FILE__, __LINE__)
#define FUN_DELETE delet... | You have to explicitly tell the compiler which functions you'd like to export. There's a little song-and-dance to do this, here's how I do it:
#ifdef USING_DLL
#ifdef CORE_EXPORTS
#define CORE_EXPORT __declspec( dllexport )
#else
#define CORE_EXPORT __declspec( dllimport )
#endif
#else
#define CORE_EXPORT
#endif
Each... |
1,567,336 | 1,567,487 | Simple 'for' loop crashing program on final iteration | The below program seems to be crashing at the very end each time, and I'm assuming that this is because once I get to i = (size-1) then wordList[i+1] won't return anything, returns null, or something equivalent. Any way around this? Am I correct that this is the source of my problem?
#include <iostream>
#include <strin... | You need two changes. As stated in previous comments, your for ending condition should be < size-1 to prevent reading out of bounds. You also need to print the count of the last item, which will be wordCount because if it's unique wordCount is 1 and if not it has been already added. Corrected code:
for (int i = 0; i < ... |
1,567,388 | 1,567,551 | Boost C++ date_time microsec_clock and second_clock | I discovered a strange result in Boost C++ date time library. There is inconsistency between microsec_clock and second_clock, and I don't understand why is that. I am using Windows XP 32-bits
My snip of code:
using namespace boost::posix_time;
...
ptime now = second_clock::universal_time();
std::cout << "Current Time i... | Not sure what could be wrong for you; the exact same code works for me.
$ cat > test.cc
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;
int main() {
ptime now = second_clock::universal_time();
std::cout << "Current Time ... |
1,567,557 | 1,567,595 | How to fix heap corruption | I've tried to build a very minimalistic memory read library to read some unsigned ints out of it. However, I run into a "HEAP CORRUPTION DETECTED" error message when the ReadUnsignedInt method wants to return.
HEAP CORRUPTION DETECTED. CRT detected that the application wrote to memory after end of buffer.
As I have r... | Michael and Naveen have both found the same major flaw in your code, but not the only flaw.
shared_ptr will delete the pointed-at object when its reference count goes to zero.
This means you can only give it objects allocated by new -- not new[].
You may wish to use shared_ptr<vector<byte> > or boost::shared_array<byte... |
1,567,650 | 1,567,690 | How to fix a C1010 error without turning off precompiled headers? | So,
I have to use precompiled headers in my VS 2005 project. Now I have a shared source file that does not have a #include "stdafx.h"... How can I include the shared source file in my project without adding stdafx.h to the top of the source file and without turning off precompiled headers??
| File properties -> C/C++ -> Precompiled Headers -> Create/Use precompiled headers -> Not using ...
|
1,567,738 | 1,567,774 | Linking error: Missing symbol but symbol exported (in exp and lib) | I have a dynamic library (plugin) that uses another dynamic library (dependency). I use the dependency in two ways:
a. by instantiating object from classes defined in the dependency
b. by inheriting from classes defined in the dependency
When doing a., there are no linking errors. But when doing b., I have a linking er... | You might want to make sure the class is being declared with __declspec(dllexport) (when building) and __declspec(dllimport) (when linking against)?
See this link.
|
1,567,834 | 1,568,044 | Why is the compiler not selecting my function-template overload in the following example? | Given the following function templates:
#include <vector>
#include <utility>
struct Base { };
struct Derived : Base { };
// #1
template <typename T1, typename T2>
void f(const T1& a, const T2& b)
{
};
// #2
template <typename T1, typename T2>
void f(const std::vector<std::pair<T1, T2> >& v, Base* p)
{
};
Why is it ... | You can either do this:
f(v, static_cast<Base*>(&derived));
Or use SFINAE to remove the first function as a selection candidate:
// Install boost library and add these headers:
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>
// #1 - change it to look like this (note the keyword void changed po... |
1,567,960 | 1,568,016 | C++ Parent class method call | I'm creating a new class that inherits queue from the STL library. The only addition to the class is a vector. This vector will have the same size of the queue and it will store some integer values that will correspond to each objects in the queue.
Now, I want to override pop() and push(), but I simply want to add more... | You asked about:
void push(type insertMe){
//This is what I want to do
super::push(); // or queue::push(); maybe?
CPU_TIME.push_back(0);
}
That would be more like:
void push(type insertMe) {
queue<type>::push(insertMe);
CPU_TIME.push_back(0);
}
Except you probably want to accept the parameter... |
1,567,972 | 1,568,193 | 'operator new': redefinition, different linkage (using _dllspec on redefined new operator) | I am using __declspec(dllimport/export) on a debug version of new as such:
#ifdef _DEBUG
DECLSPECCORE extern void* operator new(unsigned int size, const char* file, int line);
extern void* operator new[](unsigned int size, const char* file, int line);
extern void operator delete(void* address, const char* file, in... | If you have two two prototypes of overloading the new operator you must export both. Hopefulyl that is your problem.
|
1,568,298 | 1,568,326 | Under what conditions will you get unresolved external symbol for __declspec(dllimport)? | I am converting an application to use .dlls and I'm riddled with linker errors stating
unersolved external
symbol"__declspec(dllimport) public:
void __thiscall
Rail::SetNextrail(class Rail *)"
There is more gibberish at the end of this error message. Why should this happen and how do you fix it? __declspec(d... | I believe what you need to do is specify the Rails "import library" to the linker. Using the GUI, this is on the linker tab of project settings, under "additional libraries."
The "import library" is a .LIB file which contains symbols that resolve to the imports of the corresponding library. In the symbols from the .L... |
1,568,377 | 1,568,866 | Convert RGB IplImage to 3 arrays | I need some C++/pointer help. When I create an RGB IplImage and I want to access i,j I use the following C++ class taken from: http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html
template<class T> class Image
{
private:
IplImage* imgp;
public:
Image(IplImage* img=0) {imgp=img;}
~Ima... | Firstly, if you're comfortable with C++, you should consider using OpenCV 2.0 which does away with different data types for images and matrices (IplImage* and CvMat*) and uses one structure (Mat) to handle both. Apart from automatic memory management and a truckload of useful routines to handle channels, etc. and some ... |
1,568,419 | 1,568,495 | Should I implement my own TCP/IP socket timeouts? | The software I'm working on needs to be able to connect to many servers in a short period of time, using TCP/IP. The software runs under Win32. If a server does not respond, I want to be able to quickly continue with the next server in the list.
Sometimes when a remote server does not respond, I get a connection timeou... | On Linux you can
int syncnt = 1;
int syncnt_sz = sizeof(syncnt);
setsockopt(sockfd, IPPROTO_TCP, TCP_SYNCNT, &syncnt, syncnt_sz);
to reduce (or increase) the number of SYN retries per connect per socket. Unfortunately, it's not portable to Windows.
As for your proposed solution: closing a socket while it is still in ... |
1,568,540 | 1,574,791 | How to make gcc or ld report undefined symbols but not fail? | If you compile a shared library with GCC and pass the "-z defs" flag (which I think just gets passed blindly on to ld) then you get a nice report of what symbols are not defined, and ld fails (no .so file is created). On the other hand, if you don't specify "-z defs" or explicitly specify "-z nodefs" (the default), the... | From the GNU ld 2.15 NEWS file:
Improved linker's handling of unresolved symbols. The switch
--unresolved-symbols= has been added to tell the linker when it
should report them and the switch --warn-unresolved-symbols has been added to
make reports be issued as warning messages rather than errors.
|
1,568,568 | 1,568,687 | How to convert Euler angles to directional vector? | I have pitch, roll, and yaw angles. How would I convert these to a directional vector?
It'd be especially cool if you can show me a quaternion and/or matrix representation of this!
| Unfortunately there are different conventions on how to define these things (and roll, pitch, yaw are not quite the same as Euler angles), so you'll have to be careful.
If we define pitch=0 as horizontal (z=0) and yaw as counter-clockwise from the x axis, then the direction vector will be
x = cos(yaw)*cos(pitch)
y = s... |
1,568,659 | 1,568,758 | What are some rules with included headers? | I keep running into problems the larger my program gets. For instance, I get the following error:
In file included from WidgetText.h:8,
from LCDText.h:17,
from WidgetText.cpp:13:
Generic.h:21: error: expected class-name before ',' token
Here are those lines:
#include "Generic.h" // Wi... | Part of the solution is to add some forward declarations to get rid of these compiler errors (just like you did with your class Generic line). Google will turn up lots of suggestions on how exactly to do this.
Using forward declarations will let you eliminate the cyclic / circular #includes described in this answer.
A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.