question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
7,441,218
7,453,413
Does C++/CX detect and solve cycles of objects?
From my understanding C++/CX doesn't use garbage collection, it use a reference counted approach instead. The problem with reference counting is that it cannot dispose of cycles. Cycles are usually solved using weak references, such as weak_ptr in standard C++. But I cannot find a way in C++/CX to explicitly specify a ...
Short answer: No, C++/CX doesn't detect and solve cycles of objects. Long answer: WinRT itself has a standard mechanism for weak references. On ABI level, this is defined in terms of interfaces IWeakReference and IWeakReferenceSource, which you can see in "%ProgramFiles%\Windows Kits\8.0\Include\winrt\WeakReference.idl...
7,441,347
7,441,366
Undefined reference in Linux makefile
I want to build my application under linux but i can't get my makefile to make it. the problems are the static libraries I wan to link with. I get a lot of "undefined reference to" error messages like: undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()' or ...
CXX = gcc You're linking with gcc, rather than g++, so -lstdc++ is not linked in by default. Note that using gcc to compile C++ sources work just fine, since g++ is called implicitly in that case.
7,441,440
7,441,556
Weird C++ template & const problem
I don't understand why the output of this program is Second method instead of First Method... #include <iostream> template <class T> void assign(T& t1,T& t2){ std::cout << "First method"<< std::endl; } template <class T> void assign(T& t1,const T& t2) { std::cout << "Second method"<< std::endl; } class A { p...
assign( a, a+b ); The result of a + b is an rvalue expression of type A that creates a temporary and you cannot bind it to a non-const reference, so it picks up the const overload as you are allowed to bind a const reference to a temporary. assign( a, c ); In this case, the subexpression c is an lvalue expression and...
7,441,578
7,441,697
how to convert c string to xml using standard c++?
I would like to know is there any way to generate xml schema from a c string by using stander c++? In my current application there is a server which sends comma separated string by a socket. That is cumbersome to parse date. I would like to extend this to convert this string into a standard XML format. So that I could ...
Basically you have two separate steps: Parse the String and get the information you want out of it Write the XML For Step 1. I would suggest using some regular expression library, e.g. Boost.Regex. As soon as you have the information parsed, you can simply write the XML into a string using standard streams like std::...
7,441,608
7,441,676
Windows: pointer unicity
I had a need of a quick unique ID in one of my classes to differenciate one process from another. I decided to use the address of the instance to do so. I ended up with something like this (quintptr is a Qt defined type of integer to store addresses with the correct size, according to the platform): Foo::Foo() : _id(re...
Every process gets its own address space. On XP, they're all the same. Therefore it's very common to see what you saw: two objects that have the same address, but in two different address spaces. It turns out that this contributes to security risks. Attackers were able to guess where vulnerable objects would be in memo...
7,441,890
9,206,200
Boost::graph undefined properties
I am loading a graphviz dot diagram into a Boost::Graph object. I want to make sure that the nodes and arcs have a set of specific properties but do not care if they have any other properties. All I want Boost::Graph to do is to flag those (a catchable exception is fine) and not just abort the loading of the file. ...
The Graphviz loader puts properties that are not in your dynamic_properties list into a separate structure, so they should be ignored just as you want.
7,442,085
7,442,710
Cross-Compiling C and C++ application in Windows 7, using MinGW under linux
I have installed MinGW compiler in Windows 7. GCC version is 4.6.1. I have Hello World application: #include <stdio.h> int main( int argc, char* argv[] ) { printf( "Hello World!" ); return 0; } How I can compile this application under Windows 7, using MinGW compiler, in order that i can run this application ...
You need to distinguish two systems here: The build system, which is the one your compiler runs on, and the host system, which is the one your executable will run on. MinGW is the GCC compiler for the host system Windows. So, you can compile on Windows for Windows or cross-compile on Linux for Windows. You are looking ...
7,442,873
7,442,941
Is it ok to return a reference?
I have something like class X { private: someclass obj; public: someclass& get() { return obj; } }; I dont want to make obj public, so i get a reference of it and pass it around to functions. Is this a good/ok practice or is it outright evil ?
If you pass a non-const reference as in your code then obj can be modifed from outside your class. If you wish that it cannot be changed from outside X you must return a const ref, const someclass& get(); Note with this case it is worth adding another const after the function name const someclass& get() const; which...
7,442,939
7,443,329
Opening a window that has no title bar with Win32
I'm developing a C++ application for Windows. I'm using the Win32 API. How can I open a window without a title bar (without controls, icon and title) and that can not be resized. The piece of code that I am using for the application to create a window: hWnd = CreateWindow(szWindowClass, 0, (WS_BORDER), ...
hWnd = CreateWindow(szWindowClass, 0, (WS_BORDER ), 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, NULL, NULL, hInstance, NULL); SetWindowLong(hWnd, GWL_STYLE, 0); //remove all window styles, check MSDN for details ShowWindow(hWnd, SW_SHOW); //display window
7,442,944
7,497,097
Wrap an Operator overloading method
How do I wrap a method which performs operator overloading in unmanaged C++ code using C++/CLI? I am working for an organisation and I don't have much access to their source code and hence don't have much idea about what the operator overloading function does exactly. So is there a way to wrap this method and not redef...
I do not fully understand but, wrapping native code means covering and executing it in a managed function. For example you want to wrap this class: //Native code class NativeClass { std::vector<int> data; public: int operator[] (int index) { return data[index]; } } //Managed code public ref class ManagedC...
7,443,354
7,443,520
Wrapped lambda expressions
Here's a lamba wrapper expression defined: function <int(double)> f = [](double x) -> int{ return static_cast <int> (x*x); }; It is used like this: f(someintvalue); What is the difference between normal functions and wrapped lambdas?
question is - what is the difference between normal function and wrapped lambda? Normal function is a normal function and what you call "wrapped lambda" is actually a function object. By the way, why use std::function? You could simply write this: auto f = [](double x) { return static_cast <int> (x*x); }; //call int...
7,443,457
7,443,518
Receiving Error "invalid operands of types `%T' and `%T' to binary `%O' in evaluation of `%Q(%#T, %#T)' "
I have tried very very hard to solve this problem. I have always been able to find my answer through Google, and this is the first time I have ever posted to a forum because of my due diligence. However, this has completely stumped me, and Google appears to be recommending the source code for gcc, which suggests to me ...
The fix should be: (*c_a) += *c_b; Operators in C++ are not 'lifted' (like in functional languages, like e.g. Haskell; C# has the notion of lifted operator for Nullable types) Note @Daniel: This answer references the answer to your question ("why it should be this way"): C++ doesn't do automatic lifted operators for p...
7,443,760
7,443,809
Accessing double pointer causes segmentation fault
I am programming Jacobis method for eigenvalue problems in QM and I have just started c++, I want to use double pointers to construct matrices but the physics problem involved requires a lot of code. I don't want to clutter my main() with unreadible lines (others will have to read this code..) and so wanted to divide t...
//This part segfaults for(i=0; i<N; i++) Because, you are passing double **A by value (which is modified inside makematrix) and not by reference. Change your function signature to following and it should work: void makematrix(int N, double **&A) ... ^^^ pass by reference
7,443,782
7,444,032
Does dynamic memory allocation differ in C and C++ in popular implementations?
As far as the respective language standards go, C offers dynamic memory allocation only through the malloc() family, while in C++ the most common form of allocation is performed by ::operator new(). The C-style malloc is also available in C++, and many "baby's first allocator" examples use it as its core allocation fun...
Here is the implementation used by g++ 4.6.1: _GLIBCXX_WEAK_DEFINITION void * operator new (std::size_t sz) throw (std::bad_alloc) { void *p; /* malloc (0) is unpredictable; avoid it. */ if (sz == 0) sz = 1; p = (void *) malloc (sz); while (p == 0) { new_handler handler = __new_handler; ...
7,443,787
7,443,877
Using C++ ifstream extraction operator>> to read formatted data from a file
As my learning, I am trying to use c++ ifstream and its operator>> to read data from a text file using code below. The text file outdummy.txt has following contents: just dummy Hello ofstream 555 My questions is how to read char data present in the file into a char array or string. How to do this using the ifstream::o...
If you want to use formatted input, you have to know in advance what data to expect and read it into variables of the according data type. For example, if you know that the number is always the fifth token, as in your example, you could do this: std::string s1, s2, s3, s4; int n; std::ifstream in("outdummy.txt"); if ...
7,443,970
9,369,458
Separate test cases across multiple files in google test
I'm new in google test C++ framework. It's quite easy to use but I'm wondering how to separate the cases into multiple test files. What is the best way? Include the .cpp files directly is an option. Using a header seems that does nothing... Any help is welcome
Create one file that contains just the main to run the tests. // AllTests.cpp #include "gtest/gtest.h" int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } Then put the tests into other files. You can put as many tests as you like in a file. Creating one file per c...
7,443,997
7,444,079
Why wouldn't gcc compile this trivial code that calls free() function?
I tried the following code on both codepad.org and ideone.com: char* ptr = new char; free( ptr ); Yes, I know it's undefined behavior, but I want to compile it and run it to see what happens. Visual C++ 10 compiles it, but gcc which is used on the abovementioned sites says error: expected constructor, destructor, or ...
This code indeed will not compile. You have to add main() call also. #include <stdlib.h> int main() { char* ptr = new char; free( ptr ); return 0; }
7,444,148
7,444,194
Correct way to return stl map by reference / Is this behavior well defined?
I have 2 classes and one of them has map<string, vector<string> >I want to be able to use this in other class. Here is my code: class a { map<string, vector<string> > m; public: const map<string, vector<string> > & get() { return m; } }; class b { a obj; public: void test() ...
If you do not want to change the map in b::test(), you should not make a copy of it: const map<string, vector<string> >& m = obj.get(); // note the const & My objections: Major: a::get() should be const: const map<string, vector<string> > & get() const // note the const at the end Minor: I would create an alias fo...
7,444,170
7,444,213
boost::bind as l-value object
Is there way to do something like this (MS VS 2008)? boost::bind mybinder = boost::bind(/*something is binded here*/); mybinder(/*parameters here*/); // <--- first call mybinder(/*another parameters here*/); // <--- one more call I tried int foo(int){return 0;} boost::bind<int(*)(int)> a = boost::bind(f, _1); but it...
The bind returns unspecified type, so you can't directly create a variable of the type. There is however a type template boost::function that is constructible for any function or functor type. So: boost::function<int(int)> a = boost::bind(f, _1); should do the trick. Plus if you are not binding any values, only placeh...
7,444,464
7,444,502
Read bytes methods in C / C++
I am new to C and i was wondering if there are standard library methods to read bytes/int/long such as: getChar(), getInt(), getLong(). So for instance if i call getInt(), it will return the 4 bytes as a string and move the char pointer address by 4. Where can i find these methods?
Since pointer arithmetic is in the very nature of C, such Java-like functions are not available there. To get an int out of some memory buffer you would do: /* assuming that buf is of type void * */ int x = *((int *) buf); /* advance to the position after the end of the int */ ((int *) buf)++; or more compactly: int x...
7,444,790
7,444,919
How to write a different version of stl algorithms in c++?
For practice, I wrote some template functions whose names are the same as the stl algorithms. But my code can not compile error: Call to < algorithm_name > is ambiguous. I only included using std::necessary_names; in my code rather than using namespace std;.
Usually when you have using, the "used" name takes precedence: namespace N { int x = 0; } int x = 1; int main() { using N::x; cout << x; } // Output: 0 However, Argument-Dependent Lookup can mess this up: namespace N { struct T {}; void f(T) {} } namespace M { void f(N::T) {} } int main() { usin...
7,445,065
7,445,100
Unexplained error in C++ parser source code
This is the function that checks the name of the function entered by the user into the interpreter/parser I am making, compares it with the array of functions, and executes the corresponding C++ function. It works fine as long as the user enters a correct function name, but the interpreter ends with some unexplained ru...
What you are doing wrong is (int)sizeof(fset). That gives you the size of a pointer, in bytes, not the number of elements in the passed-in fset array. You need some other way of determining how many elements are in the array, perhaps by passing in another arg, by using an std:: container instead of an array, or by NUL...
7,445,315
7,445,402
How can I get rid of C4100 warning when using typeid in a template method?
The following C++ code uses typeid to print out the runtime class of the parameter: #include <iostream> class Foo { }; class Bar: public Foo { }; template <class O> void printTypeName(O& object) { std::cout << typeid(object).name(); } int main(void) { Bar x; printTypeName(x); } Since Foo is not polymor...
There's an UNREFERENCED_PARAMETER macro you can use for that. ==== Edited by the OP: one can also use (void) object; and avoid using the macro (credits to David Rodriguez for his comment about it).
7,445,576
7,448,241
gzstream on windows via mingw: injects CR + LF
I downloaded the source from the site and built it but when I run the test, all of the zipped files have CR+LF line endings rather than just LF which makes the unzipped files different from the originals. I'm looking at the source but it seems like they are already opening the file in binary mode: gzstreambuf* gzstre...
I've successfully implemented my workaround. Though gzstream looks nice I bit the bullet and just wrote some code that directly uses zlib. Turns out it wasn't bad at all because zlib has helpers hidden away in there, and also plenty of helpful comments in zlib.h itself. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uL...
7,445,660
7,445,970
Pass parameter by reference vs use Instance variable
I started to read a book about C++ and found the following code. It is an example on how you can send pass parameters by reference. #include <iostream> void swap(int &x, int &y); int main() { int x = 5, y = 10; std::cout << "Main. Before swap, x: " << x << " y: " << y << "\n"; swap(x, y);...
For several reasons. You should declare variables at the narrowest scope possible. Why? Look at 2 & 3 Variables are expensive, they take up memory, you only want them around as long as you need them. The greater a variables scope (i.e. how much code the variable is visible to) the greater the chance that you will mist...
7,445,783
7,445,896
Should I declare this as const int member variables of the class?
I have some values such as width, height among some other that I set in the constructor at this moment. They are not currently constants but I want them to be that so I will change them now. But I heard that it is not common to make such variables private const without also doing private static const. Is this the case...
Are these values specific to the instance of the object, but only set in the constructor? Then static does not make sense, as every object would have the same height and width. If you make a private data member const, the default assignment operator won't work and you will need to provide one.
7,445,798
7,445,903
C++ template question
I'm writing some test cases for C++ name-demangling code, and I get a weird error when I try to compile this: (the following is pathologically bad C++ code that I would never use in practice). template<class U, class V> class TStruct { U u; V v; public: void setU(const U& newu) {u = newu; } }; template<class T,...
The correct line should be as, int chakka(const typename Huh<T>::template Wham<U>& wu, T t) ... it's a type ^^^^^^^^ ^^^^^^^^ indicate that 'Wham' is a template [Note: g++ is quite helpful in this case :) ]
7,446,079
7,446,117
How do I make a class in C++, when initialized, return a boolean value when its name is invoked, but no explicit function call make, like ifstream
How do I make a class in C++, when initialized, return a Boolean value when its name is invoked, but no explicit function call make, like ifstream. I want to be able to do this: objdef anobj(); if(anobj){ //initialize check is true }else{ //cannot use object right now } not just for initialization, but a check fo...
The way istream does it is by providing an implicit conversion to void* http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/ stream output and implicit void* cast operator function invocation Update In reaction to the comments, the Safe Bool Idiom would be a far better solution to this: (code directly tak...
7,446,172
7,446,372
How to iterate over std::vector<char> and find null-terminated c-strings
I have three questions based on the following code fragments I have a list of strings. It just happens to be a vector but could potentially be any source vector<string> v1_names = boost::assign::list_of("Antigua and Barbuda")( "Brasil")( "Papua New Guinea")( "Togo"); The following is to store lengths of each name ...
To estimate storage, you should probably measure the strings, rather than rely on a hard-coded constant 20. For example: size_t total = 0; for (std::vector<std::string>::iterator it = v1_names.begin(); it != v1_names.end(); ++it) { total += it->size() + 1; } The main inefficiency in your loop is probably that you ...
7,446,482
7,446,510
Is there a way to get rid of constness of virtual member functions
I need to implement a mock for an interface that is defined something like: class Foo { public: void sendEvent(int id) const = 0; } My mock class needs to save all event id's sent to the class. This is how I intended to do it. class FooMock : Foo { private: m_vector std::vector<int>; public: void sendEvent(int ...
You can make the vector mutable so that it can be modified from within const methods, like this: mutable std::vector<int> m_vector; Note however that this makes the vector mutable from all methods. If you only want to write to it from a single method, a const_cast is less invasive, in that you cast the constness of th...
7,446,844
7,447,072
How to modify each element of a parameter pack, and create a tuple from those?
I'm running into an issue with a variadic function template. I need to examine each element of a parameter pack, package the element, then stuff all the packaged elements into a tuple and return that. Here's the general idea of what I'd like to do (return types are just placeholders, not sure what they'd be): templat...
You can use deduced return type. Sadly it has code reduplication: #include <iostream> #include <tuple> template<typename A> int func_helper(A ) { //examine a, depending on type, do different stuff with it. return 1; } char func_helper(double) { return 'A'; } template<typename ...Args> auto func(Args... a...
7,446,849
7,446,940
Having problems with updating a map
I have to map containers: map<string, char *> mOServs; map<LPWCH, int> mymap; I do a sqlite3 query and try to update these two maps with the results: sprintf_s(query,1024,"SELECT oservname FROM OServs;"); rc = sqlite3_get_table(db, query, &results, &nrow, &ncol, &zErrMsg); cout << "query: " << query << endl; ...
Perhaps you meant to do something more like this: map<int, std::wstring> mymap; for(int i(0); i < nrow; ++i) { // ... mymap[i] = somevar; } Edit: Actually why do you need a map here at all? std::vector would probably suffice it doesn't make much sense to have either the key or the value of the map be set to a temp...
7,447,016
7,447,356
a macro on templates
Not sure if what am trying to do is bad but here's my question: I have a some template functions like std::vector<T> operator - (const std::vector<T>& data1, const std::vector<T>& data2); std::vector<T> operator * (const std::vector<T>& data1, const std::vector<T>& data2); std::vector<T> operator & (const std::vector<T...
No space before the macro argument list! #define _BINARY_OP_ON_DATASET(OP_TYPE) ... ^^^
7,447,069
7,447,196
C++, diamond inheritance, where/when do pure virtuals need to be implemented?
C++: I have a base class A with a pure virtual function f() and then two classes B and C inherit virtually from A, and a class D that inherits from both B and C (the typical diamond structure): A f() = 0 v/ \v B C \ / D Where and when does f() = 0 need to be implemented in the following cases? Both B and ...
Both B and C have also pure virtual functions (-> do abstract classes must implement inherited pure virtuals?) Yes D MUST implement ALL the inherited pure virtual functions. Unless a class implements all the pure virtual functions of the classes it derives from the class itself actas as an Abstract class. Only one o...
7,447,915
7,448,187
How to set the background QBrush of a QMdiArea widget to a gradient of system colors?
I'm trying to set the background QBrush of a QMdiArea widget in Qt4 to a gradient of system colors. Here's some code I have now: QPrios::QPrios(int &argc, char **argv): QApplication(argc, argv) { // ... QPalette pal = this->palette(); QLinearGradient grad; grad.setColorAt(0, pal.text()....
Set the gradient's coordinate mode. You might also want to set the gradient's start and stop points at constructor if you want a vertical gradient. QLinearGradient grad(QPointF(0, 0), QPointF(0, 1)); grad.setCoordinateMode(QGradient::ObjectBoundingMode); grad.setColorAt(0, pal.text().color()); grad.setColorAt(1, pal.wi...
7,447,976
7,448,027
boost::interprocess::basic_string as std::string
I am trying to replace a class method which returns const std::string & with const boost::interprocess::basic_string &. The main challenge I am facing is the incompatibility between the two classes despite their implementation similarity. For more clear explanation I will put that into code class A { std::string m_str;...
Even if boost::interprocess::basic_string<> did have a conversion to std::basic_string<>, it would be completely useless for your purposes -- after the conversion, the interprocess string would be destroyed, and its allocator is the important one (i.e., the one holding the data in shared memory, which I assume is your ...
7,448,057
7,448,175
How do I convert PWSTR to string in C++?
I have the following code: // Fetch Local App Data folder path. PWSTR localAppData = (PWSTR) malloc(128); SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &localAppData); // Find out the absolute path to chrome.exe stringstream ss; ss << localAppData << "/Google/Chrome/Application/chrome.exe"; The result of strin...
1. Yuk! Microsoft says: typedef wchar_t* LPWSTR, *PWSTR; So let's get that horrid nonsense out of your testcase, and lose the C rubbish: // Fetch Local App Data folder path. wchar_t* localAppData = new wchar_t[128]; SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &localAppData); stringstream ss; ss << localAppDa...
7,448,078
7,448,203
How do I get the name of a tag in TinyXML?
For example: test.xml <fruit taste="good">whatever</fruit> How can I get the name-string of the tag "fruit" (which would be "fruit" of course) using TinyXML?
Use TiXmlElement::Value() The Value function returns different things based on the type. Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string
7,448,126
7,448,227
CreateProcess I can't start a process
I am using CreateProcess, but I can't start a process I am using the following code but I am getting the error "Invalid access to memory location" but I don't know why. Is there any problem with my code? #include <Windows.h> #include <stdio.h> //#include "common.h" int main(void) { DWORD creation_flags = DEBUG_P...
You have only filled in 3 fields of the startupinfo Structure. The remaining fields are filled with garbage, and some of that garbage is likely leading to bad problems. You should fully initialize the structure, explicitly putting NULL, 0 and other "empty" values where you don't want to specify anything.
7,448,321
7,448,768
Should QGraphicsItem::boundingRect() include child bounding rects?
Googling suggests that it should. But the dragdroprobot example implementation (on the parent Robot object) suggests not: QRectF Robot::boundingRect() const { return QRectF(); } Which is correct, or is there something more subtle going on?
Child items are painted directly by the scene not by the parent, and according to the documentation about boundingRect(): QGraphicsView uses this to determine whether the item requires redrawing. So, if there is no drawing to do in the parent, there is no need to return a non-null bounding rectangle, even if the pare...
7,448,411
7,448,631
Best way to load in a video and to grab images using c++
I am looking for a fast way to load in a video file and to create images from them at certain intervals ( every second, every minute, every hour, etc.). I tried using DirectShow, but it just ran too slow for me to start the video file and move to a certain location to get data and to save it out to an image. Even if I...
MPEG-4 format is not an intra-coded format, so you can't just jump to a random frame and decode it on its own, as most frames only encode the differences from one or more other frames. I suspect your decoding is slow because when you land on a frame for which several other dependent frames to be decoded first. One way ...
7,448,444
7,448,455
matrix and vector multiplication
Suppose we have 3*3 matrix like this: 1 3 4 2 6 8 9 0 12 And some vector like this: 1 2 3 My question is: how to implement it so that I could multiply one by another? I have example code: #include <cstdlib> #include <math.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int ...
Change: for (int i=0;i<3;i++){ cout<<a[i]<<" "<<endl; to: for (int i=0;i<3;i++){ cout<<c[i]<<" "<<endl;
7,448,508
7,449,368
Java vs. C++ - Raytracing
I created simple ray tracer in Java as a hobby project, and well, it's slow. Not dramatically slow, but slow nevertheless. I wonder if I can get any performance gain using lower level language like C or C++ or will the difference be negligible and I should stick to improving "my" algorithm?
I think the question have been answered as YES a not interpreted language will in 99.99% of the cases run faster than the same algorithm under a VM. This said (having worked a lot in image processing both in java and c/c++ where memory and time mattered) I think you should at first try to optimize your code, here are a...
7,448,514
7,449,186
How can I know how much memory an STL object takes?
I need to gather statistics about memory usage in my program. My code is mostly written using STL. Is there any way of learning how much memory is being consumed by an STL object? For example, string s1 = "hello"; string s2 = "hellohellohellohellohellohellohellohellohellohellohellohellohello"; How much memory is consu...
If you're willing to be slightly intrusive, you can make a custom allocator to track all heap usage by container type, or by type allocated. This is quite intrusive, but quite accurate as well, for determining memory usage. This does not track how much memory the heap itself takes though, as that is highly OS-depende...
7,448,812
7,448,923
OPenMP loop increment
Is it OK to use loop increment greater than 1? #pragma omp parallel for schedule(dynamic, 1000) for (int i=0; i<100000; i+=10) { // do something that uses i } Thank you.
Yes. The allowed form for the for loop is: for (init-expr; test-expr; incr-expr) structured-block Where incr_expr is any of: ++var var++ --var var-- var += incr var -= incr var = var + incr var = incr + var var = var - incr See http://www.openmp.org/mp-documents/OpenMP3.1.pdf page 40.
7,448,956
7,449,092
Invoking a function from another class with Boost in c++
I am fairly new to both c++ and the boost library. What I want to do is invoke a method foo from a class Bar inside a class Baz. Here is basically what I want to achieve: Baz::doSomething() { Bar bar; boost::thread qux(bar.foo); } And the foo function could be something like: // bar.cpp void foo() { cons...
boost::thread qux(boost::bind( &Bar::foo, // the method to invoke &bar // the instance of the class ));
7,449,193
7,449,212
help on understanding logic
How can I logically understand this: int low_digit = value % 10; value /= 10; Where I am lost is when mod divides and print the remainder. What is it dividing by? What does value /= 10; mean?
/= is the C++ way of saying: value = value / 10; Here value % 10 gives you the reminder of dividing it by 10. Imagine value is 19, this will give you 9, the last digit (reminder of dividing it by 10). The last statement, will divide that value by 10 (integer division), and will give you 1 (the tens digit).
7,449,374
7,450,382
Speed of operations on misaligned data
To my knowledge, a CPU performs best with a datum that is aligned on the boundary equal to the size of that datum. For example, if every int datum is 4 bytes in size, then the address of every int must be a multiple of 4 to make the CPU happy; same with 2-byte short data and 8-byte double data. For this reason, new ope...
There are far too many processors on the market to be able to give a generic answer. The only thing that can be stated with certainty is that some processors cannot do an unaligned access at all; this may or may not matter to you if your program is intended to run in a homogeneous environment, e.g. Windows. In a modern...
7,449,382
7,450,770
TBB Concurrent Hash map
I am implementing tbb's concurrent hash map to compare the performance of it against a suite of other concurrent hash tables. However the performance I get out of it is horrendous, I just can't believe it is that slow compared to other concurrent hash tables Here is my implementation of it: class TBB: public TestDs{ ...
You HashCompare::hash() returns sizeof(int), which, I guess, means every entry maps into the same bucket. It seems like you are not using it as a hash table, more of a linked list. You could try using Boost's hash: #include <boost/functional/hash.hpp> template<typename K> struct HashCompare { static size_t hash(...
7,449,596
7,450,931
implement laplacian 3x3
Im reading DIP 2nd edition by Gonzalez and Woods and try to my hands dirty with Laplacian mask (page 129&130) using wxImage. float kernel [3][3]= {{1, 1, 1},{1,-8, 1},{1, 1, 1}}; here is the processing loops: unsigned char r,g,b; float rtotal, gtotal, btotal; rtotal = gtotal = btotal = 0.0; ...
First, the result of convolving with a Laplacian can have negative values. Consider a pixel with a value of 1 surrounded by 0's. The result of the convolution at that pixel will be -8. Second, the range of the result will be between [-8 * 255, 8 * 255], which definitely does not fit into 8 bits. Essentially, when ...
7,449,602
7,449,828
Compile Managed C++ Assembly Against Specific .NET Version (VS2008)
I am running into a weird issue with my managed C++ assembly. Even though I have the C# project and the managed C++ (DLL) project set to target .NET 3.5, when I compile the managed assembly its "Runtime Version" is 2.0. I am trying to use the same assembly across a .NET 3.5 project and a .NET 4.0 version of a CSScript...
Your "fix" won't actually fix the problem. Runtime Exception: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information You need to use the 4.0 runtime to avoid this, no point in even trying for some mythical "3.5" ver...
7,449,620
7,449,700
How to call std::min() when min has been defined as a macro?
How do I call std::min when min has already been defined as a macro?
(std::min)(x,y) The parentheses around min prevent macro expansion. This works with all function macros.
7,449,650
7,449,925
including a class template within a map
I have a template class Test, and I am trying to define the following function in a separate header file: template<typename T> T dtest(const int, std::map<int, Test<T> >& y); but I get the following error: ‘Test’ was not declared in this scope template argument 2 is invalid template argument 4 is invalid
Given that you assert that the header that defines Test<T> is included by the header that declares dtest, I'm going to guess you have a circular include: The Test<T> header also includes the dtest header.
7,449,813
7,449,830
C++ object referencing in classes
I am wondering how to store a reference of an object inside of another object, and also set that reference as a private property. Example (pseudo-code): class foo { public: int size; foo( int ); }; foo::foo( int s ) : size( s ) {} class bar { public: bar( foo& ); private: f...
The same way you define and use any class member. Make sure you initialise the reference member with the _member-initialiser, instead of just assigning to it after-the-fact in the constructor body; recall that references must be initialised and cannot later be rebound. class foo { public: int size; ...
7,449,919
7,449,949
Undefined behaviour of sub-expressions
Does this result in undefined behaviour because the order of evaluation will be unspecified? int i = 0, j = 0, k = 0; int result = i++ + ++j + k++;
No, the result of the evaluation doesn't depend on the unspecified order of evaluation of the sub-expressions. Undefined behavior only occurs in this situation if two side effects that affect the same object are unsequenced relative to each other or a side effect and a value computation of the same object are unsequenc...
7,450,156
7,450,264
C++ / SDL application pauses when dragged
Came across a problem which google searches could not help me with. I have a little SDL application that runs at 60 fps. Everything is working fine, however, it pauses/stops running when the window is dragged ( 640 X 480 window ). Is there a flag or something that can be set in the SDL window to prevent this from happe...
Windows uses a modal event loop for dragging windows, which blocks your main UI thread. More discussion (and suggested workarounds, such as drawing from a second thread): http://www.sfml-dev.org/forum/viewtopic.php?p=8384&sid=632116a07a569edee43331076e028071 OpenTk apparently has code designed to address this, maybe yo...
7,450,311
7,450,342
C or C++ Return Status
What are the best practices for writing C or C++ functions that return an int that represents a status code? Specifically, I want to know about the client usage but other tips are welcome. For example, can I write something like this: int foo() { return 0; // because everything was cool } And then use it like this?...
We use this in C where I work: int err = foo(); if (err) { // armageddon } The assignment and if could be combined, but with more complicated function calls it gets more confusing and some people are confused by assignment in a conditional (and gcc hates it). For C++, I would prefer exceptions if available, otherw...
7,451,019
7,451,055
Two structures with the same name, how do u choose one?
I have int function(string n){ vector<int> n; } I want to call functions using the vector n, but..for some reason it keeps calling the string n functions..I thought it would call the closest dat
int function(string n){ { vector<int> n; n.size(); //vector! } n.size(); //string! } Although really, just rename the variable. Don't ever have variables with the same name in the same scope. Ever. People will hate you, and then there's all those nasty surprises in the afterlife.
7,451,047
7,451,322
How to write an std::floor function from scratch
I would like to know how to write my own floor function to round a float down. Is it possible to do this by setting the bits of a float that represent the numbers after the comma to 0? If yes, then how can I access and modify those bits? Thanks.
You can do bit twiddling on floating point numbers, but getting it right depends on knowing exactly what the floating point binary representation is. For most machines these days its IEEE-754, which is reasonably straight-forward. For example IEEE-754 32-bit floats have 1 sign bit, 8 exponent bits, and 23 mantissa bi...
7,451,183
7,452,285
How to create image file from QGraphicsScene/QGraphicsView?
Given a QGraphicsScene, or QGraphicsView, is it possible to create an image file (preferably PNG or JPG)? If yes, how?
I have not tried this, but this is the idea of how to do it. You can do this in several ways One form is as follows: QGraphicsView* view = new QGraphicsView(scene,this); QString fileName = "file_name.png"; QPixmap pixMap = view->grab(view->sceneRect().toRect()); pixMap.save(fileName); //Uses QWidget::grab function to ...
7,451,335
7,533,549
OpenMP calls and directives allowed in firstprivate variable construction?
I have the following code which works on the compilers I have available (xlC and gcc) but I don't know if it is fully compliant (I didn't find anything in the OpenMP 3.0 spec that explicitly disallows it): #include <iostream> #include <vector> #include <omp.h> struct A { int tid; A() : tid(-1) { } A(const A&) { ...
I would just decouple (start of) the parallel region from the loop, and use private variable to keep tid: std::vector<int>::iterator it; int tid; #pragma omp parallel private(tid) { tid = omp_get_thread_num(); #pragma omp for for (it=v.begin(); it<v.end(); ++it) *it += tid; } Added: below are the...
7,451,406
24,781,512
Are digraphs and trigraphs in use today?
Given that there were once reasons to use digraphs and trigraphs in C and C++, does anyone put them in code being written today? Is there any substantial amount of legacy code still under maintenance that contains them? (Note: Here, "digraph" does not mean "directed graph." Both digraph and trigraph have multiple mean...
There is a proposal pending for C++1z (the next standard after C++1y will be standardized into -hopefully- C++14) that aims to remove trigraphs from the Standard. They did a case study on an otherwise undisclosed large codebase: Case study The uses of trigraph-like constructs in one large codebase were examined. We ...
7,451,533
7,451,552
Question about my design for my C++ homework
First, this is for my CS296 class, so everything has to be in the main() function and I can't use anything but loops, switch, and if statements. Anyway, the program ask the user to enter the number of students in a class, followed by their names. It then displays which student should be at the front of the line and whi...
No, that seems fine. Specs called for entering a count and then entering that many students which is exactly what you've done. Don't get me wrong, the program is bad but that's because of ridiculous specs like "everything has to be in the main() function", not anything to do with your implementation. For this level of ...
7,451,546
7,451,573
Is it possible to Initialize a static member array dynamically
There are so many questions about initializing static members in C++, and yet I couldn't find this one. class Node { private: static const int INITIAL_SIZE = 100; static Node* node_space; static int OUT_OF_BOUNDS = 0; static Node BAD_NODE; }; Node* Node::node_space = new Node[Node::INITIAL_SIZE]; ...
What you may want to-do here, if you only have a single static data-object, but you want to dynamically initialize it, is to create a singleton object as a wrapper around your Node class. Basically what occurs with a singleton is you create a single version of a class that is initialized with a normal class constructo...
7,451,731
7,451,739
How is a dynamic array different from statically bound array in C++?
I am learning C++ and I just read about dynamic arrays and how it lets you set the length of an array during runtime rather than during compile time. However, you don't need a dynamic array to do this. So what is the point of a dynamic array; when would you use it? I feel like I am missing something obvious so any insi...
I don't think you can do that in C++. Only C99 allows variable-length arrays. Does this even compile? Were you talking about the vector class? EDIT: It does not compile in Visual Studio 2010: 1>..\main.c(207): error C2057: expected constant expression 1>..\main.c(207): error C2466: cannot allocate an array of constant ...
7,452,041
7,454,010
Explanation of cvSeqPartition()?
I have no idea what this does could someone explain this to me in SIMPLE terms? Please don't give me complicated mathematical answers or something too technical, just its general purpose Thanks
// This function splits the input sequence or set into one or more equivalence classes. // is_equal(a,b,...) returns non-zero if the two sequence elements // belong to the same class. The function returns sequence of integers - // 0-based class indexes for each element. // // The algorithm is described in "Introductio...
7,452,061
7,452,132
Dynamic Casts or Function Overloads?
Consider the following abstract class: class Abstract { public: // ... virtual bool operator==(const Abstract& rhs) const = 0; // ... }; Now suppose I'm creating multiple derived classes from this abstract class. However, each one uses a different algorithm when comparing with its own type, and a generic...
I think that option B is what you are looking for if you're expecting the == operator to use the dynamic type of the argument. For example: class base { public: virtual bool operator ==( const base& other ) = 0; }; class derived : public base { public: bool operator ==( const base& other ) { return false; } bool...
7,452,274
7,452,659
Faster way to scale SDL view than SDL_gfx zoomSurface?
I'm programming a game with SDL. I've implemented scalable window size via the SDL_gfx library's zoomSurface function, but boy does the framerate take a hit (presumably because every time you call zoomSurface, it creates an entirely new SDL_Surface instance, and in order to be continuously zoomed you need to call it ev...
SDL doesn't really support this. The most 'correct' way is to use the underlying graphics API (OpenGL or DirectX) to do the scaling. For example, calling glScale{f,d} if you're using OpenGL under the hood. I believe SDL on Windows is compiled to use DirectX, however, so this isn't a portable solution. An alternative is...
7,452,570
7,452,590
Creating and displaying a bitmap
What would be the easiest, most cross-platform way to create a bitmap (2D array of integers, or a quad-tree) and display it on the screen? I would also like to be able to save it as a file. Thanks
It has to be said -- the easiest and most cross platform approach is probably to use printf, with something like: // y and x loops would surround this... unsigned char grayscaleValue = /* something */; printf("%c",grayscaleValue < 128 ? " " : "X"); You could use more than two brightness values. I also like both Qt and...
7,452,849
7,465,863
default arguments for templated function
I have a function which accepts an operator object as an argument. This operator is treated sort of like a callback. The type of this operator object is a template parameter. How can I specify a default parameter for it? #include <iostream> template<class IT, class NT> class A { public: class DefaultHandler ...
Unfortunately, C++03 14.8.2.4/17 says: A template type-parameter cannot be deduced from the type of a function default argument and provides an example like so: template <class T> void f(T = 5, T = 7); void g() { f(1); // OK: call f<int>(1,7) f(); // error: cannot deduce...
7,452,868
7,452,894
Calculate sin(x) as the form of series in c++
We know that sin(x)=x-x^3/3!+x^5/5!-x^7/7!+x^9/9! and so on. I have written this code: #include <iostream> #include <math.h> using namespace std; const int m=19; int factorial(int n) { if (n==0){ return 1;} return n*factorial(n-1); } int main() { float x; cin >> x; float sum=0; int k=1; f...
The problem is that you're running out of precision due to destructive cancellation. You have an alternating series where some of the terms get very large. But those terms cancel each other out to a small result. Since float has limited precision, your round off error is larger than your final value. You can "reduce" t...
7,453,269
7,453,276
class with virtual functions takes more space
There is such code: #include <iostream> class A{ int a; int fun(){} }; class B{ int a; virtual int fun(){} }; int main() { std::cout << sizeof(A) << " " << sizeof(B) << std::endl; std::cin.get(); return 0; } The output is: 4 8 Why class B is 4 bytes bigger than class A?
Any class with a virtual function needs a pointer to the vtable for that class. Therefore, there is a hidden member that's the size of the pointer. http://en.wikipedia.org/wiki/Virtual_method_table
7,453,431
7,453,465
Get random numbers in specific ranges given a 'getrand100()' function
For getting the random numbers I have a function getrand100() which returns a random number in the range of 1-100. How can I get a random number between ranges 1-20 and 1-200 with the same function? For 1-20 I can apply: if(num>=1 && num <=20) then accept else reject But what should I do for the 1-200 range?
I would propose 1 + getrand100() % 20 for the first case (20) and (getrand100()%2)*100 + getrand100() for the latter (200).
7,453,572
7,455,373
How to compile Eigen in iPhone
I want to compile Eigen and use it in iPhone with NEON features. How to compile Eigen in iPhone? Do In need to compile for specific ARM chip? And do I need to modify build script? Cheers.
Since explicit vectorization for ARM NEON is supported out of the box in recent versions of Eigen I'm guessing you shouldn't have to do anything special at all. The section on installation in the manual reads: In order to use Eigen, you just need to download and extract Eigen's source code (see the wiki for download i...
7,453,583
7,453,660
delete cout; delete cin; do not give compilation error - a flaw in the Standard library?
Will the following give a compilation error? delete cout; delete cin; The answer is : No. It is a flaw in the implementation of stream classes from the Standard library. They have the following conversion function to void* type, which means, all stream objects can be implicitly converted to void*: operator void * (...
It has apparently been fixed. At least, in N3290 you have std::basic_ios::operator bool instead of that void* conversion, and this operator bool is declared explicit. Note that C++98/C++03 did not support explicit type conversion operators, but C++11 does. An explicit type conversion operator N3290 §12.3.2/2; is onl...
7,453,600
7,453,625
How to set std::tuple element by index?
One can get an element from std::tuple by index using std::get. Analogically, how to set tuple's element by index?
std::get returns a reference to the value. So you set the value like this: std::get<0>(myTuple) = newValue; This of course assumes that myTuple is non-const. You can even move items out of a tuple via std::move, by invoking it on the tuple: auto movedTo = std::get<0>(std::move(myTuple));
7,453,977
7,454,268
Which data structure to use for huge but constant dictionary in C++
I have to use a huge dictionary with integer (or enum) keys and string values. But this is totally constant. No way to change in runtime. Is there a way (using templates etc.) to retrieve dictionary data at compile time instead of using existing dictionary structure?
Clang and LLVM have solved your issue by generating tables containing their objects, using a combination of code generation and preprocessor trickery. You can skip either step, depending on your own setup. For example: // records.inc EXPAND_RECORD(Foo, "Foo", 4); EXPAND_RECORD(Bar, "Bar", 18); EXPAND_RECORD(Bar2, "Bar"...
7,454,061
7,488,350
Where i can download gcc and glib for Cygwin?
I'm writting application for embedded system. Where i can download gcc version 3.4.3 with glib version 2.3.4 for Cygwin ? I have download cygwin-gcc-3.3.6-glibc-2.3.2-linux.tar.bz2 but this version isn't suitable for me...
Sometimes linux distributions have a 'compat' packages which make older libraries available. Try searching cygwin for the version of libstdc++ you're looking for.
7,454,168
7,454,671
boost::bind can't work with conditional expression?
When I uncomment the conditional expression, the program will fail to compile under visual c++ 2008. #include <iostream> #include <boost/bind.hpp> #include <boost/thread.hpp> typedef boost::function<void(int, int)> vii_t; typedef boost::function<void(int)> vi_t; void foo(int a, int b){} void bar(int a){} int main(int ...
In the expression c ? x : y x and y must be of the same type, or one must be convertible to the other. That common type is the type of the whole expression. Presumably, boost::bind with different number of parameters return different types that are not convertible to each other. That they both might be convertible to v...
7,454,238
7,454,269
Correct way to use getopt/long_getopt
I know this topic has been beaten to death but I still couldn't find what I am searching for. I need to parse command line arguments in C++. I cannot use Boost and using long_getopt The issue is in casting, when I simply print the arguments , it works as expected in the loop but the value assigned to variables is not ...
You are casting a string (char*) value to integer values, which is very different from parsing it. By casting, you use the ASCII value of the first character as a numerical value, while by parsing a string, you try to interpret the whole string as a text and convert it into a machine-readable value format. You need to ...
7,454,376
7,454,412
Can i use all of c++ functionality using VISUAL c++?
Im having trouble finding a way to obtain wifi info such as RSSI and SSID using c# .net. C++ Has access to the Native WIFI api. If I opt to use VISUAL C++ instead of another compiler do i only have access to the .net classes or do i have access to the full c++ spectrum. Many Thanks
Lifting from the Wikipedia article: Microsoft Visual C++ (often abbreviated as MSVC or VC++) is a commercial, integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages So in short, yes, Visual C++ is simply an IDE which allows you to work with the C++ progra...
7,454,497
7,454,607
How to link to the carbon with gcc in mac?
I develope an application in mac that uses carbon. My IDE is Code::Blocks (GCC compiler). My code compiles successfully but does not link. #include <iostream> #include <Carbon/Carbon.h> using namespace std; int main() { //CGEventFlags flags = CGEventSourceFlagsState(1); while(true) { CGEventSourc...
A simple -framework Carbon flag for gcc should do the trick, according to various sources around the internet. Cannot verify this, though. This question seems slightly similar.
7,454,516
7,454,556
Create process and run code after the process returns a message (C++)
I am trying to create a new process (which shouldn't block the current program) in C++, and to have the C++ listen for a message. When the message arrives, I want to run some more code. I have this method which executes the command and results the result immediately, but I have no idea how to make one that runs code wh...
You could put the code which executes the process in a separate thread, that way the primary thread can continue to execute while the secondary thread starts the process and waits for the message from the child process.
7,454,772
7,455,059
How to create a Text Editor in c++ without using any graphics library?
I started out by declaring a string and storing all the text entered by the user in it. Then I transfer to a file. I cant figure out how add a line break to the input. I am just a beginner.. example code : #include <iostream> #include <fstream> using namespace std; int main() { string x; string y; ofstre...
To add a line break to the output, you need to write the string "\n" to it. ofstream a_file("example.txt"); string line; if (getline(cin, line)) { a_file << line; a_file << "\n"; } It's as simple as that. You can also combine the last two statements into one: a_file << line << "\n"; But if you want to add the li...
7,454,990
7,455,043
Why can't we pass arrays to function by value?
Apparently, we can pass complex class instances to functions, but why can't we pass arrays to functions?
The origin is historical. The problem is that the rule "arrays decay into pointers, when passed to a function" is simple. Copying arrays would be kind of complicated and not very clear, since the behavior would change for different parameters and different function declarations. Note that you can still do an indirect p...
7,455,543
7,455,567
How do multidimensional arrays in C++ function?
Possible Duplicate: How do I use arrays in C++? To put it simply, is a multidimensional array in C++ an array of arrays or is it simply a single array which behaves like it's multidimensional? A friend of mine explained that arrays in C++ are simply constant pointers, and that multidimensional arrays are also consta...
The brace-list initializer only works during initialization, and it cannot be used for assignment, as you seem to attempt. Instead, just initialize the multi-dimensional array all at once: int line[2][2] = { {100, 100}, {200, 200} }; In response to your first sentence: Arrays are arrays and pointers are pointers, and ...
7,455,570
7,455,649
How to pass Serial object by reference to my class in Arduino?
I have been reading up a couple of days now about pointers, references and dereferences in C/C++ targeted for the Arduino and can't fully udnerstand what I am missing. I have my sketch which has a setup of Serial.begin(9600); //Just for logging. Serial1.begin(9600); //Arduino Mega-> Other Device I use a wrapper cl...
You're mixing C++ references and pointers. It looks from that example snippet that you should be using pointers, so I have made my answer follow that style. References would probably be a better choice though. Your code should look something like this: myclass.h myClass(HardwareSerial *serial); // ctor HardwareSerial *...
7,455,673
7,459,508
Assertion error on priority queue with custom class pointers
I'm implementing a A* search algorithm but I keep running into problems with the priority queue. I have implemented a custom comparator for the priority queue according to this article This is the relevant code: class CNode; struct CompareNode : public binary_function<CNode*, CNode*, bool> { bool operator()(const ...
Thanks for the help. Turns out I did not rebuild the heap after changing the cost of nodes in the priority queue. Calling make_heap(const_cast<CNode**>(&open.top()), const_cast<CNode**>(&open.top()) + open.size(), CompareNode()); after every modification to the pq solved the problem.
7,455,885
7,455,969
Exceptions when allocating memory
I've just learnt than you could throw or handle exceptions if memory allocation wasn't successful. But on here, I haven't seen many people handle exceptions when using new operator. For example: Isn't the following likely to fail at any point in program? char* c = new char[1000]; delete []c; And how should you handle ...
The reason most people don't handle a bad_alloc exception explicitly is because most of the time there isn't a lot most user applications can do to recover from low memory conditions so letting the exception propogate outwards is the most sensible thing to do. You should only explicitly catch an exception if there is a...
7,455,946
7,456,294
equivalent of fgets on a buffer?
I was originally parsing a file line by line using fgets(). Now I changed things so that I already have my entire file in a buffer. I still like to read that buffer line by line for parsing purposes. Is there something designed for this, or do I need to make a loop that inspects for 0x0A chars at this point?
memchr (with a little bit of your own wrapper code, ending with memcpy) is the exact equivalent - like fgets it takes a maximum length it will process (should be the min of the remaining input buffer size and the size of your output buffer) and scans until it hits the desired character (which will be '\n') or runs out ...
7,455,982
7,456,012
Is stl vector concurrent read thread-safe?
I am working on a application where huge number of threads are expected to iterate over set of string values and try to match it's own data with the data available in the list. I am looking for following use case: Vector is initialized with few elements of type std::string. (Lets say object name is strList). strList w...
YES for the scenario you mention, it is perfectly Thread Safe. Actually, STL is not a correct way of referring it. It is the C++ Standard Library. The C++03 Standard does not talk about concurrency at all, So the concurrency aspect is left out as an implementation detail for compilers. So the documentation that comes ...
7,456,346
7,456,622
Mixing debug and release in MSVC?
I got a program that has a quite simple 'load up' function that takes about 30 seconds (3M triangles that goes into std containers). It works perfectly well. The rest doesn't always (it is not finished) so I debug a lot I make a lot of changes and so on which means restarting quite often. Is there any secret technique ...
Debug builds tend to be very slow on Visual C++. There are a few reasons for this: the most obvious is that the code is not optimized the memory allocation functions in the debug CRT library perform additional checks to detect heap corruption and other issues, so they are slower. many STL functions perform additional ...
7,456,363
7,456,424
module handle through base address
Im' trying to get the module handle of a module in C++ on windows. My problem is that I have only the base address and File handle of the module but GetModuleHandle receives only its name as a parameter. Is there a way in c++ on windows to obtain a module handle without knwoing the module's name?
Have you tried using GetModuleHandleEx (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)lpBaseAddress, &module)?
7,456,469
7,456,513
questions about writing an operating system
I have some very specific questions about writing operating systems that I was hoping could get answered: How much assembly code would I need to write to load a minimal C Kernel if I use GRUB as a boot loader? My kernel will be written in C, It will load a command line shell that I wrote in C++, it does not make any A...
1: You should only need a small amount of assembly to handle the boot process and load the C code. Shouldn't be more than like 20-30 lines I think. 2-4: I haven't really used C++ with OS dev, but I think I remember reading that it takes more work to get it running somewhere. Sorry I can't be of more help. 5: You "can" ...
7,456,541
7,456,560
Does the 'private' access modifier give the compiler more room for optimization?
Does it allow the compiler to inline it, knowing that only functions in the same class can access it? Or is it only for the programmer's convenience?
The compiler can (but is not required to) optimize as you suggest, but that's not the point. The point of access modifiers is to catch certain classes (no pun intended) of programming errors at compile time. Private functions are functions that, if someone called them from outside the class, that would be a bug, and ...
7,456,699
7,458,057
Failed to link libstlport_shared, even though it's present...?
I'm just about ready to start banging my head off the wall here. I've read every SO thread I can find about this issue, read every single google result on the issue and can't find squat. I'm building an android app where I've written a 2D engine in C++ and I'm using the shared version of stlport with NDK r6b. The .so f...
Okay well, it seems that I've found a solution, sort of. I basically just abandoned using the shared version of the stl port and switched to static. I then rebuilt the static version using the Application.mk flag: STLPORT_FORCE_REBUILD := true However, I still had weird issues. It compiled once and installed fine. Then...
7,456,778
7,456,816
Function in C++ returns by value or by reference?
When a function (callee) returns a quantity to the caller function, is it returned by value or by reference? The thing is I have written a function which builds a very large vector of when called. I want to return this big vector to the calling function , ( in this case main() ) by constant reference so I can do some f...
C++ functions can return by value, by reference (but don't return a local variable by reference), or by pointer (again, don't return a local by pointer). When returning by value, the compiler can often do optimizations that make it equally as fast as returning by reference, without the problem of dangling references. ...
7,456,902
7,456,920
Long Vs. Int C/C++ - What's The Point?
As I've learned recently, a long in C/C++ is the same length as an int. To put it simply, why? It seems almost pointless to even include the datatype in the language. Does it have any uses specific to it that an int doesn't have? I know we can declare a 64-bit int like so: long long x = 0; But why does the languag...
When writing in C or C++, every datatype is architecture and compiler specific. On one system int is 32, but you can find ones where it is 16 or 64; it's not defined, so it's up to compiler. As for long and int, it comes from times, where standard integer was 16bit, where long was 32 bit integer - and it indeed was lon...
7,456,943
7,457,015
C++ Templates Question
Can someone explain the output of the following code? #include <iostream> template <class T> void assign(T& t1, T& t2){ std::cout << "First method"<< std::endl; t1 = t2; } template <class T> void assign(T& t1, const T& t2) { std::cout << "Second method"<< std::endl; t1 = t2; } class A { public: A...
An expression doesn't only have a value and a type, but it also has a value category. This category can be An lvalue: These expressions generally refer to declared objects, references, functions or dereference results of pointers. An xvalue: These are the result of generating an unnamed rvalue reference. Rvalue refer...
7,456,989
7,457,215
Implicitly-declared Move-Operations do not fallback to Copy?
Do I read N3291 "12.8.(11/15/28) Copying and moving class objects class.copy]" correct that the implicitly-declared move constructor does an element-wise move of all non-static data-members (probably via respectively defined T(T&&) and if any non-static data-member can not be moved, the implicit move-constructor will...
You read it incorrectly. This would break lots of C++03 classes in cases such as the following Question getQuestion(); Question q(getQuestion()); // use of deleted move constructor! Instead, the FDIS says that a move constructor will be declared iff {there is no user declared {copy constructor, {copy, move} assignment...