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 |
|---|---|---|---|---|
2,671,532 | 2,671,648 | non-copyable objects and value initialization: g++ vs msvc | I'm seeing some different behavior between g++ and msvc around value initializing non-copyable objects. Consider a class that is non-copyable:
class noncopyable_base
{
public:
noncopyable_base() {}
private:
noncopyable_base(const noncopyable_base &);
noncopyable_base &operator=(const noncopyable_base &);
... | The behavior you're seeing in MSVC is an extension, though it's documented as such in a roundabout way on the following page (emphasis mine) http://msdn.microsoft.com/en-us/library/0yw5843c.aspx:
The equal-sign initialization syntax is different from the function-style syntax, even though the generated code is identic... |
2,671,732 | 2,671,971 | Why is C++ fwrite() producing larger output in release? | I recently wrote an implementation of the Canonical Huffman compression algorithm. I have a 500kb test file that can be compressed to about 250kb when running the debug and release builds from within Visual Studio 2008. However when I run the release build straight from the executeable the test file only compresses to ... | Try running it through App Verifier and see what it finds.
|
2,672,085 | 2,672,106 | What is the difference between Static and Dynamic arrays in C++? | I have to do an assignment for my class and it says not to use Static arrays, only Dynamic arrays. I've looked in the book and online, but I don't seem to understand.
I thought Static was created at compile time and Dynamic at runtime, but I might be mistaking this with memory allocation.
Can you explain the difference... | Static arrays are created on the stack, and have automatic storage duration: you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size at compile time:
int foo[10];
Arrays created with operator new[] have dynamic storage duration and are stor... |
2,672,091 | 2,672,143 | Marshal managed string[] to unmanaged char** | This is my c++ struct (Use Multi-Byte Character Set)
typedef struct hookCONFIG {
int threadId;
HWND destination;
const char** gameApps;
const char** profilePaths;
} HOOKCONFIG;
And .Net struct
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct HOOKCONFIG {
public int threa... | Easy way: Change prototype to IntPtr[]:
public IntPtr[] gameApps;
public IntPtr[] profilePaths;
Now when you call you need to roughly the following psudo-code:
GCHandle handle = GCHandle.Alloc(string);
gameApps = new IntPtr[] { GCHandle.ToIntPtr(handle) };
// Unmanaged call
handle.Free();
|
2,672,294 | 2,672,306 | Is it possible to send array over network? | I'm using C++ and wondering if I can just send an entire int array over a network (using basic sockets) without doing anything. Or do I have to split the data up and send it one at a time?
| You could definitely send an array in one send, however you might want to do some additional work. There are issues with interpreting it correctly at the receiving end. For example, if using different machine architectures, you may want to convert the integers to network order (e.g., htonl).
Another thing to keep in... |
2,672,367 | 2,672,386 | three out of five file streams wont open, i believe its a problem with my ifstreams | #include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
using namespace std;
int main()
{
ifstream in_stream; // reads itemlist.txt
ofstream out_stream1; // writes in items.txt
ifstream in_stream2; // reads pricelist.txt
ofstream out_stream3;// writes in plist.txt
ifstream in_stream... | Your code works. I think your current directory is not what you think it is.
Where are these files stored? Is your current directory the Debug/Release directory where the executable is stored or something like that?
You need to call close before opening the files for writing.
Avoid using the exit(0) function, as it doe... |
2,672,398 | 2,672,440 | Throw exception from constructor initializer | What is the best way to throw exception from the constructor initializer?
For example:
class C {
T0 t0; // can be either valid or invalid, but does not throw directly
T1 t1; // heavy object, do not construct if t0 is invalid, by throwing before
C(int n)
: t0(n), // throw exception if t0(n) is not valid
... | There are multiple ways of going about this, I think. From what I understand, n can only take on a specific range of numbers. For that, you might prevent the constructor from even being run:
template <typename T, T Min, T Max>
class ranged_type_c
{
public:
typedef T value_type;
ranged_type_c(const value_type& ... |
2,672,536 | 2,672,575 | Specializing a class template constructor | I'm messing around with template specialization and I ran into a problem with trying to specialize the constructor based on what policy is used. Here is the code I am trying to get to work.
#include <cstdlib>
#include <ctime>
class DiePolicies {
public:
class RollOnConstruction { };
class CallMethod { };
};
#includ... | Your constructor is not a template function. You should specialize the whole class.
|
2,672,538 | 2,672,598 | How might one develop a program like FRAPS? | I would like to make a program to capture video.
What is the best way to capture video?
I know C++ and I'm learning assembly. I found in my assembly book that I can get data from the video card. Would that be the best way?
I know FRAPS hooks into programs, but I would like my program to take video of the entire screen... | The way Fraps works, it's impossible to capture the entire screen (unless you're running a full-screen DirectX application, of course). You're apparently trying to emulate the functionality of CamStudio, more so than Fraps.
CamStudio is open-source (here is the SorceForge page) so perhaps you could start by studying th... |
2,672,593 | 2,672,605 | Easy way to check if item is in list? | I'm writing a search algorithm in C++, and one of the things I need to do is have a few if statements that check cells above, below, left of, and right of.
Each time a cell is found to be open and added to the stack, I want it added to a list of cells already checked.
I want to be able to say in the if statement if(thi... | For this purpose it's better to use the std::set container, because it provides you with the ability to search for items faster than a list. Then you can write:
std::set<itemType> myset;
...
if (myset.find(item) != myset.end()) {
// item is found
}
A larger example can be found by googling. For example, here.
|
2,672,688 | 2,672,737 | Beginner: Sending data over sockets | Can anyone find an example of a simple server/client thing? I'm willing to use any C++ library or even Winsocks it self. I've Googled around but want some opinion on a good article for beginners/sites.
| If you're willing to use a C++ library, I heartily recommend Qt. It gives you an easy way to communicate with sockets, and much more. In particular see the QtNetwork module - a few of its relevant classes for your cause: QTcpSocket, QTcpServer, QUdpSocket.
|
2,672,866 | 2,672,889 | Create graph using adjacency list | #include<iostream>
using namespace std;
class TCSGraph{
public:
void addVertex(int vertex);
void display();
TCSGraph(){
head = NULL;
}
~TCSGraph();
private:
struct ListNode
{
string name;
struct ListNode *next;
... | There is a problem in you addvertex method:
You have:
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
but it should be:
if (!head) // check if the list is empty.
head = newNode;// if yes..make the new node the first node.
else { // list e... |
2,673,063 | 2,673,297 | Namespaces vs. Header files | I'm asking about the best practice widely used in C++ projects. I need to have my own types in the project. It's a collection of couple of typedefs.
Is including header file containing the types good practice in C++ or is it better to use namespaces. If so, why? What are the pros and cons of the two ways?
Right now it... | From a dependency point of view, naming all types in a single header is likely to be a maintenance nightmare. It's understandable for the typedef because you want a unique definition, but there is no reason to forward declare the class here.
// types.h
namespace myproject
{
typedef int TInt;
} // namespace myproject... |
2,673,162 | 2,673,318 | Creating an independent draw thread using pthreads (C++) | I'm working on a graphical application which looks something like this:
while (Simulator.simulating)
{
Simulator.update();
InputManager.processInput();
VideoManager.draw();
}
I do this several times a second, and in the vast majority of cases my computation will be taking up 90 - 99% of my processing time.... | First I would suggest using boost::thread as opposed to pthreads since you are using C++. With boost::thread you can do something like this:
#include <boost/thread.hpp>
void input_thread()
{
//...
}
void draw_thread()
{
//...
}
int main()
{
boost::thread input_th(&input_thread);
boost::thread draw_t... |
2,673,225 | 2,683,094 | using graphviz with qt | i have a compiler project and i want to print the ast after the compile complete
so can i print this ast to qt (on c++) panel using graphviz ?
note : i dont know if there is a binding between qt or c++ and graphviz , so if it doesnt work please help me to find the alternative .
thanks .
| i did this once. gcc has a flag to generate a .dot file of the AST. this file can then be displayed by graphviz. but be warned the AST is huge and is of limited use for all but the smallest functions.
see:
http://digitocero.com/en/blog/exporting-and-visualizing-gccs-abstract-syntax-tree-ast
|
2,673,409 | 2,673,522 | Swap bits in c++ for a double | Im trying to change from big endian to little endian on a double. One way to go is to use
double val, tmp = 5.55;
((unsigned int *)&val)[0] = ntohl(((unsigned int *)&tmp)[1]);
((unsigned int *)&val)[1] = ntohl(((unsigned int *)&tmp)[0]);
But then I get a warning: "dereferencing type-punned pointer will break strict-a... | I'd probably try something like this:
template <typename T>
void swap_endian(T& pX)
{
// should static assert that T is a POD
char& raw = reinterpret_cast<char&>(pX);
std::reverse(&raw, &raw + sizeof(T));
}
Short and sweet (and relatively untested). The compiler will make all the necessary optimizations. ... |
2,673,495 | 2,673,516 | 'Invalid conversion from some_type** to const some_type**' | I've got a function that requires const some_type** as an argument (some_type is a struct, and the function needs a pointer to an array of this type). I declared a local variable of type some_type*, and initialized it. Then I call the function as f(&some_array), and the compiler (gcc) says:
error: invalid conversion fr... | See: Why can't I pass a char ** to a function which expects a const char **? from the comp.lang.c FAQ.
|
2,673,508 | 3,160,064 | Correct usage(s) of const_cast<> | As a common rule, it is very often considered a bad practice to use const_cast<>() in C++ code as it reveals (most of the time) a flaw in the design.
While I totally agree with this, I however wonder what are the cases were using const_cast<>() is ok and the only solution.
Could you guys please give me some examples yo... | const_cast is also used to remove volatile modifiers, as put into practice in this (controversed) article:
http://www.drdobbs.com/184403766
|
2,673,687 | 2,673,692 | Ambiguous constructor call | I'm trying to create a simple date class, but I get an error on my main file that says, "call of overloaded Date() is ambiguous." I'm not sure why since I thought as long as I had different parameters for my constructor, I was ok. Here is my code:
header file:
#ifndef DATE_H
#define DATE_H
using std::string;
class D... | Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object
These are both callable with no parameters. It can't be default constructed, because it's ambiguous how to construct the object.
Honestly, having those three with default parameters doesn't make much sense. When wou... |
2,673,966 | 2,678,878 | Measure time between library call and callback | Hi: In an iPhone application I use a library(C++) which asynchronously makes a callback when computation is finished.
Now I want to measure the time which is spent -including the method which calls the library- until the callback is made. Are there any possibilities to do this with the Instruments application from App... | In the past I have used the following for making network calls I had to optimize - although at first it seems a bit convoluted, it certainly gives the most accurate times I have seen.
uint64_t time_a = mach_absolute_time();
// do stuff
uint64_t time_b = mach_absolute_time();
[self logTime:(time_b-time_a)];
- (void)... |
2,674,046 | 2,678,816 | Several numpy arrays with SWIG | I am using SWIG to pass numpy arrays from Python to C++ code:
%include "numpy.i"
%init %{
import_array();
%}
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)};
class Class
{
public:
void test(float* data, int n)
{
//...
}
};
and in Python:
c = Class()
a = zeros(5)
c.test(a)
This works, b... | I found out the answer from a collegue of mine:
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data1, int n1), (float* data2, int n2)};
class Class
{
public:
void test(float* data1, int n1, float* data2, int n2)
{
//...
}
};
Now two numpy arrays are passed to Class::test.
|
2,674,351 | 2,674,360 | what is the name of this pattern? | What is the name of that kind of structure?
Or where can I read about that.
class A : public B < A > { ... }
| Check out the Curiously recurring template pattern.
|
2,674,370 | 2,674,373 | Stream overloading in C++ | why does
void operator<<(ostream out, Test &t);
return an error whereas
void operator<<(ostream &out, Test &t);
does not ?
| Because you cannot copy streams, you have to pass them per reference.
Note that the canonical form of operator<< is this:
std::ostream& operator<<(std::ostream& out, const Test &t)
{
// write t into out
return out;
}
returning the stream is important so that you can string output together:
std::cout << Test() ... |
2,674,462 | 2,684,426 | Lua and C++: separation of duties | Please help to classify ways of organizing C++/Lua game code and to separate their duties. What are the most convenient ways, which one do you use?
For example, Lua can be used for initializing C++ objects only or at every game loop iteration. It can be used for game logic only or for graphics, too. Some game engines p... | My approach has been to limit what is exposed to Lua as much as possible. I have never found a need for a "main" or other such function which is called every time the scene is rendered (or more). Some Lua engines (like LOVE) do this however. I prefer to define objects with optional callback functions for common even... |
2,674,622 | 2,674,789 | Member variable pointers to COM objects | Is there any problem with keeping member variable pointer refernces to COM objects and reussing the reference through out the class in C++.
Is anybody aware of a reason why you would want to call .CreateInstance every time you wanted a to use the COM object i.e. you were getting a fresh instance each time.
I cannot see... | There is no general rule in this case because there are a number of variables that decide whether it is a good idea or not.
First: If you own the COM objects in question i.e. have source code and control over how they are used, then yes its perfectly safe.
If COM objects are 3rd party COM objects sometimes crappy code... |
2,674,625 | 2,674,762 | How close can I get C# to the performance of C++ for small intensive tasks? | I was thinking about the speed difference of C++ to C# being mostly about C# compiling to byte-code that is taken in by the JIT compiler (is that correct?) and all the checks C# does.
I notice that it is possible to turn a lot of these functions off, both in the compile options, and possibly through using the unsafe ke... | The example given is flawed because it does not show real life usage of both programming languages. Using simple datatypes to measure the speed of a language will not bring anything interesting. Instead, I suggest you create a template class in C++ and compare it with what is possible in C# for class generics. In the e... |
2,674,649 | 2,674,796 | C++ setTimout function? | What's the cheapest way for a JavaScript like setTimeout-function in C++?
I would need this:
5000 miliseconds from now, start function xy (no parameters, no return value).
The reason for this is I need to initialize COM for text to speech, but when I do it on dll attach, it crashes.
It works fine however if I do not c... | Calling CoInitialize() from DllMain() is a bad thing to do; there are LOTS of restrictions on what you can do from DllMain(); see here: http://blogs.msdn.com/larryosterman/archive/2004/04/23/118979.aspx
Even if it DID work reliably then initialising COM from within DllMain() isn't an especially nice thing to do as COM ... |
2,674,913 | 2,674,996 | bad file descriptor with close() socket (c++) | I'm running out of file descriptors when my program can't connect another host. The close() system call doesn't work, the number of open sockets increases. I can se it with
cat /proc/sys/fs/file-nr
Print from console:
connect: No route to host
close: Bad file descriptor
connect: No route to host
close: Bad file desc... | It looks like the problem is in the structure of your program. Every time through your infinite loop, you're creating a new socket. I'd suggest moving this out of the loop and re-using it.
If you'd like to just fix the way you're doing it now though, use close inside the "connect" failed if statement you have now. The... |
2,675,016 | 2,675,077 | Semaphores in unmanaged code | I've been using the Semaphore class to create semaphores. However, the examples use managed code (requires /clr), and I need to use unmanaged code because it seems FreeType doesn't like working with managed code.
How can I create two simple threads which use a semaphore in unmanaged code?
| Use native Windows semaphore objects.
|
2,675,037 | 2,675,197 | Thread Local Memory, Using std::string's internal buffer for c-style Scratch Memory | I am using Protocol Buffers and OpensSSL to generate, HMACs and then CBC encrypt the two fields to obfuscate the session cookies -- similar Kerberos tokens.
Protocol Buffers' API communicates with std::strings and has a buffer caching mechanism; I exploit the caching mechanism, for successive calls in the the same thr... | You shouldn't expect the whole content of your std::string to reside in TLS, since std::string makes allocations and reallocations for data on its own. A simple idea would be to allocate a structure on heap and store a pointer to it in the TLS.
Edit:
AFAIK rdbuf is a feature of streams, not of string (see here and here... |
2,675,228 | 2,675,229 | How to create pointer-to-mutable-member? | Consider the following code:
struct Foo
{
mutable int m;
template<int Foo::* member>
void change_member() const {
this->*member = 12; // Error: you cannot assign to a variable that is const
}
void g() const {
change_member<&Foo::m>();
}
};
Compiler generates an error message. The... | This code is ill-formed according to C++ Standard 5.5/5:
The restrictions on cv-qualification,
and the manner in which the
cv-qualifiers of the operands are
combined to produce the cv-qualifiers
of the result, are the same as the
rules for E1.E2 given in 5.2.5. [Note:
it is not possible to use a pointer to... |
2,675,262 | 2,676,125 | Does anyone know of a simple yet flexible 2d scene graph in c++? | I'm searching a simple 2d scene graph written in c++, possibly on top of OpenGL but that's not mandatory: the perfect thing would be the Cocos2d/Cocos2d-iphone scenegraph in c++.
Do you know of any existing implementations?
| Here are a few ideas:
SGL - It is designed for 3D scene graphs, but also might support 2D. The website looks pretty informative.
Papyrus C++ Cairo Scenegraph Library
|
2,675,870 | 2,675,887 | Getting error while linking with g++ | I try to compile and link my application in 2 steps :
Compiling:
g++ -c -o file1.o file1.cc general_header.h
g++ -c -o file2.o file2.cc general_header.h
g++ -c -o file3.o file3.cc general_header.h
Linking:
g++ -o myApp file1.o file2.o file3.o
I'm getting a link error as following:
file1.o: file not recogni... | No need to include header files in your input files list
g++ -c -o file1.o file1.cc
|
2,675,928 | 4,949,592 | How to identify Draft from Inbox and Sent mails In ALL MAIl mailbox | I am working on a mail client Application for downloading gmail emails,
which uses IMAP C-client library.
I want to download emails from "ALLMAIL" mailbox folder.
as you know ALLMAIL folder consists of Inbox,Sent Mail and Draft Mails.
Here my requirement is to distinguish Draft from Inbox and Sent mails.
Usually if w... | Gmail IMAP has some issue with setting the DRAFT flag, I faced the same issue when i was working with it. I deviced a workaround where I checked the delivered-to and return-path mail headers, if these headers where not there I assumed this to be a draft message.
|
2,676,226 | 2,676,264 | What is a good format for command line output when it is being used for further processing? | I have written a console application in Delphi that queries information from several locations. This application will be launched by another process, and the output to STDOUT will be captured by the launching process.
The information I am retrieving is to be interpreted by the calling application for reporting purposes... | If you want something that can be easily parsed, especially if it has to be done quickly, go with the simplest format that can effectively communicate the information you need. CSV if you can, otherwise try JSON. Definitely not XML unless you really, really need all the extra complexity for some reason.
|
2,676,337 | 2,676,419 | Custom iterator for a class based on two sets | I have a class that contains two sets. They both contain the same key type but have different compare operations.
I would like to provide an iterator for the class that iterates through the elements of both sets. I want to start with one set, then when I increment an iterator pointing to the last element of the first... | I implemented a very similar iterator using the boost libraries:
Have a read from here:
http://www.boost.org/doc/libs/1_42_0/libs/iterator/doc/iterator_facade.html#a-basic-iterator-using-iterator-facade
For a forward iterator you will need to implement the operator++, to change that to a bidirectional iterator you nee... |
2,676,443 | 2,676,463 | Inheriting private members in C++ | suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private ... | A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
|
2,676,503 | 2,682,646 | Qt "no matching function for call" | I have
no matching function for call to 'saveLine::saveLine()'
error when compiling my application. The construcor is never actually called.
saveLine class definition:
class saveLine
{
public:
saveLine(QWidget *parent);
private:
QPushButton *selectButton, *acceptButton;
QLabel *filePath;
QLineEdit *all... |
but now it gives another error
ISO C++ forbids declaration of
'saveLine' with no type
You need to add a forward declaration to tell the compiler that saveLine class exists:
Like this:
//declare that there will be a class saveLine
class saveLine;
class MWindow : public QWidget
{
Q_OBJECT
public:
MWindow(QWi... |
2,676,522 | 2,676,614 | When is the right time to draw? | I just finished essential part of my own personal 2D engine in C++ and I'm kinda deciding how to complete the part where it is actually supposed to display everything on the screen, namely when do I call that function which does the job.
I don't have much idea of how does the graphic card work, my biggest experience is... | look up render loop.
In a game, you will do it in a loop. You can also look up game loop which is a related concept if you're working on a game.
|
2,676,988 | 2,677,589 | How to change size of STL container in C++ | I have a piece of performance critical code written with pointers and dynamic memory.
I would like to rewrite it with STL containers, but I'm a bit concerned with performance. Is there a way to increase the size of a container without initializing the data?
For example, instead of doing
ptr = new BYTE[x];
I want to d... | vec.resize( newsize ) is defined to have the same effect as
vec.insert( vec.end(), newsize - vec.size(), T() )
if newsize > vec.size()… but the compiler may have difficulty determining that it is growing, not shrinking, and by how much. You might try profiling with both.
If you're sure that the default initialization ... |
2,676,990 | 2,677,005 | Is it a good idea to apply some basic macros to simplify code in a large project? | I've been working on a foundational c++ library for some time now, and there are a variety of ideas I've had that could really simplify the code writing and managing process. One of these is the concept of introducing some macros to help simplify statements that appear very often, but are a bit more complicated than sh... | IMHO this is generally a bad idea. You are essentially changing well known and understood syntax to something of your own invention. Before long you may find that you have re-invented the language. :)
|
2,677,029 | 2,677,098 | read numbers from files in columns, one column whole numbers, other column numbers with decimals | int price=' '; // attempt to grab a decimal number - but not the correct way
int itemnum=' '; // attempt to grab a whole number - but not the right way
while((price== (price*1.00)) && (itemnum == (itemnum*1)))
What is a way to get numbers in 2 diff columns where one column is whole numbers and the other are numbers... | The best way would be to get each separately. If it is from a file then you can do this:
int itemnum;
double price;
inputFile >> itemNum >> price; //If the columns are ItemNumber then Price
or
inputFile >> price >> itemnum; //If the columns are the other way around
The >> operator is nice in C++ because it attempts... |
2,677,037 | 2,677,526 | C++ macro "if class is defined" | Is there such macro in C++ (cross-compiler or compiler-specific):
#if isclass(NameSpace::MyClass)
Would be useful.
| If you do not care about portability, the __if_exists statement in VC++ meets your needs.
|
2,677,097 | 2,677,123 | Can I free memory passed to SysAllocString? | When allocating a new BSTR with SysAllocString via a wchar_t* on the heap, should I then free the original wchar_t* on the heap?
So is this the right way?
wchar_t *hs = new wchar_t[20];
// load some wchar's into hs...
BSTR bs = SysAllocString(hs);
delete[] hs;
Am I supposed to call delete here to free up the memory? ... | As its name implies, SysAllocString allocates its memory, it does not "adopt" its argument's memory. BSTRs are size-prefixed and null-terminated, so "adopting" a c-style string is impossible, as there is no space for the size prefix.
|
2,677,158 | 2,677,209 | understanding of FPS and the methods they use | Just looking on resources that break down how frames per second work. I know it has something to do with keeping track of Ticks and figure out how many ticks occured between each frame. But I never ran into any resources on why exactly you have to use the methods you use in order to get a smooth frame work. I am trying... | There are basically two approaches.
In ActionScript (and many other engines), you request the player to call a certain function at a certain framerate. For Flash games, you'll set the framerate to be 30 FPS, and then you'll implement a function that listens for ENTER_FRAME events to do what you need to do. This means y... |
2,677,221 | 2,677,245 | Someone is using the struct name as a variable name too. What does the code really say? | This morning we found an old chunk of code that was causing a library call to crash.
struct fred
{
int a;
int b;
int c;
};
fred fred[MAX_SIZE+1];
memset( fred, 0, sizeof(fred) * MAX_SIZE+1 );
It appears that the sizeof(fred) may have been the full array size, rather than the structure s... | Number one would be, don't do this as it's confusing - but you've already discovered this.
The variable hides the name of the struct, but you can still use struct fred to refer to the type.
e.g.
fred fred[MAX_SIZE+1];
memset( fred, 0, sizeof(struct fred) * (MAX_SIZE+1) );
Alternatively, why not just use the size ... |
2,677,577 | 2,677,818 | How to overload operator<< for qDebug | I'm trying to create more useful debug messages for my class where store data. My code is looking something like this
#include <QAbstractTableModel>
#include <QDebug>
/**
* Model for storing data.
*/
class DataModel : public QAbstractTableModel {
// for debugging purposes
friend QDebug operator<< (QDebug ... | After an hour of playing with this question I figured out model is pointer to DataModel and my operator << takes only references.
|
2,677,719 | 2,677,778 | How can I extract the current user's account picture? | I am trying to extract the current user's account picture in Windows 7, but I can't seem to figure out where it is located. I have found that the picture is sometimes written to the User's temp folder, but only after performing certain actions. It isn't always guaranteed to be there. Has anyone had any luck extracting ... | It's described here under User Profile Tiles in Windows 7. It doesn't seem very encouraging.
|
2,677,770 | 2,677,814 | vector::erase with pointer member | I am manipulating vectors of objects defined as follow:
class Hyp{
public:
int x;
int y;
double wFactor;
double hFactor;
char shapeNum;
double* visibleShape;
int xmin, xmax, ymin, ymax;
Hyp(int xx, int yy, double ww, double hh, char s): x(xx), y(yy), wFactor(ww), hFactor(hh), shapeNum(s) {visibleShape=0;shapeNum=-1;... | I think you're missing an overloaded assignment operator for Hyp.
|
2,677,785 | 2,677,800 | Visual Studio 2010 Linker Finding Multiply Defined Symbols (Where It Shouldn't) | I've just started with C++, and maybe there's something that I'm doing wrong here, but I'm at a loss. When I try to build the solution, I get 4 LNK2005 errors like this one:
error LNK2005: "public: double __thiscall Point::GetX(void)const " (?GetX@Point@@QBENXZ) already defined in CppSandbox.obj
(there's one for each g... | The problem is in CppSandbox.cpp:
#include "Point.cpp"
You are including the cpp file instead of the header file, so its contents are compiled twice and everything in it is therefore defined twice. (It's compiled once when Point.cpp is compiled, and a second time when CppSandbox.cpp is compiled.)
You should include t... |
2,677,851 | 3,669,030 | Open-source projects using C++ and XML data binding | I'm looking for open-source projects that make use of two things: (1) C++ and (2) XML data binding. For those who don't know, data binding tools make use of XML schema and code generators such as Codesynthesis xsd, Liquid Technologies. I know CIAO/DAnCE project, an implementation of CORBA Component Model that uses XML ... | I have tried http://www.codesynthesis.com/products/xsd/ a few months back and I thought the resulting C++ interface was pretty clean. (It's style is similar to STL / boost APIs)
Other than that the gSOAP toolkit appears to have something too. ( http://www.cs.fsu.edu/~engelen/soapdoc2.html#tth_sEc1.4 )
|
2,677,907 | 2,677,947 | Invalid conversion from int to int** C++ | Not sure why I'm getting this error. I have the following:
int* arr = new int[25];
int* foo(){
int* i;
cout << "Enter an integer:";
cin >> *i;
return i;
}
void test(int** myInt){
*myInt = foo();
}
This call here is where I get the error:
test(arr[0]); //here i get invalid conversion from int to int... | The way you've written it, test takes a pointer to a pointer to an int, but arr[0] is just an int.
However, in foo you are prompting for an int, but reading into a location that is the value of an uninitialized pointer. I'd have thought you want foo to read and return and int.
E.g.
int foo() {
int i;
cout << "Ent... |
2,677,913 | 2,680,055 | How would I go about sharing variables in a C++ class with Lua? | I'm fairly new to Lua, I've been working on trying to implement Lua scripting for logic in a Game Engine I'm putting together. I've had no trouble so far getting Lua up and running through the engine, and I'm able to call Lua functions from C and C functions from Lua.
The way the engine works now, each Object class con... | One approach is to use
a lightuserdata pointing to the C++ variable
a C function to access the C++ variable using the lightuserdata
keep the lightuserdata as an upvalue of the C function so one function suffices for all variables
use the number of arguments to the function to select between getting and setting the var... |
2,677,990 | 2,678,096 | Explain ML type inference to a C++ programmer | How does ML perform the type inference in the following function definition:
let add a b = a + b
Is it like C++ templates where no type-checking is performed until the point of template instantiation after which if the type supports the necessary operations, the function works or else a compilation error is thrown ?
i... | I suggest you have a look at this article: What is Hindley-Milner? (and why is it cool)
Here is the simplest example they use to explain type inference (it's not ML, but the idea is the same):
def foo(s: String) = s.length
// note: no explicit types
def bar(x, y) = foo(x) + y
Just looking at the definition of bar, we ... |
2,678,175 | 2,678,191 | Iterator to last element in std::list | #include <list>
using std::list;
int main()
{
list <int> n;
n.push_back(1);
n.push_back(2);
n.push_back(3);
list <int>::iterator iter = n.begin();
std::advance(iter, n.size() - 1); //iter is set to last element
}
is there any other way to have an iter to the last element in list?
| Yes, you can go one back from the end. (Assuming that you know that the list isn't empty.)
std::list<int>::iterator i = n.end();
--i;
|
2,678,254 | 2,678,305 | Technical reasons for names containing underscores? | Are there any technical reasons for the use of the underscore in names like (for example) scoped_lock in the Boost library? Why not call it `ScopedLock?
Please note I am not asking about stylistic reasons.
| From the Boost Library Requirements and Guidelines,
Given the intent to propose portions of boost for the next revision of the C++ standard library, boost decided to follow the standard library's conventions.
|
2,678,316 | 2,678,333 | How to call a bool function | I did not see anything that address my particular code problem.
I have a bool function in a class; the bool function is named:
bool Triplet::operator ==(const Triplet& operand)const {
if( (data[0] == operand.data[0]) &&
(data[1] == operand.data[1]) &&
(data[2] == operand.data[2]))
re... | That is a C++ operator overload, it is designed so it can change the behaviour of the normal operator:
Triplet a, b;
if (a == b) // calls Triplet::operator==()
If you really want to, you can call the operator by name:
if (a.operator==(b))
|
2,678,423 | 2,678,502 | Why two subprocesses created by Java behave differently? | I use Java Runtime.getRuntime().exec(command) to create a subprocess and print its pid as follows:
public static void main(String[] args) {
Process p2;
try {
p2 = Runtime.getRuntime().exec(cmd);
Field f2 = p2.getClass().getDeclaredField("pid");
f2.setAccessible(true);
System.out.println( f2.get(... | The C++ EXE is almost certainly marked as a console app. I'm thinking a jar would be considered a GUI app by default, and would do the standard detach-from-the-main-process thing.
If you were to take the C++ code and turn it into a GUI app, i think you'd see it behave similarly to the jar.
|
2,678,463 | 2,680,430 | How to find dynamically loaded modules (the static ones) programatically in windows | I'm trying to port the unix utility ldd to windows, because dependency walker and cygcheck don't quite give me the usage I'm looking for. (also for the learning experience)
Ive been looking all over MSDN, for a windows API that lists dll dependencies of an executable, or even the storage format in the complied exe (ju... | Modules loaded with loadlibrary api cannot be found in the exe imports table. So to trace those module we have to use one of the several api monitoring tools.
http://www.rohitab.com/apimonitor
www.apimonitor.com
If that is not the case you can simply get all the imports from
dumpbin /import abc.exe
(i am not exactly... |
2,678,476 | 2,687,246 | Boost::Container::Vector with Enum Template Argument - Not Legal Base Class | I'm using Visual Studio 2008 with the Boost v1.42.0 library. If I use an enum as the template argument, I get a compile error when adding a value using push_back(). The compiler error is: 'T': is not a legal base class and the location of the error is move.hpp line 79.
#include <boost/interprocess/containers/vector.h... | I think you have find really a bug. I have posted to the Boost ML to track the issue and try to have more info.
For the moment the single workaround I see is to specialize the rv class as follows, but I'm not sure this will work on all the cases.
namespace boost {
namespace interprocess {
template <>
class rv<Test::T... |
2,678,665 | 2,681,510 | g_signal_connect error invalid use of member | I'm trying to compile some code and I'm getting the following error:
error: invalid use of member (did you forget the ‘&’ ?)
This is coming from the g_signal_connect call:
g_signal_connect ((gpointer) Drawing_Area_CPU, "expose-event",
G_CALLBACK (graph_expose), NULL);
Drawing_Area_CPU is a GtkWidget * and gr... | As GTK+ is written in plain C, callbacks have to be either plain functions or static methods, so if you want to be able to use class methods as callbacks, you must use some kind of static proxy method:
class foo {
foo () {
g_signal_connect (GtkWidget *widget, GdkEventExpose *event,
... |
2,678,711 | 2,678,846 | Vector Troubles in C++ | I am currently working on a project that deals with a vector of objects of a People class. The program compiles and runs just fine, but when I use the debugger it dies when trying to do anything with the PersonWrangler object. I currently have 3 different classes, one for the person, a personwrangler which handles all ... | 0xBAADFOOD is a magic number to alert you to the fact that you're dealing with uninitialized memory. From the stack trace, we see that this in PersonWrangler::outputPeople is invalid. Thus hal doesn't point to a valid PersonWrangler (that is, assuming frame 4 is a call to Game::menu). To resolve this sort of thing your... |
2,678,718 | 2,679,581 | How do I build a filtered_streambuf based on basic_streambuf? | I have a project that requires me to insert a filter into a stream so that outgoing data will be modified according to the filter. After some research, it seems that what I want to do is create a filtered_streambuf like this:
template <class StreamBuf>
class filtered_streambuf: public StreamBuf
{ ... }
And then insert... | Boost.Iostreams may be useful to you.
From the documentation:
Boost.Iostreams has three aims:
To make it easy to create standard C++ streams and stream buffers for
accessing new Sources and Sinks.
To provide a framework for defining Filters and attaching them to standard
streams and stream buffers.
To provide a c... |
2,678,882 | 2,678,934 | Why are there defined constants and declared constants in CPP? | Why are there two ways to "declare" constants in CPP?
Which is better, or should I write, which of them should I use when?
#define MYCON 100
const int MYCON=100
| Short rule: For conditional compilation (like different code fragments for DEBUG and RELEASE) use #define. For all other cases use const construction.
|
2,678,998 | 2,679,358 | Fonts in a multi-platform environment | What is the best way to deal with fonts in a multi-platform distributed system? If I want to use a common font across all systems to show to the user, what's the best way to do this. From the little I've been reading each platform looks to have fonts that are of the same family (ie serif, sans-serif) but with differe... | fontconfig is a cross-platform library for finding fonts by either direct name (Times Roman) or common aliases like serif - it's what most modern Linux software, like the GNOME & KDE desktops, use to find fonts, and is used in conjunction with libraries like Pango for text layout and FreeType for font rasterizing.
|
2,679,056 | 2,679,073 | get error when i try to open file using specific path | i get errors when i try to open a file using the file path
out_stream5.open("C:pathshowitems.txt", ios::out);
warning C4129: 'o' : unrecognized character escape sequence
error C2100: illegal indirection
| I presume you're working on Windows. The problem is probably that you need to escape the backslashes:
out_stream5.open("C:\\path\\showitems.txt", ios::out);
|
2,679,182 | 2,679,202 | Have macro 'return' a value | I'm using a macro and I think it works fine -
#define CStrNullLastNL(str) {char* nl=strrchr(str,'\n'); if(nl){*nl=0;}}
So it works to zero out the last newline in a string, really its used to chop off the linebreak when it gets left on by fgets.
So, I'm wondering if I can "return" a value from the macro, so it can be... | For a macro to "return a value", the macro itself has to be an expression. Your macro is a statement block, which cannot evaluate to an expression.
You really ought to write an inline function. It will be just as fast and far more maintainable.
|
2,679,274 | 2,679,285 | Simple matrix example using C++ template class | I am trying to write a trivial Matrix class, using C++ templates in an attempt to brush up my C++, and also to explain something to a fellow coder.
This is what I have som far:
template class<T>
class Matrix
{
public:
Matrix(const unsigned int rows, const unsigned int cols);
Matrix(const Matrix& m);
Matrix&... | You can access T in the constructor, so the constructor itself needs not be a template. For example:
Matrix::Matrix(const unsigned int rows, const unsigned int cols)
{
m_values = new T[rows * columns];
}
Consider using a smart pointer, like boost::scoped_array or std::vector for the array to make resource managem... |
2,679,465 | 2,679,493 | mmap() for large file I/O? | I'm creating a utility in C++ to be run on Linux which can convert videos to a proprietary format. The video frames are very large (up to 16 megapixels), and we need to be able to seek directly to exact frame numbers, so our file format uses libz to compress each frame individually, and append the compressed data onto ... | On a 32-bit machine your process is limited to 2-3 GB of user address space. This means that (allowing for other memory use) you won't be able to map more than ~1 GB of your file at a time. This does NOT mean that you cannot use mmap() for very large files - just that you need to map only part of the file at a time.
Th... |
2,679,467 | 2,679,510 | C++0x optimizing compiler quality | I do some heavy numbercrunching and for me floating-point performance is very important.
I like performance of Intel compiler very much and quite content with quality of assembly it produces.
I am thinking at some point to try C++0x mainly for sugar parts, like auto, initializer list, etc, but also lambdas. at this po... | You can expect the same optimization for your code, because the compiler certainly didn't get worse at optimizing. So only using the new C++0x features might impact it. But I doubt your core routines would suddenly be completely changed to somehow use C++0x-only features.
Keep in mind things like auto and lambda are ju... |
2,679,515 | 2,679,525 | visual studio 2005 to 2010 with boost | About a month a go I spent almost an entire week trying to figure out how to build the boost libraries for vs2005 and today I updated to vs2010.
Do I need to remove boost for vs 2005(I uninstalled vs2005) and go through the build process for 2010 or will it magically work and I can go take a nap?
| You need to rebuild Boost for the new version of Visual C++.
I don't believe anyone has released a binary distribution for Visual C++ 2010 yet. The BoostPro site would be the best place to get a binary distribution, and they don't have them yet.
It shouldn't be too difficult to build Boost if you follow the instruct... |
2,679,680 | 2,679,688 | Getting window style | I'm trying to check if a window has a certain style using GetWindowLong(hWnd, GWL_STYLE) but that gives me a LONG type of variable. how would you check for a specific style from that say a const value type 'WS_CAPTION'?
| use the bitwise & operator to compare with that long type,
example
if (szLng & WS_CAPTION){
// that window has caption
}
|
2,679,717 | 2,679,794 | Version of STL optimized for compile time? | I'm looking for a variant of the STL (it's okay if it doesn't have all the functionality) that's optimized for short compile times -- I get bothered by long compile times that delay my compile-debug-edit cycle.
I'm mainly interested in the containers of the STL: vector/map, and not so much the algorithms.
Thanks!
| Take a look at your compiler's options for precompiled headers. In GCC, for example, passing a header as if it is a source causes it to be precompiled.
It reduced time significantly for my little test, but only if you don't count the time spent precompiling:
Shadow:code dkrauss$ ls maps*
maps.cpp maps.h maps2.c... |
2,679,844 | 2,679,856 | Is it bad practice to use multi-dimensional arrays in C/C++? | Some programmers seem to violently hate them, while others seem to think they're fine. I know that anything that can be done to a multi-dimensional array can also be done to a regular array, so they're functionally equivalent. Is it bad practice to use multi-dimensional arrays, or does it not matter?
| Do you need to store multi-dimensional data where you know the dimensions ahead of time? If so, use a multi-dimensional array.
If you don't know the dimensions ahead of time (i.e., you're going to have to dynamically allocate the array), then you either need to either
allocate a one-dimensional array and emulate an n... |
2,679,885 | 2,679,905 | Using pthread in c++ | I am using pthread.h in a *.cc file. when I try to use pthread_exit(0); or pthread_join(mythrds[yy],NULL); it says:
.cc:(.text+0x3e): undefined reference to `pthread_exit'
when complied very similar code in a *.c file with gcc it work perfect. How Can I use pthread's in c++.. (I also added -lpthread)
..
void *myThrea... | You might try using the -pthread option to g++.
-pthread
Adds support for multithreading with the pthreads library. This
option sets flags for both the preprocessor and linker.
|
2,679,964 | 2,679,985 | C++ unicode UTF-16 encoding | I have a wide char string is L"hao123--我的上网主页", and it must be encoded to "hao123--\u6211\u7684\u4E0A\u7F51\u4E3B\u9875". I was told that the encoded string is a special “%uNNNN” format for encoding Unicode UTF-16 code points. In this website, it tells me it's JavaScript escapes. But I don't know how to encode it wi... | Embedding unicode in string literals is generally not a good idea and is not portable; there is no guarantee that wchar_t will be 16 bits and that the encoding will be UTF-16. While this may be the case on Windows with Microsoft Visual C++ (a particular C++ implementation), wchar_t is 32 bits on OS X's GCC (another imp... |
2,679,967 | 2,679,992 | boost::shared_ptr in Objective-C++ | This is a better understanding of a question I had earlier.
I have the following Objective-C++ object
@interface OCPP
{
MyCppobj * cppobj;
}
@end
@implementation OCPP
-(OCPP *) init
{
cppobj = new MyCppobj;
}
@end
Then I create a completely differently obj which needs to use cppobj in a boost::shared_ptr ... | shared_ptr supports custom deallocators. What you can do, is, do nothing.
void no_destroy(MyCppObj*)
{}
bsp = boost::shared_ptr<MyCppObj>(cpp, &no_destroy);
|
2,679,979 | 2,680,110 | C++ Event (Focus) Handling | Due to comments I added the following code
(in BasicPanel)
Connect(CTRL_ONE, wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Connect(CTRL_TWO,wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Connect(CTRL_THREE, wxEVT_KILL_FOCUS, (wxObjectEventFunction)&BasicPanel::OnKillFocus);
Co... | Okay, first off, here is the code to put in your BasicPanel class:
void OnKillFocus(wxFocusEvent& event);
Then add the following to the end of your BasicPanel constructor:
Connect(ID_TEXTCTRL,
wxEVT_KILL_FOCUS ,
(wxObjectEventFunction)&BasicPanel::OnKillFocus);
You will need to repeat the above code f... |
2,680,103 | 2,680,135 | Is it safe to call a function to initialize a class in a ctor list? | I have Angle class that I want initialized to a random value. The Angle constructor can accept an int from a random() function. Is it safe to place this call in the ctor list:
foo::foo() : Angle(random(0xFFFF)) {...}
or do I have to do it in the body of the constructor?
foo::foo() { Angle = Angle(random(0xFFFF)); ..... | If random cannot throw (hard to believe that it could), there is no problem with this. Side effects are allowed in constructor initializers. It's good practice to do any initialization there, if it takes only little code.
|
2,680,310 | 2,680,524 | Passing Derived Class Instances as void* to Generic Callbacks in C++ | This is a bit of an involved problem, so I'll do the best I can to explain what's going on. If I miss something, please tell me so I can clarify.
We have a callback system where on one side a module or application provides a "Service" and clients can perform actions with this Service (A very rudimentary IPC, basically)... | While I am not 100% sure I think static_cast from T* to void* and back to the original pointer type T* should work. As I see it the problem is that reinterpret_cast only changes the type of pointer without altering its actual value and static_cast in case of inheritance should adjust a pointer so that it points to the ... |
2,680,311 | 2,680,987 | Does gcc's STL support rvalue references now? | I know Visual Studio 2010's standard library has been rewritten to support rvalue references, which boosts its performance considerably.
Does the standard library implementation of gcc 4.4 (and above) support rvalue references?
| I found this from the STL of gcc 4.4 :
#ifdef __GXX_EXPERIMENTAL_CXX0X__
_Vector_base(_Vector_base&& __x)
: _M_impl(__x._M_get_Tp_allocator())
{
this->_M_impl._M_start = __x._M_impl._M_start;
this->_M_impl._M_finish = __x._M_impl._M_finish;
this->_M_impl._M_end_of_storage = __x._M_impl._M_end_of_stora... |
2,680,369 | 2,680,771 | How is inheritance implemented at the memory level? | Suppose I have
class A { public: void print(){cout<<"A"; }};
class B: public A { public: void print(){cout<<"B"; }};
class C: public A { };
How is inheritance implemented at the memory level?
Does C copy print() code to itself or does it have a pointer to the it that points ... | Compilers are allowed to implement this however they choose. But they generally follow CFront's old implementation.
For classes/objects without inheritance
Consider:
#include <iostream>
class A {
void foo()
{
std::cout << "foo\n";
}
static int bar()
{
return 42;
}
};
A a;
a.f... |
2,680,892 | 2,681,635 | How do you run your unit tests? Compiler flags? Static libraries? | I'm just getting started with TDD and am curious as to what approaches others take to run their tests. For reference, I am using the google testing framework, but I believe the question is applicable to most other testing frameworks and to languages other than C/C++.
My general approach so far has been to do one of thr... | I tend to favour static libs over dlls so most of my C++ code ends up in static libs anyway and, as you've found, they're as easy to test as dlls.
For code that builds into an exe I either have a separate test project which simply includes the source files that are under test and that are usually built into the exe OR ... |
2,681,337 | 2,681,437 | dynamical binding or switch/case? | A scene like this:
I've different of objects do the similar operation as respective func() implements.
There're 2 kinds of solution for func_manager() to call func() according to different objects
Solution 1: Use virtual function character specified in c++. func_manager works differently accroding to different objec... |
from the view point of DESIGN PATTERN, which one is better?
Using polymorphism (Solution 1) is better.
Just one data point: Imagine you have a huge system built around either of the two and then suddenly comes the requirement to add another type. With solution one, you add one derived class, make sure it's instantiat... |
2,681,405 | 2,682,643 | How to detect missing font characters | Is there a way to detect that all characters are displayed properly with the current font? In some environments and fonts certain characters are replaced with a square symbol.
I'd like to automatically verify that all characters used in the GUI are supported by the current font.
| I found a possible solution using the QFontMetrics class. Here is a an example function to query whether all characters are available in the current text of a QLabel:
bool charactersMissing(const QLabel& label) {
QFontMetrics metrics(label.font());
for (int i = 0; i < label.text().size(); ++i) {
if (!me... |
2,681,446 | 2,683,060 | Howto access thread data outside a thread | Question: I start the MS Text-to-speech engine in a thread, in order to avoid a crash on DLL_attach. It starts fine, and the text to speech engine gets initialized, but I can't access ISpVoice outside the thread. How can I access ISpVoice outside the thread ? It's a global variable after all...
You find XPThreads here:... | Firstly, your problem is that you are expecting the thread that you start when the file's static initialisers are run to have completed whilst your DllMain() is running and yet you're doing nothing to synchronise with it. Of course if you WERE doing something to synchronise with it then you would be falling foul of the... |
2,681,490 | 2,681,922 | Invalidate() debug assertion failed message (MFC, VC++) | I've made a custom control, and when I want it to repaint on the screen I call Invalidate(), and afterwards UpdateWindow(), but i get message:
debug assertion failed for a file afxwin2.inl in line 150 which is:
AFXWIN_INLINE void CWnd::Invalidate(BOOL bErase)
{ ASSERT(::IsWindow(m_hWnd)); ::InvalidateRect(m_hWnd, ... | Well,
ASSERT(::IsWindow(m_hWnd));
is an assertion. Assertions are statements which verify that something is true and kill your program if it's not. They're intended to be used for debugging and development rather than for being in the program once it has been released, so they are normally only compiled in in debug bu... |
2,681,533 | 3,183,287 | How can I determine which dependency would cause a C++ compilation unit to be rebuilt? | I have a legacy C++ application with a deep graph of #includes. Changes to any header file often cause recompiles of seemingly unrelated source files.
The application is built using a Visual Studio 2005 solution (sln) file.
Can MSBUILD be invoked in a way that it reports which dependency(ies) are causing a source file... | If you dial up the verbosity to detailed or above (Tools>Options>Project>Build or /v:detailed) then MSBuild will log, just before it runs the compiler, exactly what header file or source file caused it to run the compiler.
Is that what you're asking for?
Dan/MSBuild
|
2,681,709 | 2,681,781 | What iterator to return for non-existing map How to signkey? | I want to have a function which searches for a key in a collection of maps and returns an iterator to the found key. But what should be returned in case the key cannot be found? I cannot return map::end since the collection of maps can be empty.
Thanks.
map<string, string>::iterator CConfFile::GetKey(const string &Sect... | If you return an iterator, then that implies that one can actually iterate over all the values. If thats indeed the case, you would have to return a custom iterator type anyway and you should have no problem to denote a special end iterator.
If the iterator isn't intended to be used as an iterator, it might be better ... |
2,681,887 | 2,682,084 | writing string into file before calling the close() | I am using ofstream() to write data into file, i want the program to perform such a way that it should be keep on writting the string into the file as soon as the value gets assingned to string variable, and it should be writting before calling the close().
The need is,
I am getting the keystrokes of the keyboard, and ... | Call flush() on the ofstream after writing to it. That will cause the output to be actually written instead of being buffered.
|
2,681,890 | 2,682,056 | c++ Array passing dilemma | I am writing a function that takes a string, string pointer and an int.
The function splits the string based on a set of rules and puts each token into an array. I need to return the array out of the function with the number of elements in the int variable etc. I am stuck as to how I return the array as I can not use a... | This is more of a C than a C++ question given those restrictions.
The common C pattern for returning an array is actually to get the caller to pass in an array to fill. This lets the caller decide on the allocation (and hence deallocation).
Your function prototype would look like
int Function(string str1, string_ptr st... |
2,681,959 | 2,716,225 | Problem with "moveable-only types" in VC++ 2010 | I recently installed Visual Studio 2010 Professional RC to try it out and test the few C++0x features that are implemented in VC++ 2010.
I instantiated a std::vector of std::unique_ptr, without any problems. However, when I try to populate it by passing temporaries to push_back, the compiler complains that the copy con... | Unfortunately, /Za is buggy. It performs an elided-copy-constructor-accessibility check when it shouldn't (binding rvalue references doesn't invoke copy constructors, even theoretically). As a result, /Za should not be used.
Stephan T. Lavavej, Visual C++ Libraries Developer (stl@microsoft.com)
|
2,682,063 | 2,682,070 | C++ : Initializing base class constant static variable with different value in derived class? | I have a base class A with a constant static variable a. I need that instances of class B have a different value for the static variable a. How could this be achieved, preferably with static initialization ?
class A {
public:
static const int a;
};
const int A::a = 1;
class B : public A {
// ???
// How to... | You can't. There is one instance of the static variable that is shared by all derived classes.
|
2,682,708 | 2,683,038 | Exiting from the Middle of an Expression Without Using Exceptions | Solved: I figured out a clean way to do it with setjmp()/longjmp(), requiring only a minimal wrapper like:
int jump(jmp_buf j, int i) { longjmp(j, i); return 0; }
This allows jump() to be used in conditional expressions. So now the code:
if (A == 0) return;
output << "Nonzero.\n";
Is correctly translated to:
return
(... | You may want to research cfront, which is a program from the late 80's/early 90's that translated C++ into C (no templates or exceptions back then), because there were few, if any, native C++ compilers.
The way it handled inline functions is very similar to what you are trying to do: lots of trinary (?:) operators, com... |
2,682,760 | 2,683,510 | OpenSSL Bio chains: Clarrification on documentation | The documentation for Openssl memory BIO sinks is here.
I am creating a BIO chain to turn binary strings into base64 strings. The source/sink is always a memory location, and this enables me to just keep the same chain arround. However the data (should) go into a memory buffer managed by OpenSSL when I write to it, and... | I'm not sure to get you right but here is how I usually proceed with OpenSSL:
I consider OpenSSL's BIO structures to be some kind of opaque streams.
Whatever data I have to pass to (or get from) OpenSSL, it is usually stored in a custom data structure of my own, then copied to/from an OpenSSL BIO for processing.
As you... |
2,682,990 | 2,683,013 | Cannot Convert from int[][] to int* | I have a 3x3 array that I'm trying to create a pointer to and I keep getting this array, what gives?
How do I have to define the pointer? I've tried every combination of [] and *.
Is it possible to do this?
int tempSec[3][3];
int* pTemp = tempSec;
| You can do int *pTemp = &tempSec[0][0];
If you want to treat a 3x3 array as an int*, you should probably declare it as an int[9], and use tempSec[3*x+y] instead of tempSec[x][y].
Alternatively, perhaps what you wanted was int (*pTemp)[3] = tempSec? That would then be a pointer to the first element of tempSec, that firs... |
2,683,025 | 2,683,796 | how to print std::map value in gdb | I have a std::map< std::string, std::string> cont;
I want to see cont[ "some_key" ] in gdb. When I'm trying
p cont[ "some_ket" ]
I'm getting this message: One of the arguments you tried to pass to operator[] could not be converted to what the function wants.
I'm using GNU gdb Red Hat Linux (6.3.0.0-1.162.el4rh). Tha... | The latest gdb has python support baked in so one could easily write a function to print out the contents of any stl structure. However you'd have to learn the API and write the script. Luckily gcc 4.5 will ship with the needed python scripts to get gdb to intelligently handle stl data structures.
EDIT: you don't hav... |
2,683,101 | 2,683,131 | How can I use C++ with Objective-C in XCode | I want to use/reuse C++ object with Objective-C.
I have a hello.h that has the class definition, and hello.cpp for class implementation.
class Hello
{ int getX() ... };
And I use this class in Objective-C function.
#include "hello.h"
...
- (IBAction) adderTwo:(id)sender
{
Hello *hi = new Hello();
i... | Make sure you compile that file as "Objective-C++".
The simplest way is to rename it as *.mm.
If you don't want to rename the *.m file,
Select your file.
Open the File Info dialog (Cmd+I)
In File Type, select "sourcecode.cpp.objcpp"
|
2,683,588 | 2,683,691 | What is the fastest way to compute sin and cos together? | I would like to compute both the sine and co-sine of a value together (for example to create a rotation matrix). Of course I could compute them separately one after another like a = cos(x); b = sin(x);, but I wonder if there is a faster way when needing both values.
Edit:
To summarize the answers so far:
Vlad said, th... | Modern Intel/AMD processors have instruction FSINCOS for calculating sine and cosine functions simultaneously. If you need strong optimization, perhaps you should use it.
Here is a small example: http://home.broadpark.no/~alein/fsincos.html
Here is another example (for MSVC): http://www.codeguru.com/forum/showthread.ph... |
2,683,778 | 2,684,087 | How to detect segmentation fault details using Valgrind? | I have a std::map< std::string, std::string> which initialized with some API call. When I'm trying to use this map I'm getting segmentation fault. How can I detect invalid code or what is invalid or any detail which can help me to fix problem? Code looks like this:
std::map< std::string, std::string> cont;
some_func( ... | In general I'm not sure how that line could be generating a seg fault: the bracket operator will always return a std::string (creating an empty one if needed) and it should always be valid for printing.
Is it possible that instead, the call stack you see is pointing to the next line to execute and it's dying in some_fu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.