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 |
|---|---|---|---|---|
4,413,244 | 4,413,613 | Unifying 2 space memories |
Is there a way to read another process memory as if its memory was a part of my process memory in C++/Windows (without using "ReadProcessMemory")?
What about "CreateRemoteThread"? I want to be able to read the other process's memory but not only in my remote thread and from my application itself. will this do the job?... | MSDN has a sample that explains how to use CreateFileMapping to share memory between two processes.
Basically, you create a file mapping with an explicit name using the page file as a backing store, then open that file mapping in the second process with the same name. To map the same address in both processes, you will... |
4,413,272 | 4,413,352 | How to connect a client and a server? | Even if UDP is connection-less, I would like to establish some kind of connection between a client and a server.
The thing is, once the server has received something from the client, the only thing I can do send my answer is use the IP and the Port from the client.
And well... this will, in almost EVERY CASE, not be th... | Just send back to the client through the same socket, the NAT will automagically resolve that and pass it on to the actual box.
|
4,413,701 | 4,413,737 | Porting C++ Application From XP to Vista/7 | I have a C++ application that I have written for Windows XP, and I would like to port it for use on Windows Vista/7. It uses some MFC (for serial I/O) and ATL (for WMI), but it primarily uses the good ol' fashioned Windows API. What are some of the got-yas I should keep in mind when porting my application? Thanks.
| You probably don't need to do anything at all. In general, applications written for XP run fine on Vista and Windows 7. (Device drivers and other such low-level code may be a different story.)
Are you having problems running it on Vista or Windows 7? Have you even tried?
Some possible gotchas:
security (does your ap... |
4,413,714 | 4,413,794 | Injecting a C++ exception in another thread | With the C++0x feature of exception_ptr one can store an exception in one thread and have another thread access it. However, the other thread has to call rethrow_exception(). In some cases, however, I need to actually interrupt the other thread and have the exception be raised there immediately; polling the exception... | I read that article you linked to some time ago, and I was a bit skeptical.
The approach of modifying another thread's instruction pointer directly feels VERY scary. You have absolutely no idea what operation you're interrupting and leaving half-completed, and the interrupted operation may not be expecting an exception... |
4,413,780 | 4,444,604 | Restrict variadic function template to only accept variations of one variadic class template's nested variadic class template? | I have a variadic class template that has a nested variadic class template. The outer class template has a function template that accepts any number of arguments and will return an object of type inner. My problem is creating a completely separate function that will accept any number of any variation of those inner t... | Well, I didn't set out to answer my own question, but I think I've beat my head against the wall just enough the past few days to figure this one out... and certainly learned some new stuff along the way (no complaints there). It's a bit of an ugly duckling (SFINAE + type traits metafunctions + variadic function templ... |
4,413,890 | 4,413,952 | What's better in that context - `for` or `while` | I've read somewhere that one should use a for loop when you are iterating over some sort of array/sequence/list/whatever you call it and a while loop when your loop needs to stop at a certain condition.
So, what if I have something like this
int len = 0;
for(; s[len] != '\n'; ++len) {
// some processing
if (s... | I'd probably write it this way:
int len;
for (len = 0; s[len] != '\n'; ++len) {
...
}
return len;
Just because then I say in the for statement what the range is I'm interested in (index 0 up to the first newline character).
I generally choose between for and while on the basis of what the code looks like, rather t... |
4,414,027 | 4,415,711 | Visual C++ Unmanaged Code: Use /EHa or /EHsc for C++ exceptions? | If I'm creating a new project in unmanaged C++, Visual Studio 2008 or greater, which exception handling model do I want to go with?
I understand that /EHa option results in less efficient code, and also catches SEH exceptions, right?
So I have been steering clear of that option and typically going with /EHsc, so that I... | /EHa does two things. First and foremost, it suppresses an optimization that omits exception filters that automatically call the destructors of local class variables if the code analyzer cannot see any code that might throw a C++ exception. This makes stack unwinding safe for any kind of exception, not just a C++ exce... |
4,414,042 | 4,414,192 | async_write - boost. Does it copy the buffer? | async_write(*this, BoostAsio::buffer(pck->_storage), boost::bind(&tcp_socket::handle_wrote, this, pck, BoostAsio::placeholders::error));
pck is allocated on heap, if I delete it, would _storage become invalid as well or does async_write copy the buffer into its internal structures and it can be freely deleted/allocate... | The async_write function does not copy the buffer. It passes an internal const_buffer object to deeper library functions. The const_buffer object contains an internal pointer to the actual buffer, so no deep copy is performed. You need to make sure that pck->storage remains valid until after the asynchronous handler... |
4,414,054 | 4,415,312 | Best practice for std::auto_ptr | I'm just getting used to smart pointers using std::auto_ptr.
Assume that I want to call a function with both auto_ptr and normal Pointers.
auto_ptr<uint32> data_smart(new uint32[123])]);
uint32 data_fix[123];
uint32* data_dumb = new uint32[123];
processData(data_smart);
processData(data_fix);
processData(data_dumb);
... | In your situation using a vector is the safest choice:
std::vector<uint32> data(123);
The signature of processData should ideally be:
void processData(const std::vector<uint32> & data);
However, this one is more frequently used:
void processData(uint32 * bytes, int length);
In both cases you can use the vector:
// 1... |
4,414,090 | 4,414,152 | Does there exist an "unput" for std::ostream like there exists "unget" for std::istream? | I have some parsing code that allows for escape sequences to be entered into a string of text:
// In a file or large, multi-line string ...
my_parameter="A setting for the parameter\nthat contains \"escape sequence\" characters"
When I parse it, I handle the backslashes and add the appropriate character to the string ... | Streams are an awful lot like the mail. each message sent on a stream is like a letter, and messages can be queued into buffers, which are like mailboxes.
If you were responsible for both putting messages into and taking messages out of a mail-box, then you could certainly know that a letter you just put there is st... |
4,414,204 | 4,414,226 | How to draw "pouring" effect in gdi+? | See the pic:
I know gradients, but in this pic, the gradient border is irregular, just like pouring water.
| I think you're referring to a "gradient" -- there is a LinearGradientBrush class that you can use for this purpose; you can also find an example on MSDN: Creating a Linear Gradient.
|
4,414,214 | 4,414,292 | OS-X support for std::tr1 | What is the current support for tr1 or the new C++0x on the Mac
I know that the gcc supplied with XCode is always a couple of versions behind that available from gcc.gnu.org so I was just wondering what the state of play for modern support was.
For example do I need to download boost to use shared_ptr or can I get it f... | OS X 10.6 ships with g++ 4.2.1 as well as g++ 4.0, but it should be straightforward to install your own build if you choose to. GNU tools are awesome for that. This builds on my machine, a Snow Leopard Mac with g++ 4.2.1:
#include <tr1/memory>
int main(int argc, char* argv[])
{
std::tr1::shared_ptr<int> p;
ret... |
4,414,316 | 4,414,335 | Is "node" an ADT? If so, what is its interface? | Nodes are useful for implementing ADTs, but is "node" itself an ADT? How does one implement "node"? Wikipedia uses a plain old struct with no methods in its (brief) article on nodes. I googled node to try and find an exhaustive article on them, but mostly I found articles discussing more complex data types implemented ... | A node is an incredibly generic term. Essentially, a node is a vertex in a graph - or a point in a network.
In relation to data structures, a node usually means a single basic unit of data which is (usually) connected to other units, forming a larger data structure. A simple data structure which demonstrates this is ... |
4,414,442 | 4,414,459 | How to pass a pointer to a function | I am trying to pass an array pointer to a method of a class, so the method can operate on the array.
However when I am passing it, the address seems to change.
The pointers are member variables.
Basically I am doing this:
unsigned char array[1000];
unsigned char * pointer = array;
printf("p%", &pointer);
setup(pointer... | &pointer is finding the address of the pointer, not the address of the array. You just want printf("%p", pointer);.
|
4,414,651 | 4,414,704 | C++ Passing an object by reference? | I have a class that represents an capture zone in a game. Inside of this class I have a vector of player's that are capturing that zone (CUtlVector is a vector class from the SDK I am using)
typedef CUtlVector<ConquestPlayer*> CappingPlayersType; (defined outside of class)
CappingPlayersType CapturePlayers;
In my Game... | Do you mean something like this?
const CappingPlayersType& CTriggerCaptureZone::GetPlayersCapturing() const
{
return CapturePlayers;
}
And in the calling function:
const CappingPlayersType& CapturePlayers = CaptureZones.Element(i)->GetPlayersCapturing();
size_t CapPlayersCount = CapturePlayers.size();
I haven't l... |
4,414,655 | 4,414,941 | Server client app, I'm having trouble thinking of a clean way to process client data on the server side | I have a server client app written in C++ on Linux. When a client connects to my server, the server spawns a thread that waits for the client to send the server commands to execute. the commands are OS dependent. the thread that the client is talking to the server on, calls global functions that perform the required co... | This doesn't sound like a threading problem.
Sounds like you can use simple inheritance.
Using something like
abstract class OSMethods {
void listDir();
}
class OSMethodsLinux : OSMethods {
void listDir() { system.exec("ls"); }
}
class OSMethodsWin : OSMethods {
void listDir() { system.exec("dir"); }
}
Then se... |
4,414,674 | 4,417,550 | In the C++0x standard there will be unordered_map, how does this compare to boosts unordered_map? | Which is more efficient? Are there any good benchmarks out?
| C++11's std::unordered_map specification is similar to boost::unordered_map which is based on tr1::unordered_map. That being said, there are some small differences. The addition of rvalue references in C++11 result in the addition of the emplace and emplace_hint functions that may be useful for performance.
C++11 is no... |
4,414,814 | 4,419,623 | calculations in function seem to be ignored, same number returned always | growthRate function: (as of 8:00 PM 12/11/2010)
#include "header.h"
float growthRate (float birthRate, float deathRate)
{
float growthrt;
growthrt = (birthRate) - (deathRate);
cout << growthrt << endl;
return growthrt;
}
estimatedPopulation function: (as of 8:00 PM 12/11/2010)
#includ... | You don't see a problem with this code?
void output ()
{
float currentPopulation, years;
cout << estimatedPopulation (currentPopulation, years) << endl;
}
If you really can't see why this is wrong, then you should start off with MUCH simpler programs.
|
4,415,082 | 4,415,114 | Translating C++ Classes to Delphi | I am translating some C++ code to Delphi and there are some abstract classes that need to be translated. These classes are used as parameter/return types, etc, and my question is if a C++ class hierarchy such as this:
class Thing {
virtual void blah() = 0;
};
class Thing2 : public Thing {
virtual bool asdf(Thi... | Not quite. In C++, marking a method as = 0 means it's an abstract method. In Delphi, to get the same effect, you have to mark it as virtual; abstract;, not just as virtual;.
Also, in Delphi, if you place a class member declaration immediately under the class name, it'll be declared by default as published, which mean... |
4,415,302 | 4,415,505 | Varargs class method header conversion error | I have a C++ class that I am converting to Delphi that has a varargs member function like this:
class ICInterface {
virtual void printf(const char* fmt, ...) = 0;
};
I have tried to do this to make equivalent Delphi code so I can call it from Delphi:
ICInterface = class
procedure printf(fmt : PAnsiChar); varar... | It is unclear what are you trying to do.
If you need Delphi analogue of C++ code
class ICInterface {
virtual void printf(const char* fmt, ...) = 0;
};
it is
ICInterface = class
procedure printf(fmt : PAnsiChar; const args: array of const); virtual; abstract;
end;
but it is not binary compatible with C++ code... |
4,415,350 | 4,415,372 | How can one obtain the "name" of a process start address as done in Process Explorer? | Okay, I'm writing an application designed to enumerate threads in a given process, just as Process Explorer does. I'm well aware that this is potentially going to break between different windows versions, because it relies on "unofficial" APIs like NtQuerySystemInformation, and I'm perfectly fine with that.
I already h... | If all you need is the module name, the simplest way is to use EnumProcessModules to get a list of all the loaded the modules, then use GetModuleInformation on each of them. One of the things that GetModuleInformation returns is the base address where that module is loaded. Technically, the integer value of the HMODULE... |
4,415,524 | 4,415,646 | Common array length macro for C? | I've seen several macros for array length floating around:
From this question:
#define length(array) (sizeof(array)/sizeof(*(array)))
#define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))
#define SIZE(array, type) (sizeof(array) / (sizeof(type))
And Visual Studio's _countof:
#define _countof(_Array) (sizeo... | Here's a better C version (from Google's Chromium project):
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
It improves on the array[0] or *array version by using 0[array], which is equivalent to array[0] on plain arrays, but will fail to compile if array happens to be a C++ ty... |
4,416,051 | 4,416,075 | In C++,is it possible to define a class used as: SomeObj obj1; SomeObj<4> obj2; | I want to implement a string class which has an option to create the inner buffer on stack or heap. So that I think about the appearance of that string like:
String str_on_heap;
String<512> str_on_stack;
will be elegant. But, latter I find that it is hard to implement such an interface in C++.
template < int StackBuff... | If the String class is a template, you always need to use the <> notation when referring to the class.
What you can do is write a template specialization for the case when StackBufferSize == 0, which will use the heap.
template <int StackBufferSize = 0>
class String
{
// code to allocate string on the stack
};
templ... |
4,416,132 | 4,416,152 | strncpy() to get end of string | I am using C Style strings for a project, and I am confusing myself a bit. I am checking strings to see what they are prepended with (zone_, player_, etc) then getting the rest of the string after that.
else if(strncmp(info, "zone_", 5) == 0)
{
int len = strlen(info);
char *zoneName = new char[len];
strncpy... | You have to remember that C-style strings are terminated with a NUL character. You've allocated enough space in zoneName, but you only need len-5 plus one:
char *zoneName = new char[len - 5 + 1];
Then, you can actually use strcpy() to copy the tail of the string:
strcpy(zoneName, &info[5]);
You don't need to specify ... |
4,416,135 | 4,416,182 | Should I include files included in another header? | Most often when creating multiple classes inside a program that use each other, I like to include only the minimum number of header files I need to reduce clutter.
For example, say class C inherits from class B, which contains class A. Now of course since class B contains class A as a member, it needs to include a.h in... | Include what's necessary for the header file to be parsed without relying on external include ordering (in other words : make your headers self-sufficient).
In your case, if c.h declares a class C which inherits from class B, obviously you must include B.h. However, if class A never appears in c.h, I believe there is n... |
4,416,144 | 4,416,198 | How can I (at compile time) determine if a typename is a function pointer typename? | Consider the following wrapper around Win32's Runtime Dynamic Linking mechanism:
#include <boost/noncopyable.hpp>
#include <windows.h>
#include "Exception.hpp"
namespace WindowsApi
{
class RuntimeDynamicLinker : boost::noncopyable
{
HMODULE hMod_;
public:
RuntimeDynamicLinker(const wchar_t ... | You could use is_pointer<T>::value && is_function<remove_pointer<T>::type>::value in a static_assert/BOOST_STATIC_ASSERT.
|
4,416,217 | 4,416,272 | How should I implement a static collection of Strings in my class | I am very new to C++ so this might be an easy question to answer. I am writing a class (Person) and when a Person is created it should be assigned a random name from a collection of predefined names. So within the Person class I would like to define some sort of static collection of strings that I can access randomly... | You could use QStringList.
Person.h:
class Person
{
private:
static QStringList names;
};
Person.cpp:
QStringList Person::names = QStringList() << "Arial" << "Helvetica"
<< "Times" << "Courier";
|
4,416,267 | 4,416,384 | Code breaking when trying to set member variable in constructor | I have a class like this:
class Player
{
public:
Player(Board * someBoard);
void setSide(char newSide);
protected:
Board * board;
char side;
};
and its implementation is as such:
Player::Player(Board * someBoard)
{
board = someBoard;
side = '0';
}
void Player::setSide(char newSide)
{
sid... | Is it possible that you are using two incompatible definitions of your Player class, defined in different header files? If the definitions have different sizes, then the 'size' member might lie outside the memory block allocated for the class instance.
Edit I see that your problem has disappeared. So it was probably a... |
4,416,348 | 4,416,383 | Test for a program I'm programming | Hay!
I would like to create a test that can find the complexity (time & space) of the program.
function by function...
I thought of doing so with the library "time" and to count seconds while running the functions for a large number of "n".
Does anyone have a better idea? maybe it already exists? :)
Thanks!
Amihay
| Looks like a perfectly reasonable approach, for the time complexity at least. Make sure that your program outputs in a useful format, for example CSV or tab separated, so that you can easily copy/load this into a spreadsheet.
Space complexity might be a bit more tricky to get reliably. For this, you might want to modif... |
4,416,444 | 4,416,585 | C++: hiding some functions | I redefined some maths functions (so that they're faster -ie: less accurate-, or use templates). I put these functions in a namespace and they work just fine.
It happens often, though, that I forget to call functions from my namespace (ie: I forget to write mymath::cos or using mymath::cos; when I want to call cos), an... | Put this in a header file, and #include it everywhere:
namespace DontUseMe {
double cos (double) ;
// ...etc.
}
using namespace DontUseMe ;
|
4,416,478 | 4,416,836 | Avoiding null pointers and keeping polymorphism | In my code I just noticed that I quite often need to check for nullptr, even though nullptr should not be possible (according to specified requirements).
However, nullptr might still occur since other people might send a nullptr believing this is ok (unfortunately not everyone reads/writes specification), and this defe... | I personally prefer to encode the null possibility in the type, and thus use boost::optional.
Create a data_holder class, that always owns a data (but allows polymorphism)
Define your interfaces in terms of data_holder (non-null) or boost::optional<data_holdder>
This way it is perfectly clear whether or not it may be... |
4,416,551 | 4,416,568 | Stack memory allocation and deallocation mechanism | If I pass by value as an argument to a particular function, then will that function deallocate memory of this parameter when the function execution ends?
If I pass a pointer or reference as argument, what happens if function deallocates memory of the pointer argument? Will it affect to the variable outside of function... | In the first case memory will be "deallocated" (actually stack pointer will be increased). If this is not POD type variable destructor is called, so the memory will be deallocated from heap if it was allocated there.
In the second case value referenced by pointer won't be deallocated - only memory for pointer will be d... |
4,416,569 | 4,416,774 | C++/C -assembly level questions |
When a global variable is used inside a function(C/C++), whether it'll be taken directly from registers or from stack?
Why bound loops(for loops) are considered to have more scope for optimization than nobound loops(while loop/do while)?
Why returning a value is not as good as passing the value by reference?
If possi... | 1) Global variable is statically allocated by linker
(it can be an offset from module's base though, not
necessarily a fixed address).
Still, a function would usually read a global var from
a direct address, and a local var from offset + stack pointer
and a class field from offset + object base pointer.
The value of ... |
4,416,715 | 4,416,810 | API for C/C++ programs. Which technique? | Please, could you explain, which technique is common for developing API for C/C++ programs?
One example is sockets. And what else?
Thanks...
| Have a look at the APIs standardised by the Khronos Group. They have a well-established convention of defining library interfaces in a concise way.
No, they probably don't hold the Guiness record for "Most convenient API", but they indeed could have one for "Most consistent API stanard", "Best legacy API deprecation mo... |
4,416,718 | 4,416,740 | C++ array of objects. One element to access method of another element in array | I have array of objects
MyClass MyArr[10];
In method of one element of array ( MyArr[j] ) I need to access to method of another element in this array ( MyArr[i].Method2(arg) ).
How I Can do this?
Access from one element of array to another element of array?
| There's lots of ways. Some are:
make MyArr a static variable of the MyClass class
pass MyArr[i] as a parameter to the method call on MyArr[j]
construct each object passing in a pointer or reference to the other instance
|
4,416,724 | 4,419,416 | List to priority queue | I have a college programming project in C++ divided into two parts. I beggining the second part where it's supposed to use priority_queues, hash tables and BST's.
I'm having trouble (at least) with priority queues since it's obligating myself to redone a lot of code already implemented in the first part.
The project it... | It sounds like you need a priority queue with efficient increase and decrease key operations. You might be better of creating you own your own priority queue implementation.
The priority_queue container is great for dynamic sets. But since the number of terminal in an airport are pretty much fixed you can a fixed size ... |
4,416,744 | 4,416,796 | Optimize an array of tribools for space | Let me start with some background:
By "tribool" I understand a variable which can hold one of the following values: true, false or null.
In question Copying array of ints vs pointers to bools , the OP wanted to have an array of tribools (more or less) which would be as small as possible.
With "a bit of" most basic bit-... | Your intuition is correct, this is certainly possible. This is basically a form of arithmetic coding, or at least a simple instance of it.
The easiest way to think of it is to imagine encoding your array of "tribools" as a number in base 3 - e.g. 0=FALSE, 1=TRUE, 2=NULL. Then the following array:
{TRUE, FALSE, NULL, NU... |
4,416,765 | 4,416,787 | reincluding header in implementation | suppose I have a header foo.h like this:
#ifndef FOO_H
#define FOO_H
#include <string>
#include "non_standard_class.h"
std::string foo(MyClass a);
...
#endif
and the implementation foo.cpp will be
#include <vector>
#include "foo.h"
std::string foo(MyClass a)
{
std::vector<int> x;
MyClass b;
...
}
is it a ... | The practice I follow:
foo.h should directly include all headers its source code needs (i.e. #include <string> if there is std::string in foo.h)
foo.cpp should directly include foo.h plus all other headers its own source code needs, except for those already directly included by foo.h
Another formulation of this pract... |
4,416,779 | 4,416,872 | How do I use the QTable? Adding, editing, removing and retrieving rows | How do you use the QTable object. I have searched the internet and the examples don't really seem to make sense. Do you just create a new row within the extended class. It all seems fussing. How do you retreive, edit and delete rows. Is there any extensions that could be used like
QRowObject *row = table->add("Main Tit... | QTable is pretty old. You might be looking for QTableWidget. If you want to get into the whole 'Model-View' arch thing, look into QTableView.
// inside e.g. a QMainWindow, parent could be 'this'
QTableWidget *widget = new QTableWidget(parent);
// add to layout etc, then:
QStringList headerLabels;
headerLabels << "Fir... |
4,416,932 | 4,417,005 | Typedef redefinition (C2371) for uint32 in two 3rd-party libraries | In my application I am using Box2D and Spidermonkey. Both libraries are defining the type uint32, which obviously gives me a compiler-error when using both in the same compilation unit.
b2settings.h (Box2D): typedef unsigned int uint32;
jsotypes.h (Spidermonkey): typedef unsigned long uint32;
Is there any way to resolv... | You can do this hack:
#define uint32 Box2D_uint32
#include "Box2D.h"
#undef uint32
#define uint32 Spider_uint32
#include "Spidermonkey.h"
#undef uint32
Since typedef is merely an alias, this shouldn't cause ODR violation as long as these headers contain declarations only. If there is a (struct or inline function) defi... |
4,417,072 | 4,417,107 | C++: this-pointer overwritten | Please take a look at my source files, they're a bit too long to post them here:
X11Painter.cpp: http://pastebin.com/gu4SrHUr
X11Painter.h: http://pastebin.com/3ktp1Fvn
The behaviour of this class is in my opinion very strange.
I'm having the following test case:
#include "X11Painter.h"
int main()
{
X11Painter p ;
... | In your parameterless constructor, you do this
X11Painter::X11Painter()
{
X11Painter(-1);
}
This is not doing what you think it is doing, since there is no constructor chaining in C++. What the code above is doing is constructing a temporary X11Painter object, calling the other constructor for that temporary objec... |
4,417,155 | 4,417,258 | Floating point arithmetic at compile-time | Are floating point calculations, which use compile-time constant integers, performed during compile-time or during run-time? For example, when is the division operation calculated in:
template <int A, int B>
inline float fraction()
{
return static_cast<float>(A) / B;
}
| I believe it is implementation defined, but most compilers will evaluate constant expressions at compile time. However even if yours does not the following modification:
template <int A, int B>
inline float fraction()
{
static const float f = static_cast<float>(A) / B;
return f ;
}
will at least ensure that t... |
4,417,191 | 4,417,227 | Composition in c++ with raw or smart pointer? | A little example of what I want to do.
I have a list of (stack allocated) vertices
class Vertex {
int id;
double x;
double y;
double z;
};
and want to create a list of edges
class Edge {
int id;
Vertex * source;
Vertex * target;
};
with two pointers to its source and target vertex.
Norma... | What Composition is
Composition (in UML terms) is an association when a given object is "a part" of another objects- i.e. it has the same lifetime and - what's most important and characteristic - does not exist / make sense on its own.
According to this description, composition is not what we want to achieve - see the... |
4,417,199 | 4,417,344 | Custom ostream without flushing? | Currently I create an ostream with a custom stringbuf derived object, but it uses sync() to print text on the screen. Is there a way to avoid having to flush it? I really want to do logStream << "Test"; without std::flush or endl.
| See my answer to this related question: Custom stream to method in C++?
All you really need to change is to add the flush instead of the function call and your stream instead of the stringstream.
Edit: Just saw that was your question. The answer still works though.
|
4,417,219 | 4,417,294 | Use of qualified name in function parameter | According to the C++ Standard, function parameter's name is parsed by a declarator-id, and a declarator-id can also be a qualified name. That means, the following code is perfectly valid (if I've understood the relevant sections from the Standard correctly):
template<class T>
struct Sample
{
int fun(int T::count);... | It's invalid. The syntax allows arbitrary declarators, but 8.3.5p8 says
An identifier can optionally be
provided as a parameter name; if
present in a function definition
(8.4), it names a parameter (sometimes
called “formal argument”)
Edit Another quote which syntactically constraints declarators (8.3p1, [dcl... |
4,417,351 | 4,438,825 | Replace image with another one in QTextEdit | Say there is a text and images in a QTextEdit. And say you extract HTML code of the QTextEdit. Now how it is posible to find the places in the HTML code where the images are instantiated () and replace with another images that I have as a QImage objects retaining the position and the size of the former image.
In other ... | //Add images as resources
for(int i = 0; i < vectorOfImages.size(); i++ )
{
QUrl url(QString("image_%1").arg(i));
textEdit->document()->addResource(QTextDocument::ImageResource, url, vectorOfImages.at(i));
}
//Process the htmlCode that is in QTextEdit.
int count = 0;
int pos = 0;
QRegExp rx("<img src=\".+/>... |
4,417,544 | 4,417,604 | Where is the original of the statement "the most derived class's ctor needs to directly call the virtual base class's ctor"? | While I learn how to implement a final class in C++, I find such a statement:
"the most derived class's ctor needs to directly call the virtual base class's ctor."
However, I can't find the original of the statement in the C++ standard. (N3126)
Who can tell me the exact page number?
Thanks in advance.
| In C++03, it's § 12.6.2 5
Initialization shall proceed in the following order:
— First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, w... |
4,417,682 | 4,417,830 | Custom stream flush type | I've had multiple questions on the matter of streams and stuff, but after thinking for a bit, I've come to the conclusion that all I need is a custom flush type. I want my stream to flush when it gets a new line. It saves having to type out std::endl. Is it possible to implement this? I'm using an ostream with a custom... | I believe all it would take is overriding ostream::put(char), but don't quote me on that:
template <typename Ch>
class autoflush_ostream : public basic_ostream<Ch> {
public:
typedef basic_ostream<Ch> Base;
autoflush_ostream& put(Ch c);
};
template <typename Ch>
autoflush_ostream<Ch>& autoflush_ostream<Ch>::put... |
4,417,782 | 7,240,019 | How to avoid errors while using CRTP? | Using CRTP sometimes I write a code like this:
// this was written first
struct Foo : Base<Foo, ...>
{
...
};
// this was copy-pasted from Foo some days later
struct Bar : Base<Foo, ...>
{
...
};
And it's very difficult to understand what goes wrong, until I trace code in debugger and see that Bar's members are... | In C++0x you have a simple solution. I don't know whether it is implemented in MSVC10 however.
template <typename T>
struct base
{
private:
~base() {}
friend T;
};
// Doesn't compile (base class destructor is private)
struct foo : base<bar> { ... };
|
4,417,788 | 4,417,902 | Pointer changes value for no reason c++ | I am trying to store a pointer as a member variable, so that during the life of the class, other functions can work with the pointer.
However, when I first setup this class, the pointer variable is correct for the first printf, but when the second one is called, the value is 0x0
In my main, setup is called once first, ... | As written, and after fixing minor compilation errors (by supplying NULL and 0 as the other arguments to setup, for example), the code as presented does not exhibit the behaviour you describe when I run it. In particular, it prints out the same non-NULL pointer 101 times. Conclusion: this is not the code you're having ... |
4,417,797 | 4,417,833 | Why is inheriting constructors not supported by ALL of the existing C++ compilers? | For now, both of G++ and VC++ 2010 don't support inheriting constructors.
However, I think this is one the most beautiful features in C++0x. And I think it should be rather easy to implement by the compiler.
Why are the compilers not interested of this feature?
Assume I want to design my own string class by inheriting ... | There's a lot of new material in C++0x, and it seems that the volunteers working on gcc found other changes more interesting to work on first.
As for VC++, there's not only the prioritization of work, but the additional costs (often mentioned on Microsoft product manager blogs) of requirements, documentation, and very ... |
4,417,845 | 4,417,858 | How to create an int pointer on the stack? | void func(int* param){};
func(&123); //error: '&' on constant
funct(&int(123)) //error
| That's not how pointers work.
You must first allocate memory for your 123, like this:
int x = 123;
func(&x);
|
4,417,883 | 4,417,919 | Why doesn't compile issue an error for code that results in undefined behavior | For example, articles usually say that if malloc and delete is paired up, or say that it is wrong and don't do it.
But why doesn't compiler do some checking for us.
Will there be any cases that this kind of code is right and intended? Therefor compiler can't always say it's wrong to do it?
Or is there any technically... | Many reasons. Off the top of my head.
Some undefined behaviour may have defined effects as an implementation specific extension.
Some undefined behaviour only occurs based on a program's environment or input, so the code might has the potential to cause undefined behaviour but won't necessarily do so.
Many instances o... |
4,417,904 | 4,420,102 | C++ and GUIs for teaching | So, I've been tasked to teach a programming course which includes some stuff about GUI programming in C++. I was wondering, what would be the best setup for this? Linux, and GCC are my tools of choice.
I've never done a course like this, I'm a good C programmer but not a C++ programmer. I need C++ because the same cour... | FWITW, Bjarne Stropstrups uses FLTK for the same purpose: http://www.stroustrup.com/Programming/sw_stack.html
|
4,417,915 | 4,419,177 | problem with painting one widget inside another one (parent) | I am trying to make a simple game under Qt 4.6. The idea is to have two widgets, one is the main window widget and represents the space and the second one is a starship widget inside the space (parent).
Simplified code looks like this:
/*this is ship and child widget*/
class MyRect : public QWidget {
Q_OBJECT
public:... | • QPainter painter(itsParent); - wrong. You should draw only on this widget's surface, not on parents. So correct will be QPainter painter(this);
• You should not save widgets body in MyRect class. Class space must keep its size and position. So in MyRect::paintEvent() change painter.drawRect(*body); to painter.drawRe... |
4,417,989 | 4,421,983 | relinking applications that use updated shared library with implicit linking? | Let's say I changed a shared library and recompiled it.
Do I have to relink all main applications that use that shared lib (in case I'm using that shared library with implicit linking - #include "myLib.h") or relinking is done automatically when those applications load?
| You have to recompile only if the Application Binary Interface (ABI) of the library is incompatible with previous version - it could happen if some public functions are removed or their signature is changed, if some structures' sizes are changed, virtual functions order is changed and some other cases.
Otherwise you d... |
4,418,532 | 4,418,575 | I need to ungzip/regzip a file for edit in my c++ in windows | I'm working on a small application that parses a certain file, un-encrypts, makes changes, re-encrypts, and saves. It works well, but for it to work I need to manually ungzip it, run the application on the output, then gzip what comes from that. I'm just wondering if someone knows of an elegant solution/library I can ... | Zlib does that. And CGZip implements a C++ wrapper for it. And here is an example of how to detect if a given file is gzipped.
Testing GZIP files
First, we should reference the "RFC 1952 GZIP File Format Specification Version 4.3". This is the document shown in the screenshot. It contains useful information about th... |
4,418,549 | 4,418,607 | Need Webkit and C++ example code for reading and displaying HTML from file | I'm looking for some C++/webkit example code or some grate tutorials. Here is what i need in the example:
1. Read Html file from disk, and render the htmlvascript and display content
2. I need so its independent from any other web browsers on pc, using only webkit.
thnx
| Have you considered using Qt because it would be dead simple with it?
Basically something like this:
QWebView view;
view.load(QUrl("http://www.google.com"));
view.showMaximized();
|
4,418,635 | 4,418,649 | obscure c++ operator |
Possible Duplicate:
What is this weird colon-member syntax in the constructor?
Can someone tell me what the last line of this code block does? I have looked up the : operator but only found it in a context for variables, not with a function.
class Vec3
{
public:
float x, y, z;
Vec3() {}
Vec3(float _x, f... | This is not obscure, it's the C++ initialization list syntax
Basically, in your case, x will be initialized with _x, y with _y, z with _z.
|
4,418,691 | 4,418,705 | error C2109: subscript requires array or pointer type | #include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
bool premiereLignefaite = false;
//Lire le fichier
FILE * graphe = fopen("graphe.txt", "r");
//Fichier de sortie
FILE * resultat = fopen("resultat.txt", "w");
int nbr1, nbr2;
int *matrice; //pointeur vers la matrice d'adjacence
//Li... | int *matrice; means that matrice is a pointer to an int (or ints), so matrice[a] will give you an int. A pointer does not have any information about the dimensions of the array, so you can't do two-dimensional access.
You want to do store the dimensions of your array and then do
matrice[nbr1 * numberOfColumns + nbr2] =... |
4,418,706 | 4,419,006 | How to expose template template arg | Let's assume that I have following class template:
<> - read as template
template<template<class T> class Policy>
struct
{
};
How (without adding additional params to this <>) can I expose Policy type to external world?
typedef won't work, and why for the loG can't I write something like this:
typedef Policy<T> P... | I know it is possible with C++0x, but I don't know the syntax. In the meantime, the closest fit in C++03 is
template <template <typename> Pol>
struct Foo
{
template <typename T>
struct policy
{
typedef Pol<T> type;
};
};
usage: typename Foo<F>::template policy<T>::type where you would have want... |
4,418,708 | 4,418,774 | What's the rationale for null terminated strings? | As much as I love C and C++, I can't help but scratch my head at the choice of null terminated strings:
Length prefixed (i.e. Pascal) strings existed before C
Length prefixed strings make several algorithms faster by allowing constant time length lookup.
Length prefixed strings make it more difficult to cause buffer o... | From the horse's mouth
None of BCPL, B, or C supports
character data strongly in the
language; each treats strings much
like vectors of integers and
supplements general rules by a few
conventions. In both BCPL and B a
string literal denotes the address of
a static area initialized with the
characters ... |
4,418,773 | 4,418,859 | Reading file until blank line | After reading Jerry Coffin's answer on this question I copy-pasted his code into my editor, and after some minor edits it compiled and run like it should.
Here is the code after the changes:
#include <iostream>
#include <string>
#include <istream>
#include <fstream>
class non_blank {
private:
std::string data_;
... |
Shouldn't I be able to use a variable
of the type non_blank anywhere I would
use a std::string? Isn't it the
porpuse of the cast operator?
Not quite. If the compiler sees you doing something that it knows requires a std::string, it can call your conversion operator to get one. But in the case of the ostream o... |
4,419,104 | 4,419,192 | Vector of pointers to abstract class,to access derived class members |
I'm new to C++ and trying to implement a turtle emulator that will read commands from a text file, put them on a vector and draw them using glut
I have node class,command class derived from node, 4 derived classes(forward,left,right,jump,repeat) from command and Prog class that is used to store commands.
class node
{
... | Based on what you describe, pro.push_back( new Forward(value) ); is what you're looking for.
Also, a function or class must be declared as friend in every class that will have non-private members be accessed by it.
|
4,419,143 | 4,419,156 | using ifstream in c++ | I have the following code to read in from a file
#include <queue>
#include <iostream>
#include <fstream>
#include <string>
main(int argc,char * argv[])
{
ifstream myFile(argv[1]);
queue<String> myQueue;
if(myFile.is_open())
{
while(...
///my read here
}
}
I have input file like t... | string input;
myFile >> input;
myQueue.push(input);
Untested but I believe it works.
By the way, if you want to parse the whole file:
while(myFile>>input)
Thanks to rubenvb for reminding me
|
4,419,226 | 4,419,248 | Object initialization problem in C++ header file | I am coding in C++, and I have private data members in the header file of a class.
private:
Object1 obj1;
Object2 obj2(&obj1);
So, the second object takes a pointer to the first object. When I try to compile the program, I get the following error:
"expected identifier before ‘&’ token"
Is there a way to i... | What your compiler is telling you with this error is that you are trying to make a method called obj2, returning an Object2 that is taking a reference as a parameter. But it can't figure out what the type of the reference is.
On the other hand if you want to set the reference before the construction of the object you c... |
4,419,293 | 4,419,347 | warning: format not a string literal and no format arguments | I want to remove the warning that i get on this line of the code,
FILE *fil;
char *imp;
(...)
fprintf(fil,imp);
the thing is when i do this it writes on the file exactly what i want, but if i apply the format %s it doesn't, like this
fprintf(fil, "%s", imp);
| This warning is gcc's way of telling you that it cannot verify the format string argument to the printf style function (printf, fprintf... etc). This warning is generated when the compiler can't manually peek into the string and ensure that everything will go as you intend during runtime. Lets look at a couple of examp... |
4,419,375 | 4,419,401 | templated constructor vs. templated copy constructor | I have a class with a templated constructor for implicit move conversion, however this constructor should NOT be used for the class (which should only be copy constructible). However, the compiler always tries to use the templated constructor instead of the regular copy constructor.
e.g. With this i get the follow comp... | Okay, here is my complete overhaul of my_class:
class my_class
{
public:
my_class() {}
my_class(my_class&& that) : impl_(std::move(that.impl_)) {}
template <typename T> my_class(T&& impl,
typename std::enable_if<
std::is_base_of<
implementation,
typename std::remove_refe... |
4,419,485 | 4,419,509 | use array in structure c++ | I have a struc like this:
struct process {int PID;int myMemory[];};
however, when I try to use it
process p;
int memory[2];
p.myMemory = memory;
I get an criptic error from eclipse saying int[0] is not compatible with int[2];
what am i doing wrong?
Thanks!
| Don't use static arrays, malloc, or even new if you're using C++. Use std::vector which will ensure correct memory management.
#include <vector>
struct Process {
int pid;
std::vector<int> myMemory;
};
Process p;
p.reserve(2); // allocates enough space on the heap to store 2 ints
p.myMemory.push_back( 4815 ); /... |
4,419,496 | 4,419,511 | NULL pointer returned by new and malloc, why? | #include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
void multiplier_matrice_vecteur (char * v0, char * A, int N)
{
int i,j,k;
char somme;
for (i = 0; i < N; i++) //On fait N calculs car c'est une matrice 1xN
{
//On fait N additions + multiplicat... | You should use
matrice = new char[nbr1 * nbr1];
and remember to free with
delete[] matrice;
|
4,419,503 | 4,419,549 | Iterator equivalent to null pointer? | In an algorithm I'm currently implementing, I need to manipulate a std::list of struct T.
T holds a reference to another instance of T, but this reference can also be "unassigned".
At first, I wanted to use a pointer to hold this reference, but using an iterator instead makes it easier to remove from the list.
My quest... | According to this (emphasis by me):
Compared to the other base sequence
containers (vector and deque), lists
are the most efficient container doing
insertions at some position other than
the beginning or the end of the
sequence, and, unlike in these, all of
the previously obtained iterators and
reference... |
4,419,620 | 4,419,666 | c++ not able to find file (i think) | I have the following code (simplified)
int main()
{
ifstream myFile("input.txt");
if(myFile.is_open())
cout<<"test";
}
However myFile.is_open() is returning false;
why?
I'm using eclipse and the input.txt file is right in the src folder with the .cpp file...
Thanks!
| Every executable is - by default - ran from the directory of your project. So for a tree like this:
project
|- src
| |- a.cpp
| |- b.cpp
| |- foo.txt
|
|- Debug
| |- a.exe
|
|- foo2.txt
You shall use the paths like src/foo.txt or foo2.txt. Your exe is located in Debug directory, but it will be ran from yo... |
4,419,697 | 4,420,439 | Link to libraries built by GCC when I use ICC for my code | For a personal project on Linux, I would like to use ICC. My project uses Boost, Qt and several other libraries. These libraries are available on Ubuntu repository so I would like to save time by installing these prebuilt ones.
Is it possible for me to link dynamically my ICC-built executable with the libraries built b... | Yeah, it's possible. It may not be the safest thing ever, and I wonder why you want to use ICC for a personal project, but it could be OK, and you can use tools like valgrind to help you detect issues at run time for extra peace of mind.
|
4,419,747 | 4,419,754 | Thinking in C++ error in source code | I am reading the book Thinking in C++ (2nd edition Vol 1) and i have a problem when i try to compile this source code:
http://www.linuxtopia.org/online_books/programming_books/thinking_in_c++/Chapter16_015.html
The problem appears to be in that line:
Stack::Link* p;
As i have read in C++: error "... is not derived fro... | Yes, it's wrong. You need the typename. See the typename and template FAQ entry.
Stack is a dependent type and Stack::List is a dependent type too. This is legal in C++0x, but it's illegal in current C++.
|
4,419,799 | 4,428,205 | Converting QuantLib to QuantLib-SWIG C# | I have downloaded and built QuantLib (search google for quantlib and check install link) from their website in visual studio 2010. But because my knowledge of C++ is kind of minimal I would like to use SWIG so I can call the QuantLib libraries with C#. After the SWIG conversion I get a proper build. I thought this woul... | It might be some kind of version mismatch.
First: since you're using VC2010, I assume the version of QuantLib and QuantLib-SWIG you're using are checked out from Subversion; is this correct?
Second, did you use the VC2010 projects included in the checkout (the ones with _vc10 in the file name) for both QuantLib and Qua... |
4,419,802 | 4,419,820 | Getting a program only to run with certain dlls in the directory | When, for instance, I create a program and compile it with MinGW if I delete the environment variable I need to put the dll in the directory for it to work
ie. libgcc_s_dw2-1.dll
without it the program will not even start.
When developing with QT I noticed I needed another dll in the directory, it was QtCored4.dll, I w... | That is taken care by the operating system -- since your program uses functions from the DLL, it is automatically loaded when your program starts, and if the DLL is missing, you will get an error. You can read more about this process on MSDN: Load-Time Dynamic Linking.
|
4,419,954 | 4,419,991 | c++ delete reference | I'm still learning c++ and have a question that may be obvious, or maybe I just don't know what I'm trying to do. I have functions that take a matrix (a class I wrote, which has a properly written destructor) and create a new matrix from it, returning a reference to the new one. I need to iterate possibly tens of thous... | Stroustrup R'lyeh Fhtagn.
Writing MyType myVar = MyFunction() creates a brand new object using a constructor that accepts the return type of myFunction as an argument. Whatever was returned by myFunction is then discarded - in your example, getX0 returns a reference to an object that was allocated dynamically, and is t... |
4,420,181 | 4,420,200 | trying to create a c++ dll in visual studio but no dll file after successful build | hi
I have a pretty basic c++ project to compile, and I get 'build succeeded' but don't see a .dll file in the debug or release directories.
there are 4 object files, 2 manifest files, 1 idb, 1 dep, a vc90 debug database, a compiled resource script myprogram.dll.embed.manifest and a build log but no .dll
project propert... | If you have a separate solution directory, the DLL is under that directory\debug (or release).
|
4,420,199 | 4,420,217 | c++ static-only class allocation | I know how to prevent heap allocation of a class (make new and new[] private).
I know how to prevent stack and static allocations (make destructor private).
I am wondering is there anyway to allow only static allocations at compile time?
| Nope. Sorry. Reason is that the static allocation places exact same requirements on the type as automatic allocation; it can't be distinguished.
However, you can prevent client code from instantiating your type, and provide access to one or more instances created by the type's own code.
Generally people often think tha... |
4,420,379 | 4,420,496 | Crash when C++ program calls Delphi DLL function | I have an abstract class in a C++ program that looks like
class Interface {
virtual void blah() = 0;
virtual int asdf() = 0;
};
and that C++ program allows you to load DLLs with LoadLibrary. When you load a DLL, it calls a function in the DLL called Setup with GetProcAddress, passing a pointer to a subclass o... | If your C++ code really is as you say it is, you need to determine what calling convention it's using. Is it definitely using the C calling convention? What is it compiled with, and what flags for calling convention?
Your Interface class needs to include the calling convention too, something like:
Interface = class abs... |
4,420,462 | 4,420,565 | Writing to file using c and c++ | When I try to write the file using C; fwrite which accepts void type as data, it is not interpreted by text editor.
struct index
{
index(int _x, int _y):x(_x), y(_y){}
int x, y;
}
index i(4, 7);
FILE *stream;
fopen_s(&stream, "C:\\File.txt", "wb");
fwrite(&i, sizeof(index), 1, stream);
but when I try with C++;... | This is the way to write binary data using a stream in C++:
struct C {
int a, b;
} c;
#include <fstream>
int main() {
std::ofstream f("foo.txt",std::ios::binary);
f.write((const char*)&c, sizeof c);
}
This shall save the object in the same way as fwrite would. If it doesn't for you, please post your code... |
4,420,685 | 4,420,689 | Simple Way to Use a DLL | I followed the MSDN walkthrough on creating and using a DLL in Visual C++ Studio, but it requires the user to add the DLL project to the same solution as the project they're working on.
Is there a simple way to include a DLL? Ideally, I'd like to just distribute my .dll (and the .lib, I suppose) to my friends so they ... | At a minimum, you need to do the following:
Include the .lib file in the project
Tell the linker where you put the .lib file (library search path)
Make the .dll file available at runtime (easiest is to put it in the same directory as the .exe)
To distribute the compiled .dll to your friends, you will need to include:... |
4,420,891 | 4,420,985 | C++ new / new[], how is it allocating memory? | I would like to now how those instructions are allocating memory.
For example what if I got code:
x = new int[5];
y = new int[5];
If those are allocated how it actually looks like in RAM?
Is whole block reserved for each of the variables or block(memory page or how-you-call-it - 4KB of size on 32bit) is shared for 2 ... | A typical allocator implementation will first call the operating system to get huge block of memory, and then to satisfy your request it will give you a piece of that memory, this is known as suballocation. If it runs out of memory, it will get more from the operating system.
The allocator must keep track of both all t... |
4,421,106 | 4,421,260 | using typedef in declaring structs in C++ | I personally don't like old C-style of struct declarations like that:
typedef struct {} NewType;
ctags makes ugly anon types of this and make the debugging difficult. Is there any reason in C++ code using typedef struct instead of simply struct, except the code is used in both C and C++?
Regards,
Valentin
| One major drawback of those
typedef struct tagSomethingSomething SomethingSomething;
is that, forward-declarations are not possible with the commonly used typedef'fed name.
Yes, it's a C-ism (kudos sbi) and there are c++-codebases, where it - unfortunately - (still) is common.
|
4,421,148 | 4,421,178 | Two pointers different information stored | Is it true that having:
int* p = new int;
and:
int* p1 = new int[5]();
in case of p1 there will be extra info stored?
| Yes, there might be.
I recommend you read the following to items from C++-faq :
How does the compiler know there are n objects to be destructed using delete[] ?
How do compilers use "over-allocation" to remember the number of elements in an allocated array ?
A relevant quote extracted from the first link :
The run-t... |
4,421,367 | 4,421,383 | problem with win 32 API programming | i just tried to compile and run a simple example which was found on Programming Windows - Win32 API by Charles Petzold here is the code :
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
MessageBox (NULL, TEXT ("Hello, Windows!"), TEXT ("HelloMsg"), ... | There's no doubt this is a duplicate question but i'll answer anyway.
You have created the wrong project type. You need to create a Win32 Project not a Win32 Console Application.
|
4,421,462 | 4,422,344 | What are your favorite C++ idioms? |
Possible Duplicate:
What are your favorite C++ Coding Style idioms
Dear C++ fans,
Could you list here your favorite C++ idioms? It is better to list those which are useful yet not well-known.
Firstly, I put one of mine:
To avoid tedious repeating for (size_t i = 0; i < n; ++i) {...} , I use a macro like this:
#defin... | Good question but I think your example is a bad one! Your LOOP macro does not make anything clearer - it actually hides your intent from programmers who don't use your macro, and it doesn't even look like C++ - my first reaction to your snippet would be "is that even C++?" or "what's wrong with an ordinary for?". It ... |
4,421,505 | 4,421,560 | C++ references vs return values | I understand the principle point of references is to avoid making copies of large structures, but what if a function you're writing itself creates a large structure? Is it less efficient (or are you more likely to run out of memory) to create the variable locally, then return it, than you are to pass the destination ob... | The first example should presumably be more like one of these two:
void getLines(std::string in, std::vector<std::string> &out);
void getLines(std::string in, std::vector<std::string> *out);
The second style is often more convenient, and can in theory be made mostly as efficient as the first one:
http://en.wikipedia.o... |
4,421,506 | 4,422,352 | Implementing a priority queue that can be iterated over in C++ | I need to implement a priority queue for a project, but the STL's priority_queue is not indicated since we need to iterate over all elements and remove them randomly.
We are thinking about using the STL's set for this, wrapping it in a class to make it an ADT.
Is there a smarter solution for this?
How can we make it so... | You should be able to implement your own priority queue using std::vector, std::make_heap, std::push_heap, and std::pop_heap. Isn't this how std::priority_queue is implemented? You'll just need to call std::make_heap again to fix the data structure when you remove a random element.
Do you need to iterate over the eleme... |
4,421,518 | 4,421,591 | Value or reference semantics in this situation? | I don't have a feeling (yet, I hope) for whether to chose value or reference semantics in some situations. Is there any rule of thumb I can apply?
I usually pick references for everything other than the built-in data types (char, int, bool, double etc.). However, sometimes it's not possible to return references from a ... | Returning by value is fine, since most compilers will optimize the extra copy away (this is called Return Value Optimization, or rather Named Return Value Optimization in your case).
But the idiomatic way is
void bar(Foo& out)
{
out.do_stuff();
}
|
4,421,639 | 4,477,386 | Randomly permute N first elements of a singly linked list | I have to permute N first elements of a singly linked list of length n, randomly. Each element is defined as:
typedef struct E_s
{
struct E_s *next;
}E_t;
I have a root element and I can traverse the whole linked list of size n. What is the most efficient technique to permute only N first elements (starting from roo... | I've not tried it, but you could use a "randomized merge-sort".
To be more precise, you randomize the merge-routine. You do not merge the two sub-lists systematically, but you do it based on a coin toss (i.e. with probability 0.5 you select the first element of the first sublist, with probability 0.5 you select the fir... |
4,421,698 | 4,421,721 | Understanding the space occupied by an vector instance in C++ | I'm trying to understand the amount of bytes occupied by an instance of std::vector. The following code:
vector <int>uno;
uno.push_back(1);
uno.push_back(1);
cout <<"1: "<< sizeof(uno)<<" bytes"<<endl;
cout << endl;
vector <bool>unos;
unos.push_back(true);
cout <<"2: "<< sizeof(unos)<<"... | In C++, the sizeof operator is always evaluated at compile time, so every vector<T> will have the same size (unless vector<T> is a specialization like vector<bool>).
In case you are wondering about the 12 bytes, that is probably the size of 3 pointers, or alternatively, the size of a pointer and an element count and a ... |
4,421,840 | 4,447,626 | Parsing c++ function headers from a file using GNU toolchain | I need to parse function headers from a .i file used by SWIG which contains all sorts of garbage beside the function headers. (final output would be a list of function declarations)
The best option for me would be using the GNU toolchain (GCC, Binutils, etc..) to do so, but i might be missing an easy way of doing it wi... | I would try getting an XML dump of the abstract syntax tree either from clang or from gccxml. From there you can easily extract the function declarations you are interested in.
|
4,421,962 | 4,421,972 | C++ operation overload, crash | Why does this code crash the program when I run it
ostream& operator<<(ostream& cout, Array<int> a) {
return cout;
}
and this doesn't
ostream& operator<<(ostream& cout, Array<int>& a) {
return cout;
}
| What does the copy constructor for Array<int> do ? See if reading the first answer to What is The Rule of Three? solves your problem (namely, that your class handles internally a pointer to a resource, but fails to perform a deep copy in its copy constructor, resulting in two instances deleting the same resource).
|
4,422,100 | 4,422,407 | Should I start targeting Clang / LLVM with my C++ iPhone project? | Apple is pushing LLVM and Clang a lot. Rumors say it's because Apple wants to drop GCC (due to problems with GPLv3 license), and switch to Clang.
Anybody has any idea about when it is going to happen?
I'm starting a C++ project which I'm planning to port on iPhone, and don't know whether I should use C++0x features (at... |
Rumors say it's because Apple wants to
drop GCC (due to problems with GPLv3
license), and switch to Clang.
This isn't a rumor, this is Apple's stated position. The GPL license on GCC prevents Apple from thoroughly integrating the compiler / parser within their development tools. With Clang / LLVM, they have no ... |
4,422,268 | 4,424,550 | How to do inverse real to real FFT in FFTW library | I'm trying to do some filtering with FFT. I'm using r2r_1d plan and I have no idea how to do the inverse transform...
void PerformFiltering(double* data, int n)
{
/* FFT */
double* spectrum = new double[n];
fftw_plan plan;
plan = fftw_plan_r2r_1d(n, data, spectrum, ... | http://www.fftw.org/fftw3_doc/Real_002dto_002dReal-Transform-Kinds.html
http://www.fftw.org/fftw3_doc/1d-Real_002deven-DFTs-_0028DCTs_0029.html
The "kind" specifies the direction.
(Note also that you'll probably want to renormalize your signal by dividing by n. The normalization convention of FFTW multiplies by n af... |
4,422,294 | 4,423,918 | Is manually simulating the effects of the delete operator in C++ formally illegal? | I realise this is ill-advised, and I'm not proposing to do it, but I'm curious as to whether the following is actually formally illegal:
#include <iostream>
struct X
{
~X()
{
std::cout << "~X()\n";
}
};
int main()
{
X *x = new X;
//delete x;
x->~X();
::operator delete(x);
retur... | I'm pretty sure that this is not standard compliant. Nowhere in the standard (that I'm aware of) does it say that the operand of delete p; is passed directly to the deallocation function, and for delete [] it almost certainly isn't passed through unchanged.
It will probably work on all practical implementations, howev... |
4,422,339 | 4,422,395 | Passing Int as void* then getting the value | I am using a Timer class that takes a void* as an optional arguement to pass to the callback. I need to pass an integer but my logic doesn't seem to be working out to well.
In Event_PlayerSpawn() I have a int* clientIndex that is pointing to the memory location of the int "client". I pass this into the void* param, and... | You need to allocate memory for variable. But for now it's in stack and destroyed when you leave Event_PlayerSpawn.
int *clientIndex = new int[1];
clientIndex[0] = client;
|
4,422,399 | 4,422,495 | Serialization of STL Class | is it possible serialize any STL class including std::string? I've a sets of std::strings and I'm trying to write them into file and load them back into std::set.
| Yes, it's possible. With boost.serialization, for example.
For STL, read corresponding tutorial section
|
4,422,488 | 4,422,592 | compiling someone else's vs c++ app - inconsistent linkage | hi
I am not a c++ developer and I'm trying to compile someone else's app. Build succeeds, but I get 5 'inconsistent dll linkage' warnings.
the dll builds but does not work in the same scenario in which the existing dll does. there have been no code changes.
after some googling, I assume it has to do with this, found ... | Right-click the project in the Solution Explorer window, Properties. Configuration Properties, C/C++, Preprocessor, Preprocessor Definitions setting. Verify that you see CPLAPPLET_PROGRAM_EXPORTS there. If you don't then add it.
It is also very likely that you'll need a .def file so that the export gets renamed. Ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.