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
5,691,176
5,691,512
Segmentation fault in a Binary Tree
Either I've been staring at this code for way too long or I just can't figure this one out. but when I use an 8000 number text file in descending order; 8000, 7999, ... I get a segmentation fault in the height function. If someone could take a look I would be so greatful. Thanks. int BST::height(TreeNode* node) ...
If you have a sorted list of numbers then you might be storing this in a list (worst case for a tree is O(n) unless it is balanced). In this case, your recursive routine will be recursing 8000 times with a stack depth of 8000. I don't know if this is enough to overflow the stack, but in any case you should take a loo...
5,691,231
5,691,267
Getting error about an undefined reference, even though it is defined
//Double.h file #ifndef Double_h #define Double_h int add(int x,int y); #endif //Double.cpp file int add(int x,int y) { return x + y; } //main.cpp file #include <iostream> #include "Double.h" using namespace std; int main() { cout << add(7,8)<<endl; return 0; } It's su...
Make sure that your header file Double.h is in the proper folder when you are compiling main.cpp (are they by chance duplicated and your main.cpp is seeing a wrong file ?). Your Double.cpp also should include Double.h. Also make sure you compile both main.cpp and double.cpp together for generating final executable outp...
5,691,336
5,691,348
File system iterator for C++
I'd like a basic C++ STL-like container for the filesystem. e.g. std::filesystem::const_iterator i = filesys.begin(); i->file_name(); i->full_path(), etc.. Does something like that exist?
Yes. It exists. Almost similar, atleast which can work with the STL iterators and containers. boost::filesystem Example: path p ("directorypath"); std::vector<path> v; std::copy(directory_iterator(p), directory_iterator(), std::back_inserter(v)); for (std::vector<path>::const_iterator it=v.begin()...
5,691,384
5,691,432
Most efficient data structure to store an XML tree in C++
I'm doing some work with XML in C++, and I would like to know what the best data structure to store XML data is. Please don't just tell me what you've heard of in the past; I'd like to know what the most efficient structure is. I would like to be able to store any arbitrary XML tree (assuming it is valid), with minimal...
The most efficient structure would a set of classes derived from the DTD or the Schema that defines the particular XML instances you intend to process. (Surely you aren't going to process arbitrary XML?) Tags are represented by classes. Single children can be represented by fields. Childen with min...max arity can ...
5,691,389
5,691,417
Passing function as class template argument
Without knowing a function's type, I am declaring its pointer with below technique and initializing a function pointer. template<typename T> struct Declare { typedef T Type; }; // for declaring any func ptr void fun () {} int main () { Declare<fun>::Type pf = &fun; // can't use C++0x 'auto' } However, it gives co...
Is it invalid to pass a function into a class template as above? Yes. Because what you, in other words, want the compiler to deduce the type parameter for the class template, which simply not possible in C++. Recall that fun itself isn't a type, its a value of type void (*)(). But your class template expects type, no...
5,691,445
5,691,590
Seg fault, need help reading a core dump
I have an error with an assignment, of which I get a seg fault, that when reading the core dump gives this: #0 0xb781eb27 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const () from /usr/lib/libstdc++.so.6 This is the code snippet I believe it is referring to. bool flightmap::GetNe...
bt is correct for a backtrace. You can see there the error starts in sortedListClass::Retrieve line 167. The next entry in the backtrace (working back up to #0) is for operator ==, which means the == on line 167 is the cause of the crash. There are a few == calls in the code you posted, so if you can edit your post a...
5,691,446
5,691,507
Child doesn't terminate correctly in fork
I am writing a c program for a class that is a small shell. The user inputs a command, and the code executes it using the exec() function. I need to have a fork in the process so all the work is done in the child process. The only problem is that the child won't terminate properly and execute the command. When I r...
You said: Its the line of code where I call strcpy. You haven't allocated any memory to store your string. The first parameter to strcpy is the destination pointer, and you're using an uninitialized value for that pointer. From the strcpy man page: char *strcpy(char *s1, const char *s2); The stpcpy() and strcpy()...
5,691,740
5,691,755
Initialising a struct that contains a vector of itself
I have a menu system that I want to initialise from constant data. A MenuItem can contain, as a sub-menu, a vector of MenuItems. But it only works up to a point. Here are the bare bones of the problem: #include <vector> struct S { std::vector<S> v ; } ; S s1 = { } ; S s2 = { { } } ; S s3 = { { { } } } ; g++ -std=c++0...
GMan is correct in his comment: in the declaration of S::v in your code, S is still incomplete. A type must be complete to be usable as the value type in an STL container. For more information see Matt Austern's article "The Standard Librarian: Containers of Incomplete Types." If you were to switch to a container th...
5,692,005
5,692,027
Frequency count in a linked list
I have the following struct for a linked list: struct Node { int type; int otherInfo; Node * next; } I want to create a sorted (eventually) linked list that keeps track of how many times each "type" appears. An example node would be: struct Node2 { int type; int frequency; //A linked list to ke...
Sounds like what you really need is a map or a basic binary search tree. The key type will be your type value, and the value type will hold your frequency.
5,692,009
5,692,617
How do I find out if a path specifies an actual file?
I have a function as follows: DWORD stats = GetFileAttributesA(path); return (stats != INVALID_FILE_ATTRIBUTES) && !(stats & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0; The problem is that a SQL Connection string: "Driver={SQL Server Native Client 10.0};server=localhost;database=NorthWindDB;Trusted_Connection=yes;" somehow is ...
Since all else seems to fail, here is a completely different approach: try system("dir \"path_to_check\"") and check its return value (works on my machine :) See also system().
5,692,187
5,692,257
STL map insertion efficiency: [] vs. insert
There are two ways of map insertion: m[key] = val; Or m.insert(make_pair(key, val)); My question is, which operation is faster? People usually say the first one is slower, because the STL Standard at first 'insert' a default element if 'key' is not existing in map and then assign 'val' to the default element. But I d...
Both accomplish different things. m[key] = val; Will insert a new key-value pair if the key doesn't exist already, or it will overwrite the old value mapped to the key if it already exists. m.insert(make_pair(key, val)); Will only insert the pair if key doesn't exist yet, it will never overwrite the old value. So...
5,692,426
5,692,467
How to check whether a huge floating point number is an integer?
I have a very large floating point number (around 20 digits) and I want to check whether it is an integer or not. For example, if I have a number like 154.0 then it is an integer while 154.123123 is not an integer. I need to check for very huge floating point numbers (20 digits or more) which means I can't first conve...
Well, what's "huge"? If the number is really huge in a sense that the number of digits is greater than the number representable by the mantissa of your floating-point number, then your floating-point number is always an integer. For example, the IEEE 754 double-precision format has a 52-bit mantissa, which is sufficie...
5,692,444
5,692,592
What is the fastest algorithm to return the power of a number which is a power of 2?
Given n = 2^k, how can I find k assuming n is 32-bit integer using C/C++ bitwise?
Well, you could use the fact that the binary exponent is explicitly stored in floating point numbers: unsigned log2(unsigned x) { float f = x; memcpy(&x, &f, sizeof x); return (x >> 23) - 127; } I don't know how fast this is, and it surely is not the most portable solution, but I find it quite interesting....
5,692,470
5,692,512
Static linking with a Qt project
I've got a Qt project I've built in Visual Studio 2010 Professional. However, when I run it (in either Debug or Release mode) it asks for a few Qt dll's. It works if I supply the dll's and throw them into System32, but my question is, how do I make it so that all libraries are included in the .exe? I have all of the st...
The correct way is to create a setup program that installs the Qt libraries along with your application. Visual Studio comes with a setup project template that you can use to create your own customized installer easily. Static linking is rarely a good option, for numerous reasons. However, if you insist on static linki...
5,692,471
5,692,499
Bootstrapper (pre-installer) for .net apps
I'm trying to develop a small app like Flash Player updater. I want users to download this executable first and so I can check if user has required .net framework and other prerequisites (sql server, crystal reports etc.). Then by this app I'll download missing ones and install them. So which language I must use (c, c+...
It seems you're looking for a bootstrapper. Several solutions target the .NET framework, including the popular (and free) dotNetInstaller.
5,693,136
5,693,224
Is it possible to use UTF-8 encoding by default in Visual Studio 2008?
Possible Duplicate: How to create a UTF-8 string literal in Visual C++ 2008 Is it possible to force Visual Studio to use UTF-8 encoding for all strings by default? For example have wchar_t *txt="hello"; encoded in utf8
This blog article looks promising: UTF-8 strings and Visual C++ Most of the important content is still there, even though some of the pictures are broken. In short: First step, you have to make sure the source file is UTF-8 encoded with the byte order mark (BOM). The BOM is an extremely important thing, without it th...
5,693,243
5,693,304
Error in writing binary files in C++
I try to open a binary file for both reading and writing (flag: ios_base::binary | ios_base::in | ios_base::out). My file already exists and its content is: 123 There is no problem in reading of the file, but writing the file does not work after closing the file. The file content has no change. It seems fstream.write()...
You need to position the write pointer correcty: stream.seekp( 1 ); stream.write(&ch, 1/*size*/);
5,693,265
5,694,304
Merging AVL trees using an empty tree (C++ templates)
As part of an AVL template I am working on (C++ templates) I was trying to merge 2 AVL trees in O(n1+n2) complexity when n1+n2 is the total elements in both trees. I thought about the next algorithm. Inorder traversal on the 1st tree and build an array/list - O(n1) Inorder traversal on the 2nd tree and build an array/...
If the nodes issue by the merge sort are stored in a vector, it can be done relatively easily. Your nodes are already sorted, so you can "insert" the nodes in the following fashion: Build your root node from the element at 1/2 of the array; Build the root's child nodes using the elements at 1/4 and 3/4 of the array; ...
5,693,432
5,693,588
Making auto_cast safe
GMan has posted a code for the delicious auto_cast “operator” that allows to write code such as the following in C++: float f = 4.0f; int i = auto_cast(f); // instead of: int j = static_cast<int>(f); or, more saliently, T x = value; typename nested_type<with, template_arguments>::type y = auto_cast(x); // instead of t...
It appears you want to use the T{u} form of initialization. template <typename U> operator U() { return U{std::forward<T>(mX)}; } One of the reasons for these uniform initialization was that to use explicit constructors for creating a temporary, you need a cast aka T(u). With T{u} that problem was solved. For C++...
5,693,455
5,693,470
Random Binary Generator (not pseudo)
How do I generate random binary values lets say 10 digits 0010101001 and I want to call this C1 I then want to create another one called C2 same again random 10 digit binary number. C# is my language of choice. Is there a bitset class for c# something simple would be nice, like int C1 for ( int C1 = 0; <=10; C1++) ...
function randomInt(max) // produces integer with uniform distribution between [0,max) # this should be in your standard library # though perhaps not by this name; and you may need to # initialize and maybe randomly seed your RNG beforehand myRandomBinaryNumber = randomInt(2^10) // then cast it if requ...
5,693,477
5,698,663
C++CLI. Are native parts written in pure C++ but compiled in CLI as fast as pure native C++?
I want to delegate audio computing to a C++ layer, but handle and edit audio content through a WPF GUI. I have had a brief look at C++/CLI, and I wanted to know: should I use C++/CLI as an intermediate layer between C# GUI and C++ audio management or should I simply put my code in C++/CLI and expect it to be compiled ...
In C++/CLI, managed types (ref class for example) and their members are compiled to MSIL. This means no use of SIMD, and much less optimization (at least in the current version of .NET, and the reasons given by Microsoft aren't changing any time soon, although they could change their assessment of the tradeoffs). Nati...
5,693,581
5,693,609
how to transfer image (HBITMAP) of application to another application?
i tryed to transfer image data using device contexts and handle to bitmaps but the handles is invalid in another application. I need to transfer image data or DC data from one application to another. How this can be accomplished?
Looks like a duplicate here of why they're invalid: Sharing HDC between different processes And here's a response on techniques to share image data: Most efficient way to send images across processes
5,693,597
5,693,807
C++ template programming struct vs template
To provide a functionality for a class cls, say, 'add', following are the types I decided: struct add { add sum(add other) { ... } }; vs. template<typename Add> Add sum(Add one, Add two) { ... } Which approach should be preferred, what advantages do the first have over the second and vice versa?
Which approach should be preferred, what advantages do the first have over the second and vice versa? I believe the question does not have a straightforward answer. I think this goes down to the Generic Vs Object Oriented Programming battle. See also On the Tension Between Object-Oriented and Generic Programming in C++...
5,693,869
5,947,385
how to send a multicast message to couple of peers in C windows
i'm writing a program in C for windows that has to send messages to couple of peers, each with different IP and port. no need to guarantee the delivery of the messages. so i'm looking to send a multicast message not limited to same LAN that i'm on. How do i do it ? do i have to send each message separately to each of t...
There are two common ways to do this. UDP Unicast You maintain a list of IP address receivers in your program, iterating over each receiver and sending a copy of every datagram to each receiver. IP Multicast The list of receivers has to exist somewhere. If you use IP Multicast, then the list of receivers is maintained...
5,693,937
5,693,963
how to solve 0-1 package problem by iteration?
Possible Duplicate: Design patterns for converting recursive algorithms to iterative ones I can only figure out a recursive way: how to transform it into iteration? for simplicity, my recursive way only find the result value. #include<iostream> //0-1 bag using namespace std; int weight[5]={50,30,45,25,5}; int value[...
Given what you really want, I think this is a duplicate question of Design patterns for converting recursive algorithms to iterative ones
5,693,954
5,693,961
C++: "error: expected class-name before ‘{’ token" when inheriting a template class
I've looked around for a solution to my problem and found lots about cyclic references and namespace issues (neither apply in my case), but nothing like the problem I'm having. I have a template class defined and implemented in maths/matrix.h: template<class T> class Matrix { public: // constructors, destructors an...
You need to inherit from the concrete class, i.e. from Matrix<T>, not merely Matrix: template<class T> class Vector : public Matrix<T> { … };
5,694,015
5,694,031
Cannot correctly compare two numbers
unsigned long long value = 0; bool result = value >= std::numeric_limits<signed int>::min(); This should give true but gives false? Why and how can I fix it?
The int converts to an unsigned int for comparison. You could cast your unsigned long long to a long long. 5/9: Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type...
5,694,036
5,694,152
Is there any reference for LINUX and cross-platforms APIs?
First, I develope C++ applications that invokes OS APIs (like CopyFile, GetModuleFileName, ... in Windows). I don't want to develope GUI applications. my applications work like a SERVICE or CONSOLE in WINDOWS. Second, Standard C++ Libraries doesn't provide advance programming features like Threads, Network and even Fil...
There is a standard that should work (other than minor bugs or a few things that aren't implemented) across most Unix-type systems, including all Linux distros, the BSDs, Solaris, AIX, and so on. It's called POSIX or the Single Unix Specification; they are both basically equivalent, but published by different groups. Y...
5,694,058
5,694,222
Create a BITMAPINFO from a JPG/PNG file in Windows C++
I have a function in an API I am using that request a BITMAPINFO pointer. I am suppose to give this function an image. My images are JPG/PNGs. Suppose I transform them to BMP files, I have still no clue on how to set up this struct. Is there a windows API that I can use for it?
You can use GDI+ for this. Read BMP/JPG/PNG/GIF using Gdiplus::Bitmap::FromFile to load and Gdiplus::Bitmap::GetHBITMAP to access HBITMAP and then BITMAPINFO
5,694,190
5,694,199
Boost.Filesystem how to find out in which directory your executable is?
So I run my app. I need for it to know where its executable is. How to find path to it using Boost.Filesystem?
If you mean from inside the executable that you're running, you can use boost::filesystem::current_path()
5,694,255
5,694,408
Boost how to create a map for types selection?
so i use BOOST.EXTENTION to load modules. I have a special file that describes each module. I read variables from that file. so such example: shared_library m("my_module_name"); // Call a function that returns an int and takes a float parameter. int result = m.get<int, float>("function_name")(5.0f); m.close(); for me...
For that, you would need a heterogeneous map - that is, its elements can be of different types. Furthermore you would need the ability to return types from functions, not just variables. Now, a heterogeneous map would be possible with Boost.Variant or a simple union, but that binds it to compile time: we need to kno...
5,694,265
5,694,490
How expensive are dynamic casts in C++?
For my GUI API which works with a variety of backends (sdl, gl, d3d, etc) I want to dynamically cast the generic type image to whatever it may happen to be. So the bottom line is, I would be doing around 20 * 60fps dynamic casts per second. How expensive is a dynamic cast? Will I notice that it has a noticeable negativ...
1200 dynamic_casts per second is not likely to be a major performance problem. Are you doing one dynamic_cast per image, or a whole sequence of if statements until you find the actual type? If you're worried about performance, the fastest ways to implement polymorphism are: --- fastest --- Function overloading (compi...
5,694,700
5,704,121
how to subtract one path from another?
So... I have a base path and a new path.New path contains in it base path. I need to see what is different in new path. Like we had /home/ and new path is /home/apple/one and I need to get from it apple/one. note - when I would create some path from (homePath/diffPath) I need to get that /home/apple/one again. How to d...
Using stem() and parent_path() and walk backwards from the new path until we get back to base path, this works, but I am not sure if it is very safe. Be cautious, as the path "/home" and "/home/" are treated as different paths. The below only works if base path is /home (without trailing slash) and new path is guarante...
5,694,706
5,700,440
Py_Initialize fails - unable to load the file system codec
I am attempting to put together a simple c++ test project that uses an embedded python 3.2 interpreter. The project builds fine but Py_Initialize raises a fatal error: Fatal Python error: Py_Initialize: unable to load the file system codec LookupError: no codec search functions registered: can't find encoding Minimal ...
So, for some reason the python dll fails to locate the encodings module. The python.exe executable apparently finds it because it has the expected relative path. Modifying the search path works. The reason for all of this? Don't know but at least it works. I highly suspect a typo on my part somewhere, that's usually th...
5,694,707
5,694,757
sequence of conversions with contsructor-type conversions and conversion operators
I have read that a standard conversion can precede or follow a conversion implemented by a conversion operator or a contructor type conversion. On the other hand, a sequence of two conversion operators is not allowed a sequence of two contructor type conversions is not allowed I set out to test this an...
myString sYou(b); only involves one implicit conversion. The second conversion is explicit; you're calling the constructor. So it compiles. Conversely, the following will not compile: void func(myString blah) { ... } func(b); as this would require two implicit conversions.
5,694,843
5,695,050
template specialisation for a whole set of parameters
Possibly easy to solve, but its hard to find a solution to this: Is it possible to (partially) specialize for a whole set of types? In the example "Foo" should be partially specialized for (T,int) and (T,double) with only one template definition. What I can do is define a specialisation for (T,int). See below. But, it ...
If I understood your question correctly, then you can write a base class template and derive from it, as illustrated below: template <typename T, typename U> struct Foo_Base { static inline void apply(T a) { cout << "we are in the partial specialisation Foo_Base(T)" << endl; } }; template <typename T> struc...
5,694,973
5,695,612
C++ & Boost: I'm trying to find an example TCP program with a server that accepts connections from multiple clients
A chat program would be a good enough example. Just need a server that can accept multiple connections from the clients, and the server needs to be able to send messages to individual clients. I plan to turn this into a distributed computing program to work with multiple Neural Networks.
Asio is the Boost library that handles networking. There's a chat server example listed here.
5,695,082
5,695,126
Boost library acceptance in industry
I have seen lots of people suggesting the Boost library on Stack Overflow, so I am also thinking of learning it. But today I came across this link: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Boost I wanted to know about its acceptance in industry at a broader level. My current company also doesn't a...
Parts of Boost library is currently being accepted into the Standard library for C++0x and it is regarded as one of the top libs with a high industry acceptance. I'm actually unaware of any other library getting accepted into the C++ Standard Library on such a large scale. "Ten Boost libraries are already included in t...
5,695,146
5,695,176
What is cin doing inside argument of if?
Possible Duplicate: How would std::ostringstream convert to bool? #include<iostream.h> void main() { if(cin>>2) { // what is cin>>2 doing inside arg of if cout<<"if works"; } else { cout<<"else works"; } } We don't get error in this code.But Alwaysif statement works why? how?
cin >> 2 is invalid. cin >> integervar is valid, assuming that's what you mean? The standard library class ios which basic_istream (and thus cin) inherits from overloads operator void * (and operator!) to allow you to do such tests. operator void * returns 0 if failbit or badbit is set - aka the last extraction failed...
5,695,270
5,695,278
Linear multi-dimensional container
I require a linear vector container to behave like a multi-dimensional vector container. That is, a vector such as std::vector< std::vector< std::vector<int> > > be declared as std::vector<int> but behave as if it is multi-dimensional. This requires that I have set and get functions that allow accessing by multiple ind...
You have two choices: std::valarray (and its splice adapters), or boost::multi_array. The first one lacks many things, and is not often used (it should deserve more love though). The second one is heavy but quite clean to use. Also, you can have a look at Eigen if you intend to do linear algebra on those beasts. I can...
5,695,430
5,699,834
Undo functionality in an MVC design
I have a C++ application designed according to a classic Model-View-Controller pattern. The model is modified through a controller interface by an external source by means of a Command pattern. The commands are represented by an Action object (and its derivatives). Now I want to be able to undo the modifications, but m...
I also support the model layer containing undo support. There are quite a few ways to handle this in the model side. The first and most obvious is the models themselves remembering the history of the changes with "labels", but this is probably going to be difficult to synchronize for all your model classes. One other o...
5,695,456
5,695,476
Meaning of unsigned char (*pArray[10][10]);
What does the following declaration mean? unsigned char (*pArray[10][10]);
cdecl says: declare pArray as array 10 of array 10 of pointer to unsigned char Basically what you did was to declare a 2-D Array of pointers. See this question: Equivalent C declarations Now try to parse this: int **(*f)(int**,int**(*)(int **,int **)); [ In your mind of course ]
5,695,477
5,695,516
Using _BitScanReverse64
How to use _BitScanReverse64(unsigned long * Index, unsigned __int64 Mask) in order to find a first position set to 1 in integer?
Try this: unsigned __int64 mask = some_value; unsigned long index; unsigned char isNonzero = _BitScanReverse64(&index, mask); if (!isNonzero) { // index variable contains index of the first bit set to 1 }
5,695,645
5,695,890
Qt/MySQL++/vector iteration question
I've got a question regarding my vector iteration method within a Qt/MySQL++ project I'm working on at the moment. I've been using for loops to iterate through them so far, and being quite a beginner at C++, didn't realise that the generally accepted method is to use vector::iterator. I've been trying to see a way I ca...
Is it any serious reason you don't use QSql? I think QSqlQueryModel + QTableView can solve your problem without any vectors and iterators. A small example, right from Qt help: QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("SELECT name, salary FROM employee"); model->setHeaderData(0, Qt::Horizontal, tr...
5,695,658
5,695,713
Class creation [Begineer in programming]
It's my first code with classes. the dev c++ compiler find 4 errors so i need a help. I think there's something wrong in my concept may be This was the Header file "complex.h" class complex{ public: bool ReadComplex(); private: double real; double imag; }; This is the .cpp file #in...
Your first code with classes should be: class complex{ }; int main() { return(0); } Seriously. Get this to work, with no compiler warnings. Then add complexity a little at a time, and never add to code that doesn't work.
5,695,683
5,695,727
Is this a good design?
Right now my gui is abstract and basically has a Bitmap class which holds a void* to the native bitmap type. The way it works is I have an abstract bitmap loader which returns a void pointer to the image data given a path string. the loader is a static pointer in the Bitmap data type and is set by the user for whatever...
No, this is bad design. void* is what you definitely want to get rid of in C++. It is not fully clear to me what problem you are trying to solve. Is it only about abstracting I/O of images or also drawing of them? the typical solution to the I/O problem is to have ImageReader/ImageWriter abstract classes. Then their im...
5,695,700
5,695,793
GNU make: generate list of source files
Is it normal to generate the list of source files (.c, .cpp etc, not headers) automatically? How would you do it? I am thinking to use find and sed. EDIT: The project is a library. All source files are inside the project directory. No unrelated source files are there. All object files are generated using the same compi...
With GNU make you can use wildcards. See this question for an example.
5,695,705
5,695,741
Contents of the string after failed extraction from istream
If I do this: ifstream stream("somefilewhichopenssuccesfully.txt"); string token; if( stream >> token ) cout << token; else cout << token; Is the output in the second case guaranteed to be an empty string? I can't seem to find the answer to this on cplusplus.com. Thanks!
Is the output in the second case guaranteed to be an empty string? The answer is : no, because it depends, as described below. Since else block will be executed only if an attempt to read from the stream fails, and that can occur anytime in the course of reading. If it fails at the very first attempt, then there is ...
5,695,951
5,695,978
Qt anonymous signals
Is it possible to send signals to a slot without connecting them? There is a class that has a SLOT which shows some logs. For now we don't have any information how many classes will be use to send signals to this log slot, and we won't be able to address their objects to each other, but every objects might send logging...
You can call an object's (public) slot just like you call a normal member function. A connection is not necessary. Besides, you don't need to know in advance who will connect to a given slot. The connection can happen outside your class. (For public slots at least.)
5,696,033
5,696,204
C++ Make compile errors with Poco Library - Path Name containing spaces
I'm attempting to build/install/use the Poco C++ Libraries. I'm running Ubututu (Natty). I've compiled the static libraries which are working fine, but when I set the env var PROJECT_BASE to a path containing spaces, I get errors: make /bin/sh: Syntax error: Unterminated quoted string /bin/sh: Syntax error: Unterminate...
It requires great care and deliberate effort to make systems such as makefiles handle pathnames with spaces accurately. It can be done; it is not trivial. It is fairly clear that this package has not been so modified; it is like the majority of such packages. If you really want to make life hell for yourself, use a p...
5,696,072
5,696,120
how to trace a recursive function C++
#include <iostream> using namespace std; int g(float A[] , int L , int H) { if (L==H) if (A[L] > 0.0) return 1; else return 0; int M = (L+H)/2; return g(A,L,M)+ g(A,M+1,H); } int main (void) { float A[] = {-1.5 ,3.1,-5.2,0.0}; g(A,0,3); system ("pause"); ret...
It's a convoluted way to count how many numbers in the array is greater than 0. And if you try to run this in a compiler, the return value is 1 because the only number that is greater than 0 in the array is 3.1. at first run: {-1.5, 3.1, -5.2, 0.0} 0 1 2 3 L H then since L=0 and H=3, M = ...
5,696,142
5,696,187
How to share single critical section between two classes
I have some trouble finding the right design solution for a problem of sharing same critical section object between two classes in different class hierarchies. Imagine: class IB; class IA { public: void method_one(); }; class A : public IA { IB* m_ib; }; class IB { public: void method_two(); }; clas...
The simplest approach is : create an instance of critical_section in the main(), before creating any threads between which you want to share the object. Pass it to the constructors of the classes and store it as reference: class A : public IA { IB* m_ib; critical_section & m_cs; //reference public: ...
5,696,243
5,696,334
Dynamic data type choosing based on template
suppose I have an object like this: class Spline { public: Spline(std::size_t const dim); // Quite a few functions here. One of those: vec operator()(double const t) const; // Returns vector of dimension d } Now, at most uses of this class, the dimension will already be determined at compile time, thus it ...
Use a simple traits metastruct and specialize that. template<std::size_t dim> struct spline_return_traits{ typedef vec::fixed<dim> type; }; template<> struct spline_return_traits<0>{ // 0 is a special marker for runtime dimensions typedef vec type; }; template<std::size_t dim> class Spline_impl{ typedef typenam...
5,696,535
5,697,014
C++/Assembly IDE on Linux
What I'm looking for is an IDE that will run on Linux, that has support for C++ and x86 assembly syntax highlighting. I've already tried Code::Blocks, but that won't let me run the program as I need to, so that didn't work well. My needs: Able to compile programs by issuing a "make all" in a certain directory Able to ...
Vim Be sure to look at C++ Omni Completion ctags and TagList I use ctags --exclude=packagedir -R --c++-kinds=+p --fields=+iaS --extra=+q . cscope (here and here) Simply the best editor and will work anywhere - including in your remote terminal under screen :) Eclipse CDT Eclipse can import existing makefile proje...
5,696,594
5,696,936
Gracefully shut down a TCP socket
I'm writing an IRC client in C++ and currently I'm having an issue where, upon exit, I do: Send("QUIT :Quit\r\n"); // just an inline, variadic send() wrapper shutdown(m_hSocket, SD_BOTH); closesocket(m_hSocket); WSAShutdown(); However, the issue is that the QUIT message is not being sent. I've sniffed the packets com...
First of all you should check the return value of send: are the data you attempt to send actually accepted by the network stack? (In general this should be done after each and every send call, not just in this case). Assuming the data is accepted, then AFAIK it should be actually transmitted as a result of calling shut...
5,696,685
5,696,964
Flat array from an array of structs?
Hey guys. Thanks for clicking. This is a problem that I'm encountering while coding OpenGL, but it's a pretty general problem overall - so nothing graphics specific. I have a struct (not a class, just a simply struct), Particle. typedef struct { float x; float y; float z; }float3; typedef struct { float...
glVertexAttribPointer has a stride parameter that is designed for just this situation. Typically you will load an array of Particle objects into a VBO, and then, with the VBO bound: glVertexAttribPointer(shader_arg_position, 3, GL_FLOAT, GL_FALSE, sizeof (Particle), offsetof(Particle, position));
5,696,893
5,696,911
Firefox interacts with my timers somehow ?!?! This is crazy ^^
I have a problem with the timers in my win32 C++ DirectX game (a little demo). I am using "timeGetTime" to get the current time and use it to playback the animations or for logic by using the delta time (I also use a constant for normalization when animating). I use a tickrate as low as 2 miliseconds sometimes. I am us...
Yes the default precision of TimeGetTIme is 5ms or more. This can be altered with the calls timeBeginPeriod and timeEndPeriod functions. Alterning the precision of TimeGetTime affects all running applications. I guess Firefox is calling those functions which affect your application. Change to use the QueryPerformanceC...
5,697,042
5,697,181
command to suspend a thread with GDB
I'm a little new to GDB. I'm hoping someone can help me with something that should be quite simple, I've used Google/docs but I'm just missing something. What is the 'normal' way folks debug threaded apps with GDB? I'm using pthreads. I'm wanting to watch only one thread - the two options I see are a) tell the debugge...
See documentation for set scheduler-locking on. Beware: if you suspend other threads, and if one of them holds a lock, and if your interesting thread needs that lock at some point while stepping, you'll deadlock. What is the 'normal' way folks debug threaded apps You can never debug thread correctness, you can only d...
5,697,243
5,697,314
C++ check cin for valid data not working
I am doing an assignment for school and I am using an array filled with the ICAO words alphabet. The user enters a letter and then the program displays what ICAO word goes with the letter provided. I am using an index variable to get the ICAO word from the ICAO array. However I need to check that the user only enters a...
Your check for while( !cin ) checks if the stream has failed. End-Of-File or some other cause. What you want to accomplish is trickier. Maybe you could do a getline( cin, string ) to check if the user only input one character and then hit return. string input; getline( cin, input ); if ( input.size() == 1 && *input...
5,697,321
5,697,362
Why does my program continuously loop?
I'm a cis221 student, and I've been assigned a piece of homework I simply cannot figure out... The code below is the overloaded input operator for my "Fraction" class. istream& operator>>(istream& in, Fraction& fract) { cout << "Enter the whole number part for the fraction "; in >> fract.Whole; cout << "...
Fraction fract[4]; for (i=0; i<5; i++) That's no good. Use Fraction fract[5] and you won't be overwriting random memory.
5,697,328
5,697,373
Why is there no base class in C++?
From a design point of view, why is that, in C++, there is no mother-of-all base-class, what's usually object in other languages?
The definitive ruling is found in Stroustrup's FAQs. In short, it doesn't convey any semantic meaning. It will have a cost. Templates are more useful for containers. Why doesn't C++ have a universal class Object? We don't need one: generic programming provides statically type safe alternatives in most cases. Other ca...
5,697,546
5,877,273
Converting const unsigned int to unsigned int in template parameter
With the following code: #include <iostream> template< class T, unsigned int NVectorDimension = 3 > class Vector { }; template< unsigned int TDimension > int RunTest( void ) { const unsigned int VectorDimension = 4; typedef Vector< int, VectorDimension > VectorPixelType; } int main(int argc, char *argv[]) { ...
There was indeed a bug in gcc. It has been fixed now: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48657
5,697,629
5,697,906
C++ linked list , stack ( sort of )
#include <iostream> using namespace std; struct Node { int item; // storage for the node's item Node* next; // pointer to the next node }; /************** use reference **************/ void addNode(Node*& head, int data , int& count) { Node * q; // new node q = new Node; // allocate memory f...
In the do-while loop try this addNode(data, count, head); instead of addNode( data, count ); Also, change the signature of addNode as follows: void addNode( int data , int& count , Node*& head)
5,697,977
5,698,007
Accessing non-array floats via pointers
Is this valid/portable/legal code: class Vector3 { public: float& operator [] ( const size_t i ) { assert( i < 3 ); return *(&x+i); } float x, y, z; }; There have been quite a few instances where I wanted to use the [] operator and ended up putting the elements in an array (to avoid if/switch statem...
No. This is not correct and is not good practice. It is likely that there won't be padding between the three elements (even without instructing the compiler to pack the structure) and thus it is likely that you would be able to access the members as if they were elements of an array. That doesn't make the code right...
5,698,002
5,735,744
how does one securely clear std::string?
How does one store sensitive data (ex: passwords) in std::string? I have an application which prompts the user for a password and passes it to a downstream server during connection setup. I want to securely clear the password value after the connection has been established. If I store the password as a char * array, I ...
Based on the answer given here, I wrote an allocator to securely zero memory. #include <string> #include <windows.h> namespace secure { template <class T> class allocator : public std::allocator<T> { public: template<class U> struct rebind { typedef allocator<U> other; }; allocator() throw() {} allo...
5,698,022
5,698,076
Class C++ trace this value!
#include <iostream> using namespace std; class t { public: int health; //its members int speed; int power; void attack() // its methods { cout<<"I'm attacking"<<endl; }; }; int main() { t A,B,C,D; A.power = 100; B.health = 87; C.speed = 92; cout<<"A= "<<A.power<<"B= "<<A.health<<"C= "<<A.speed<<end...
You should create a constructor to initialize those values to some default value in the initializer list. class t { public: t() : health(100),power(100),speed(100) {} // ... }; This will guarantee that those values are all set to 100, or some default, or even an input parameter, rather than garbage. It's considered mu...
5,698,023
5,698,050
Conversion from STL vector of subclass to vector of base class
I am wondering if it is possible to convert a vector of derived class values to a vector of base class values. Specifically I want to be able to pass a vector of base class objects to a function whose formal parameters takes a vector of base class. It does not appear to be possible directly as the following code exam...
No, it is not. vector<B> is not derived from vector<A>, regardless of the fact that B is derived from A. You will have to change your function somehow. A more idiomatically C++ approach might be to template it and have it take a pair of iterators - this is why the various standard library functions (<algorithm> etc) wo...
5,698,225
11,860,927
Embed NoSQL document/EAV database in desktop program, like SQLite3, but NoSQL?
What's the best choice if I want to embed a document db or EAV db in client application? Something like "SQLite3 for NoSQL", small runtime library, index arbitary schema, small memory footprint, etc. C/C++ API or ActiveX/COM interface would be awesome! Thanks in advance!
Okay, after some development, I have to say, the best options so far are LevelDB and Tokyo Cabinet.
5,698,239
5,698,261
Is there a way to have buffer functions not waste so much memory?
buffer functions like GetWindowText(), GetModuleFileName(), SHGetFolderPath() make me angry because you almost always waste so much memory in the buffer. Is there a way to have them not waste so much memory?
"make me angry"? Are you a six-year-old? :-) I'm not entirely certain what your complaint is here. You can restrict how much is returned from GetWindowText and GetModuleFileName quite easily (at the cost of losing information) by specifying your own maximum length. But, if you want to be able to get the whole thing, yo...
5,698,423
5,698,430
Class C+ wrong output
All the code is working properly without errors but the command Setreal() and Setimag() below give wrong output. #include <iostream> using namespace std; class complex { public: bool Readcomplex() { cout<<"Enter the real part"<<endl; cin>>real; cout<<"Enter the imaginary part"<<endl; ci...
Those methods should have a return statement: double Setimag(double im) { return imag=im; }; double Setreal(double re) { return real=re; };
5,698,479
5,698,522
Realisticly why would I use duck-typing or inversion of control?
I'm just beginning to learn about Duck-typing, and Inversion of Control. In practical real world examples why would I want to incorporate these concepts into my code?
There are many benefits of coding to an Interface, even if you do not "develop code for other developers" as hinted in your comment. Discussing these benefits is a worthy exercise, but since the question asks for real world examples/use cases, here goes: For testing.   IoC makes it easy to introduce mocks and other ...
5,698,614
5,698,668
java final methods vs c++ nonvirtual functions
are java final methods and c++ nonvirtual methods different or the same? How?
You can still declare non-virtual member functions with the same signature in inheriting classes in C++, where-as Java explicitly forbids declaring methods with the same signature in which the base class declares that method final. Virtuality in C++ just helps find the correct function to call when dealing with inherit...
5,698,706
5,698,726
comparing linked list , C++ , same order but can be different seize
Let's say we are given the function definition bool sameValsOrder(node *p , node *q) We have to write a function to compare the 2 linked list if they have the same order it returns true else false [77777] and [77] -> true [1234567] and [1234555567] -> true bool sameValsOrder (node *p , node *q) { if ( q==NULL &&...
According to what you have written you don't actually care about the values but you want to return true if the list is ordered? It seems like you just need to go through each value in the list. As long as the NEXT value is NOT LESS than the PREVIOUS value keep going through the list. If you reach the end, then retur...
5,698,715
5,698,939
Compiler compile a 'io_service_' variable show as : cannot appear in a constant-expression
I created a ServerService namespace for containing a class name server_datetime. Server_datetime class as tutorial at Boost examples, but I improved server_datetime class by using template parameter for inserting io_service ( boost::asio::io_service ) and endpoint ( tcp::endpoint(tcp::v4(),SIZE_DATA) ) objects to te...
std::string message = make_daytime_string; you have forgotten the (), should be : std::string message = make_daytime_string();
5,698,960
5,773,674
Google Breakpad examples
Does anyone have any examples of configurations for google breakpad? I can build it just fine, however, there is limited documentation. I would like to see examples, such as how to modify where crash reports get sent to.
This appears to be platform-specific. On Windows, you could check out the following function in client\windows\sender\crash_report_sender.h (in particular, note the 'url' argument). // Sends the specified minidump file, along with the map of // name value pairs, as a multipart POST request to the given URL. // Paramete...
5,699,044
5,699,252
Implementation of a class if a data member is redefined
What happens to the implementation of a class if we redefine a data member? for example, suppose we have: class foo { public: int a; char *b; }; ... class bar : public foo { public: float c; int b; }; Does the representation of a bar object contain one b field or two? If two, are they both accessible, ...
It contains two, but one of them is called foo::b int main() { bar x; x.b = 0; // access bar::b x.foo::b = 0; // access foo::b }
5,699,128
5,700,159
friend not getting the private members
I've a class called Packet That I want to serialize with QDataStream I overloaded operator>> and operator<< and in the over loaded function I called stream << somIntMember Though Its declared as friend its complaining for Private Variables error: 'int DG::Packet::_state' is private error: 'DG::Packet::PacketType DG::Pa...
Well, the reason for the no match for 'operator>>' error is that there isn't any match for the operator>>, at least not in the code you've shown. The only operator>> and operator<< in the code you've shown are for Packet::CommonHeader and for Packet. Nothing for a quint32, nor for a QTime, nor for a PacketType, nor f...
5,699,187
5,699,206
abstract class declarations in c++
Suppose foo is an abstract class in a C++ program, why is it acceptable to declare variables of type foo*, but not of type foo?
Because if you declare a foo you must initialize/instantiate it. If you declare a *foo, you can use it to point to instances of classes that inherit from foo but are not abstract (and thus can be instantiated)
5,699,378
5,699,453
Why do some languages prefer static method binding rather than dynamic?
Why is the default decision in C++, C#, and Ada 95 to use static method binding, rather than dynamic method binding.? Is the gain in implementation speed worth the loss in abstraction and re-usability?
In general, you can consider that you have todesign the base class for extensibility. If a member function (to use the C++ vocabulary) isn't designed to be overridden, there is a good chance than overriding it will in practice not be possible and for sure it won't it be possible without knowledge of what the class des...
5,699,403
5,699,850
Spaces are removed from command line arguments when external dll is called from c#
We've a library written in c which is called by our main application which is written in c# (V 3.5). Previous version of our c# application was in Delphi and that one was also using the same library. The usage mode is as follows: we load the library using DLLImport in the c# code and call the required function. Th...
From the documentation: If lpApplicationName is NULL, the first white space–delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the ...
5,699,579
5,710,242
boost split with a single character or just one string
I wish to split a string on a single character or a string. I would like to use boost::split since boost string is our standard for basic string handling (I don't wish to mix several techniques). In the single character case I could do split(vec,str,is_any_of(':')) but I'd like to know if there is a way to specify just...
In the following code, let me assume using namespace boost for brevity. As for splitting on a character, if only algorithm/string is allowed, is_from_range might serve the purpose: split(vec,str, is_from_range(':',':')); Alternatively, if lambda is allowed: split(vec,str, lambda::_1 == ':'); or if preparing a dedicat...
5,699,609
5,699,723
thread safety in thirty part libraries
I want to use a library developed by someone else, of which I only have the library file, not the source code. My question is this: the library provides a class with a number of functionalities. The class itself is not thread safe. I wanted to make it thread safe and I was wondering if this code works // suppose libob...
This only inherits from libobj, which may or may not "work" depending on whether the class was designed for inheritance (has at least a virtual destructor). In any case, it won't buy you thread-safety for free. The easiest way to get that is to add mutexes to the class and lock those when entering a critical section: c...
5,699,778
5,700,139
Decent cross-compiler for Mac OS X targets
I'm developing an SDL application in C++, and some of my consumers have asked for a version that runs on Mac OS X. I am wondering if anyone knows of a good cross-compiler for Mac OS X targets, and maybe a Mac OS X emulator (maybe a virtual HDD for Virtual Box?) so that I can actually test it myself.The emulator is not ...
The easiest, and most common, solution is the other way: use a Mac platform with Windows installed either as dual boot or in a virtual machine. That way you will benefit of 100% of both worlds and never be bothered whenever a Mac system update is delivered. Bonus: You can install Linux as well.
5,700,006
5,700,310
How can I refactor this C++ to remove the labels/gotos?
My problem is not really a problem, but I want to make this code look a bit more elegant than it currently is. It has spaghetti code. Here is a little example of what I got. int func(...) { if ( ... ) { v6 = ESI_1C; EBP = 1; v5 = 0; v21 = 0; v19 = 0; v25 = ESI_1C; if ( packetSize > 1 ) ...
Second answer, as the question changed a lot. The original code looks like, after removing all redundant stuff: for (... ; ; ...) { ... if (...) { break; } ABC LABEL_19: DEF } XYZ; goto LABEL_19; This is exactly the same as: for (... ; ; ...) { ... if (...) { XYZ; } else { ABC } ...
5,700,186
5,700,612
Meta programming into several output languages
I'm looking for a way to have to write and maintain a certain algorithm (a graphics rendering sub-module of my code, actually) only once. I need the algorithm in C++, PHP and Javascript. Theoretically I could write it in C++ and wrap it into a PHP extension; but that has many issues of itself and doesn't solve the Java...
You could take a look at Haxe. Haxe is an open source programming language. It can be compiled to JavaScript, Flash/ActionScript, PHP, C++, Java, C#, Python and Lua.
5,700,204
5,700,212
c++ does implicit copy constructor copy array member variable?
Possible Duplicate: How are C array members handled in copy control functions? I would guess implicit copy constructor (generated by compiler) would copy pointer if member variable is declared as pointer. I'm not sure what happens to array member variable. Does implicit copy constructor copy array member correctly?...
Yes and yes is the answer. This is also true of structs in C. typedef struct { int a[100]; } S; S s1; s1.a[0] = 42; S s2; s2 = s1; // array copied
5,700,246
5,702,856
Boost.log V1 Compilation Error
Experiencing difficulty in compiling boost.log v1 in my code, though I know that the issue is due to boost.filesystem v3 lack of support. I know I need to #define BOOST_FILESYSTEM_VERSION 2 but where should I define it? The compilation error: error: 'external_string_type' is not a member of 'boost::filesystem3::wpath' ...
You can add this preprocessor #define two ways: a) on the compiler command line, usually something like -DBOOST_FILESYSTEM_VERSION=2 b) before including any of the boost filesystem header files in your sources: #define BOOST_FILESYSTEM_VERSION 2
5,700,338
5,700,413
Where does the function call occur?
In the following code from the C++ GUI Programming with Qt 4, where is the call for the on_lineEdit_textchanged() function occuring, as it is not explicitly shown in the code? #include <QtGui> #include "gotocelldialog.h" GoToCellDialog::GoToCellDialog(QWidget *parent): QDialog(parent) { setupUi(this); QRegExp regExp("...
Qt knows how to autoconnect certain signals and ports which are named according to the convention on_ObjectName_SignalName(). See http://doc.qt.nokia.com/latest/designer-using-a-ui-file.html#automatic-connections for an example. The Qt API describes that functionality at http://doc.qt.nokia.com/latest/qobject.html#auto...
5,700,466
7,866,194
C/C++ Unix configuration file library
Where can I find a C or C++ library for reading and manipulating Unix configuration files (format: name=value\n)?
For plain C, libconfuse is quite good
5,700,623
5,700,679
Non-Virtual Interface - how to invoke the correct virtual function
I have a hierarchy that looks something like this: class Base { public: void Execute(); virtual void DoSomething() = 0; private: virtual void exec_(); }; class Derived : public Base { public: //DoSomething is implementation specific for classes Derived from Base void DoSomething(); private: void...
This class Base { public: void Execute(); private: virtual void exec_() {} }; class Derived : public Base { private: void exec_() {} }; void Base::Execute() { // do some work exec_(); //work specific for derived impl // do some other work } int main() { Derived d; Base& b = d; ...
5,700,999
5,701,035
problem with enum "does not name a type'
g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 I am having a problem and I seem to find out way I am getting this error. file statemachine.h #ifndef STATEMACHINE_H_INCLUDED #define STATEMACHINE_H_INCLUDED #include "port.h" enum state { ST_UNINITIALIZED = 0x01, ST_INITIALIZED = 0x02, ST_OPENED = 0x03...
Could it be that you're including "statemachine.h" in "port.h" and "port.h" in "statemachine.h"? Try removing the line: #include "port.h" From the file "statemachine.h" Edit (as per Daniel's comment below): Then you need to forward declare your port_t type as follows: ... ST_DISPOSED = 0x05 }; struct port_t...
5,701,315
5,701,585
Pragmatic methods for debugging mixed C++ and Java code
I'm developing a wrapper for a C/C++ library in Java, and it's gotten to the point where it is mostly working, but there are occasional segfaults and other errors popping up. I'm using Eclipse for development, and it looks like they are working towards mixed debugging, but it is not finished yet. Can anyone suggest goo...
I've not found anything but using print statements for the Java side, but it's quite possible to attach gdb to the Java process, or start the JVM under gdb, and set break points, examine variables, etc. with it.
5,701,351
5,701,385
Why std::queue allows redundant type specification?
The forward declaration of STL library class std::queue is as follows: namespace std { template<typename T, class container = deque<T>> class queue } That means we can declare an object of type queue with different type specifications like this: std::queue<float, std::deque<std::string>> string_queue; Why this is...
Wouldn't it be more type safe to declare queue like this: More type safe yes, but not as convenient. The normal user of queue doesn’t care about the underlying container which is really just an implementation detail. They only care about the element type. This is also for consistency with the other container classes....
5,701,435
5,701,530
C++ Trace Logging Question, fstream access violation question
this is really two questions, I'll start with the easiest. I get an access violation exception at the end of this simple program. This is in MSVC6 (yes, I know...). int main() { std::fstream logFile("clog.txt"); std::clog.rdbuf( logFile.rdbuf() ); // ... use clog ... logFile.close(); // I've tried removing...
For your first problem, you probably want to restore the original buffer. Something like: std::fstream logFile("clog.txt"); streambuf * old = std::clog.rdbuf( logFile.rdbuf() ); // ... use clog ... std::clog.rdbuf( old ); logFile.close(); // I've tried removing this, same problem. Or better,create a RAII class to h...
5,701,904
5,701,941
Is std::vector::size() allowed to require non-trivial computations? When would it make sense?
I'm reviewing a piece of code and see a class where an std::vector is stored as a member variable and the size of that std::vector is stored as a separate member variable. Both std::vector and its "stored copy" of size are never change during the containing object lifetime and the comments say size is stored separately...
I would guess that your definition of "trivial" doesn't match that of the author of the code. If size isn't stored, I'd expect begin and end to be stored, and size to be computed as the difference of the two, and that code to be inlined. So we're basically talking two (nearby) memory accesses and a subtraction, instead...
5,702,034
5,702,487
How to write a simple debugger?
I would like to connect my compiled object code to the c++ code, and then to check if a certain line of code was executed. How to do those two things? If the explanation is not simple (I bet it is not), can someone at least point to some web pages explaining how to do this? I understand that the solution is different f...
If you want to know how it is done, gdb is open source the ptrace syscall should get you started, libunwind-ptrace this is a nice article using ptrace
5,702,100
5,702,144
What's the most reliable way to prohibit a copy constructor in C++?
Sometimes it's necessary to prohibit a copy constructor in a C++ class so that class becomes "non-copyable". Of course, operator= should be prohibited at the same time. So far I've seen two ways to do that. Way 1 is to declare the method private and give it no implementation: class Class { //useful stuff, then private:...
The first method is how Boost solves it (source code), as far as I know, there's no drawbacks. In fact, the linker errors are the big advantage of that method. You want the errors to be at link time, not when your client is executing your code and it suddenly crashes. In case you are using Boost, you can save yourself ...
5,702,318
5,702,347
use vector<wchar> instead of dynamically allocated wchar array
The other day, I got told off (on stackoverflow!) for not using vector instead of a dynamically allocated wchar array. So I had a look into using this method of string manipulation, as it seems like a good idea to prevent possible memory leaks. What I came up with was, that unless I'm using the vector template class in...
If you're using std::vector<WCHAR> you should probably be using std::wstring as it is also a container of WCHAR elements. The following links might help you: std::wstring (typedef of std::basic_string<WCHAR>) std::basic_string
5,702,342
5,702,366
C++ compilation error, constructor has no return type... but I didn't specify one
So here is the error: 1>c:\users\ben\documents\visual studio 2010\projects\opengl_learning\opengl_learning_without_glut\openglcontext.cpp(18): error C2533: 'OpenGLContext::{ctor}' : constructors not allowed a return type And here is a block of code where the error points, specifically the error originates from the defa...
Most likely you forgot a semicolon after OpenGLContext's definition. Then your code is parsed as class OpenGLContext { /* ... */ } OpenGLContext::OpenGLContext(void) { } That's valid syntactically. But as constructors don't have a return type, like the message says, the compiler complains.
5,702,369
5,702,507
Syslink control - normal (double) click notification?
Normal statics have SS_NOTIFY for recieving (double)clicks. How can I handle the same events for Syslink controls when "normal" text within them is clicked, not the link?
I don't believe there's any easy approach. Probably the easiest is to superclass a syslink and handle WM_LBUTTONDOWN/WM_LBUTTONUP. You could also subclass, but There's little difference in difficulty for a less flexible solution.